라즈베리 파이 피코 SD 카드에 변수 쓰기

이 가이드는 Raspberry Pi Pico를 사용하여 Micro SD 카드에 데이터를 저장하는 방법을 보여줍니다. 다음에 대해 논의할 것입니다:

Raspberry Pi Pico에서 Micro SD 카드로부터 키-값을 읽어 int, float 또는 문자열 형식으로 변환하는 방법을 알아보려면, 라즈베리 파이 피코 - SD 카드에서 설정 읽기를 방문하세요.

라즈베리 파이 피코 마이크로 sd 카드

준비물

1×라즈베리 파이 피코 W 쿠팡 | 아마존
1×라즈베리 파이 피코 (또는) 쿠팡 | 아마존
1×마이크로 USB 케이블 아마존
1×마이크로 SD 카드 아마존
1×마이크로 SD 카드 모듈 쿠팡 | 아마존
1×점퍼케이블 쿠팡 | 아마존
1×(옵션) MicroSD to SD 메모리 카드 어댑터 아마존
1×(추천) 라즈베리 파이 피코용 스크루 터미널 확장 보드 아마존
공개: 이 포스팅 에 제공된 일부 링크는 아마존 제휴 링크입니다. 이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

마이크로 SD 카드 모듈 소개

Micro SD 카드 모듈(핀 구성, 사용법 및 프로그래밍 방법에 대한 자세한 내용)에 대한 정보는 라즈베리 파이 피코 - 마이크로 SD 카드 가이드를 확인하세요.

선연결

라즈베리 파이 피코 마이크로 sd 카드 모듈 배선도

이 이미지는 Fritzing을 사용하여 만들어졌습니다. 이미지를 확대하려면 클릭하세요.

※ 주의:

이더넷 쉴드 또는 Micro SD 카드 보유기가 있는 다른 쉴드를 보유하고 있다면, 별도의 Micro SD 카드 모듈이 필요하지 않습니다. 단순히 Micro SD 카드를 쉴드의 보유기에 삽입하면 됩니다.

라즈베리 파이 파이코 - 마이크로 SD 카드의 파일에 변수를 쓰는 방법

아래 코드는 다음 작업을 수행합니다:

  • 마이크로 SD 카드에 정수 저장
  • 마이크로 SD 카드에 실수 저장
  • 마이크로 SD 카드에 텍스트 저장
  • 마이크로 SD 카드에 문자열 저장
  • 마이크로 SD 카드에 바이트 배열 저장
/* * 이 라즈베리 파이 피코 코드는 newbiely.kr 에서 개발되었습니다 * 이 라즈베리 파이 피코 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/raspberry-pico/raspberry-pi-pico-write-variable-to-sd-card */ import machine import os import sdcard # Define SPI pins for the Micro SD Card module SPI_SCK_PIN = 2 # The Raspberry Pi Pico pin GP2 connected to SCK SPI_MOSI_PIN = 3 # The Raspberry Pi Pico pin GP3 connected to MOSI SPI_MISO_PIN = 4 # The Raspberry Pi Pico pin GP4 connected to MISO SPI_CS_PIN = 5 # The Raspberry Pi Pico pin GP5 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/pico.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 pico.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 pico.txt", e) os.umount("/sd")

자세한 사용 방법

다음 지침을 단계별로 따르세요:

  • 컴퓨터에 Thonny IDE가 설치되어 있는지 확인합니다.
  • Raspberry Pi Pico에 MicroPython 펌웨어가 설치되어 있는지 확인합니다.
  • Raspberry Pico 사용이 처음이라면 자세한 설명은 라즈베리 파이 피코 - 시작하기 튜토리얼을 참고하세요.
  • 제공된 회로도에 따라 부품들을 연결합니다.
  • USB 케이블을 사용하여 Raspberry Pi Pico를 컴퓨터에 연결합니다.
  • 컴퓨터에서 Thonny IDE를 실행합니다.
  • Thonny IDE에서 도구 옵션으로 이동하여 MicroPython (Raspberry Pi Pico) 인터프리터를 선택합니다.
  • Interpreter 탭에서 드롭다운 메뉴에서 MicroPython (Raspberry Pi Pico)를 선택합니다.
  • 올바른 포트가 선택되었는지 확인합니다. Thonny IDE는 포트를 자동으로 감지하지만, 필요에 따라 직접 선택할 수도 있습니다 (예: Windows의 COM3 또는 Linux의 /dev/ttyACM0).
  • 위 코드를 복사하여 Thonny IDE의 에디터에 붙여넣습니다.
  • Raspberry Pi Pico에 스크립트를 저장합니다:
    • Save 버튼을 클릭하거나 Ctrl+S 키를 사용합니다.
    • 저장 대화 상자에서 두 개의 섹션(이 컴퓨터 및 Raspberry Pi Pico)이 표시됩니다. Raspberry Pi Pico를 선택합니다.
    • 파일 이름을 main.py로 저장합니다.
  • 초록색 실행 버튼을 클릭하거나 F5 키를 눌러 스크립트를 실행합니다. 스크립트가 실행됩니다.
  • Thonny 하단의 Shell에서 메시지를 확인합니다.

