ESP32 MicroPython SD 카드에 변수 저장
이 가이드는 ESP32와 MicroPython을 사용하여 마이크로 SD 카드에 다양한 유형의 MicroPython 변수를 저장하는 방법을 보여줍니다. 다루는 내용:
- ESP32와 MicroPython으로 마이크로 SD 카드에 문자열 값 저장하기.
- ESP32와 MicroPython으로 마이크로 SD 카드에 정수 값 저장하기.
- ESP32와 MicroPython으로 마이크로 SD 카드에 부동소수점 숫자 기록하기.
- ESP32와 MicroPython으로 마이크로 SD 카드에 바이트 배열 쓰기.
- ESP32와 MicroPython으로 마이크로 SD 카드에 키-값 형식으로 데이터 저장하기.
이 가이드는 마이크로 SD 카드에 다양한 변수 유형을 저장하는 완전한 방법을 제공하여 나중에 데이터를 쉽게 저장하고 검색할 수 있게 합니다. SD 카드에서 키-값 쌍을 읽어 정수, 소수, 문자열 유형으로 파싱해야 하는 경우 ESP32 MicroPython - SD 카드에서 설정 읽기 튜토리얼을 확인하세요.

필요한 하드웨어
| 1 | × | 38-pin ESP32 ESP-WROOM-32 Dev Module - Narrow | 쿠팡 | 아마존 | |
| 1 | × | (또는) 38-pin ESP32 ESP-WROOM-32 Dev Module - Wide | 쿠팡 | 아마존 | |
| 1 | × | (또는) 30-pin ESP32 ESP-WROOM-32 Dev Module - Wide | 아마존 | |
| 1 | × | (또는) ESP32 Uno-form board | 아마존 | |
| 1 | × | (또는) ESP32 S3 Uno-form board | 아마존 | |
| 1 | × | USB 케이블 타입-A to 타입-C (USB-A PC용) | 쿠팡 | 아마존 | |
| 1 | × | USB 케이블 타입-C to 타입-C (USB-C PC용) | 아마존 | |
| 1 | × | 마이크로 SD 카드 | 아마존 | |
| 1 | × | 마이크로 SD 카드 모듈 | 쿠팡 | 아마존 | |
| 1 | × | 점퍼케이블 | 쿠팡 | 아마존 | |
| 1 | × | (옵션) MicroSD to SD 메모리 카드 어댑터 | 아마존 | |
| 1 | × | (추천) ESP32용 스크루 터미널 확장 보드 | 쿠팡 | 아마존 | |
| 1 | × | (추천) Breakout Expansion Board for ESP32 | 쿠팡 | 아마존 | |
| 1 | × | (추천) ESP32용 전원 분배기 | 쿠팡 | 아마존 |
공개: 이 포스팅 에 제공된 일부 링크는 아마존 제휴 링크입니다. 이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
마이크로 SD 카드 모듈에 대하여
마이크로 SD 카드 모듈이 처음이신가요? ESP32 MicroPython - SD 카드 튜토리얼에서 핀, 작동 방법, 프로그래밍에 대한 모든 것을 알아보세요.
배선도