스크립트의 이름을 main.py로 지정하고 Raspberry Pi Pico의 루트 디렉토리에 저장하면, Pico 전원 공급 또는 리셋 시마다 자동으로 실행됩니다. 이는 전원이 켜지는 즉시 실행되어야 하는 독립 실행형 응용 프로그램에 유용합니다. 만약 스크립트의 이름을 main.py 이외의 다른 이름으로 지정하면, Thonnys의 셸에서 수동으로 실행해야 합니다.

  • Micro SD 카드를 FAT16 또는 FAT32로 포맷합니다 (온라인에서 지침을 확인하세요)
  • 제공된 코드를 복사하여 Thonny IDE에서 엽니다
  • Thonny IDE에서 Upload 버튼을 클릭하여 코드를 Raspberry Pi Pico로 전송합니다
  • 시리얼 모니터에서 결과를 확인합니다
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot SD CARD INITIALIZED. -------------------- -52 -12.70 HELLO Raspberry Pi PicoGetStarted.com 12345 1,2,3,4,5
MicroPython (Raspberry Pi Pico) • Board CDC @ COM29 ≡
  1. 구성 요소에서 마이크로 SD 카드를 꺼내십시오.
  2. 마이크로 SD 카드를 USB SD 카드 리더기에 삽입하십시오.
  3. USB SD 카드 리더기를 컴퓨터에 연결하십시오.
  4. 컴퓨터에서 arduino.txt 파일을 여십시오.
라즈베리 파이 피코가 변수를 micro sd 카드에 기록합니다.

Raspberry Pi Pico - Micro SD 카드에 키-값을 파일에 기록하는 방법

/* * 이 라즈베리 파이 피코 코드는 newbiely.kr 에서 개발되었습니다 * 이 라즈베리 파이 피코 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/raspberry-pico/raspberry-pi-pico-write-variable-to-sd-card */ import machine import os import sdcard # Define SPI pins for the Micro SD Card module SPI_SCK_PIN = 2 # The Raspberry Pi Pico pin GP2 connected to SCK SPI_MOSI_PIN = 3 # The Raspberry Pi Pico pin GP3 connected to MOSI SPI_MISO_PIN = 4 # The Raspberry Pi Pico pin GP4 connected to MISO SPI_CS_PIN = 5 # The Raspberry Pi Pico pin GP5 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/pico.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 pico.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 pico.txt", e) os.umount("/sd")

자세한 사용 방법

  • 위 코드를 복사하여 Thonny IDE에서 엽니다.
  • Thonny IDE에서 Upload 버튼을 클릭하여 Raspberry Pi Pico로 코드를 전송합니다.
  • 시리얼 모니터에서 결과를 확인합니다.
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot SD CARD INITIALIZED. -------------------- myInt=-52 myFloat=-12.70 myString=HELLO myCharArray=Raspberry Pi PicoGetStarted.com myByteArray=12345 myByteArray2=1,2,3,4,5
MicroPython (Raspberry Pi Pico) • Board CDC @ COM29 ≡
  • 마이크로 SD 카드를 슬롯에서 꺼내십시오. 마이크로 SD 카드를 USB SD 카드 리더기에 삽입하십시오. USB SD 카드 리더기를 컴퓨터에 연결하십시오. 컴퓨터에서 arduino.txt라는 파일을 찾아 열어보십시오; 언급된 대로 표시될 것입니다.
라즈베리 파이 파이코가 변수를 마이크로 sd 카드에 기록합니다.

동영상

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