이 이미지는 Fritzing을 사용하여 만들어졌습니다. 이미지를 확대하려면 클릭하세요.
아래 배선표는 마이크로 SD 카드 모듈을 ESP32에 연결하는 방법을 보여줍니다:
| Micro SD Card Module | ESP32 |
|---|---|
| VCC | 5V |
| GND | GND |
| MISO | GPIO19 |
| MOSI | GPIO23 |
| SCK | GPIO18 |
| CS | GPIO5 |
※ 주의:
이더넷 실드 등 쉴드에 마이크로 SD 카드 슬롯이 내장되어 있는 경우, 외부 모듈을 생략하고 카드를 슬롯에 직접 삽입할 수 있습니다.
ESP32 MicroPython - 마이크로 SD 카드의 파일에 변수 저장하기
다음 MicroPython 코드는 다음 방법을 보여줍니다:
- 마이크로 SD 카드에 int 값 저장하기
- 마이크로 SD 카드에 float 값 저장하기
- 마이크로 SD 카드에 string 저장하기
- 마이크로 SD 카드에 byte array 저장하기
/*
* 이 ESP32 마이크로파이썬 코드는 newbiely.kr 에서 개발되었습니다
* 이 ESP32 마이크로파이썬 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다.
* 상세한 지침 및 연결도에 대해서는 다음을 방문하세요:
* https://newbiely.kr/tutorials/esp32-micropython/esp32-micropython-write-variable-to-sd-card
*/
import machine
import os
import sdcard
# Define SPI pins for the Micro SD Card module
SPI_SCK_PIN = 18 # The ESP32 pin GPIO18 connected to SCK
SPI_MOSI_PIN = 23 # The ESP32 pin GPIO23 connected to MOSI
SPI_MISO_PIN = 19 # The ESP32 pin GPIO19 connected to MISO
SPI_CS_PIN = 5 # The ESP32 pin GPIO5 connected to SS (CS)
# Initialize SD card using SoftSPI and sdcard driver
spi = machine.SoftSPI(baudrate=1000000, polarity=0, phase=0,
sck=machine.Pin(SPI_SCK_PIN),
mosi=machine.Pin(SPI_MOSI_PIN),
miso=machine.Pin(SPI_MISO_PIN))
cs = machine.Pin(SPI_CS_PIN, machine.Pin.OUT)
try:
sd = sdcard.SDCard(spi, cs)
os.mount(sd, "/sd")
print("SD CARD INITIALIZED.")
except Exception as e:
print("SD CARD FAILED, OR NOT PRESENT!", e)
raise SystemExit
print("--------------------")
file_path = "/sd/esp32.txt"
# Variables to write
my_int = -52
my_float = -12.7
my_string = "HELLO"
my_char_array = "newbiely.com"
my_byte_array = bytearray(b'12345')
# Delete the file if it exists
try:
os.remove(file_path)
except OSError:
pass
# Create new file and write variables
try:
f = open(file_path, "w")
f.write("{}\n".format(my_int)) # write int variable to SD card in line
f.write("{:.2f}\n".format(my_float)) # write float variable to SD card in line
f.write("{}\n".format(my_string)) # write string variable to SD card in line
f.write("{}\n".format(my_char_array)) # write char array to SD card in line
f.write(my_byte_array.decode()) # write byte array to SD card
f.write("\n") # new line
f.write(",".join(str(ch) for ch in my_byte_array.decode())) # write byte array with comma
f.write("\n") # new line
f.close()
except Exception as e:
print("SD Card: Issue encountered while attempting to open the file esp32.txt", e)
# Open file for reading
try:
f = open(file_path, "r")
while True:
ch = f.read(1) # read characters one by one from Micro SD Card
if not ch:
break
print(ch, end="") # print the character to the Shell
f.close()
except Exception as e:
print("SD Card: Issue encountered while attempting to open the file esp32.txt", e)
os.umount("/sd")
빠른 시작
Thonny IDE를 사용하여 ESP32에서 MicroPython 코드를 설정하고 실행하는 방법:
- Thonny IDE가 컴퓨터에 설치되어 있는지 확인합니다.
- ESP32 보드에 MicroPython 펌웨어가 로드되어 있는지 확인합니다.
- ESP32에서 MicroPython을 처음 사용하는 경우, ESP32 마이크로파이썬 - 시작하기 가이드를 참조하세요.
- 위 이미지에 따라 배선합니다.
- USB 케이블로 ESP32 보드를 컴퓨터에 연결합니다.
- 컴퓨터에서 Thonny IDE를 엽니다.
- Thonny IDE에서 Tools Options로 이동합니다.
- Interpreter 탭에서 드롭다운 메뉴의 MicroPython (ESP32)를 선택합니다.
- 올바른 포트가 선택되어 있는지 확인합니다. Thonny IDE가 자동으로 감지하지만, 수동으로 선택해야 할 수도 있습니다(Windows에서는 COM3, Linux에서는 /dev/ttyACM0).
- Thonny IDE의 Tools Manage packages로 이동합니다.
- "sdcard"를 검색하여 micropython-lib에서 제공하는 sdcard 라이브러리를 찾습니다.
- sdcard를 클릭한 후 Install 버튼을 클릭하여 SD 카드 라이브러리를 설치합니다.

- 마이크로 SD 카드가 FAT16 또는 FAT32로 포맷되어 있는지 확인합니다(필요한 경우 온라인에서 방법을 검색하세요).
- 제공된 MicroPython 코드를 복사하여 Thonny 편집기에 붙여넣습니다.
- 다음 방법으로 코드를 ESP32에 저장합니다:
- Save 버튼을 클릭하거나 Ctrl+S를 누릅니다.
- 저장 대화상자에서 MicroPython device를 선택합니다.
- 파일 이름을 main.py로 지정합니다.
- 녹색 Run 버튼을 클릭하거나 F5를 눌러 스크립트를 실행합니다.
- Thonny 하단의 Shell 메시지를 확인합니다.
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot
SD CARD INITIALIZED.
--------------------
-52
-12.70
HELLO
newbiely.com
12345
1,2,3,4,5
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡
- 모듈에서 마이크로 SD 카드를 꺼냅니다.
- USB SD 카드 리더기에 꽂아 PC에 연결합니다.
- PC에서 esp32.txt 파일을 열면 다음과 같은 내용이 표시됩니다:

ESP32 MicroPython - 마이크로 SD 카드에 키-값 쌍 저장하기
/*
* 이 ESP32 마이크로파이썬 코드는 newbiely.kr 에서 개발되었습니다
* 이 ESP32 마이크로파이썬 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다.
* 상세한 지침 및 연결도에 대해서는 다음을 방문하세요:
* https://newbiely.kr/tutorials/esp32-micropython/esp32-micropython-write-variable-to-sd-card
*/
import machine
import os
import sdcard
# Define SPI pins for the Micro SD Card module
SPI_SCK_PIN = 18 # The ESP32 pin GPIO18 connected to SCK
SPI_MOSI_PIN = 23 # The ESP32 pin GPIO23 connected to MOSI
SPI_MISO_PIN = 19 # The ESP32 pin GPIO19 connected to MISO
SPI_CS_PIN = 5 # The ESP32 pin GPIO5 connected to SS (CS)
# Initialize SD card using SoftSPI and sdcard driver
spi = machine.SoftSPI(baudrate=1000000, polarity=0, phase=0,
sck=machine.Pin(SPI_SCK_PIN),
mosi=machine.Pin(SPI_MOSI_PIN),
miso=machine.Pin(SPI_MISO_PIN))
cs = machine.Pin(SPI_CS_PIN, machine.Pin.OUT)
try:
sd = sdcard.SDCard(spi, cs)
os.mount(sd, "/sd")
print("SD CARD INITIALIZED.")
except Exception as e:
print("SD CARD FAILED, OR NOT PRESENT!", e)
raise SystemExit
print("--------------------")
file_path = "/sd/esp32.txt"
# Variables to write
my_int = -52
my_float = -12.7
my_string = "HELLO"
my_char_array = "newbiely.com"
my_byte_array = bytearray(b'12345')
# Delete the file if it exists
try:
os.remove(file_path)
except OSError:
pass
# Create new file and write key-value pairs
try:
f = open(file_path, "w")
f.write("myInt={}\n".format(my_int)) # write key=int to SD card
f.write("myFloat={:.2f}\n".format(my_float)) # write key=float to SD card
f.write("myString={}\n".format(my_string)) # write key=string to SD card
f.write("myCharArray={}\n".format(my_char_array)) # write key=char array to SD card
f.write("myByteArray={}\n".format(my_byte_array.decode())) # write key=byte array
f.write("myByteArray2={}\n".format(",".join(str(ch) for ch in my_byte_array.decode()))) # write key=byte array with comma
f.close()
except Exception as e:
print("SD Card: Issue encountered while attempting to open the file esp32.txt", e)
# Open file for reading
try:
f = open(file_path, "r")
while True:
ch = f.read(1) # read characters one by one from Micro SD Card
if not ch:
break
print(ch, end="") # print the character to the Shell
f.close()
except Exception as e:
print("SD Card: Issue encountered while attempting to open the file esp32.txt", e)
os.umount("/sd")
빠른 시작
- 위 코드를 복사하여 Thonny 편집기에 붙여넣습니다.
- 녹색 Run 버튼을 클릭하거나 F5를 눌러 스크립트를 실행합니다.
- Thonny 하단의 Shell 출력을 확인합니다.
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot
SD CARD INITIALIZED.
--------------------
myInt=-52
myFloat=-12.70
myString=HELLO
myCharArray=newbiely.com
myByteArray=12345
myByteArray2=1,2,3,4,5
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡
- 모듈에서 마이크로 SD 카드를 꺼냅니다.
- USB SD 카드 리더기를 사용하여 PC에 연결합니다.
- Esp32.txt 파일을 열면 다음과 같은 내용이 표시됩니다:

동영상
비디오 제작은 시간이 많이 걸리는 작업입니다. 비디오 튜토리얼이 학습에 도움이 되었다면, YouTube 채널 을 구독하여 알려 주시기 바랍니다. 비디오에 대한 높은 수요가 있다면, 비디오를 만들기 위해 노력하겠습니다.