Xiao ESP32S3 sense 基于micropython的内存卡读写(Xiao ESP32S3 sense is a micropython-based memory SDcard read/write)

micropython固件中 machine库提供了SDCard对象,我们可以快速的挂载SD卡
SDCard 的构造对象方法如下(The machine library in the micropython firmware provides SDCard objects that we can quickly mount an SD card
The following describes how SDCard constructs objects):
class machine.SDCard(slot=1, width=1, cd=None, wp=None, sck=None,miso=None, mosi=None, cs=None, freq=20000000)
使用示例(Example of use):SDCard(slot=2,width=8,sck=7, miso=8, mosi=9, cs=21)
slot=2,width=8这两个是固定传入参数,传入错误会无法读取SD卡(slot=2 and width=8 are fixed incoming parameters, and the incoming error will make the SD card unable to read),sck=7, miso=8, mosi=9, cs=21这几个是引脚配置,详细可查看xiao esp32s3 sense的引脚配置(SCK=7, MISO=8, MOSI=9, CS=21 are pin configurations, please refer to the pin configuration of Xiao ESP32S3 Sense for details):

ESP32-S3 GPIO SDCard
GPIO21 CS
D8 / A8 / Qt7 / GPIO7 SCK
D9 / A9 / Qt8 / GPIO8 MISO
D10 / A10 / Qt9 / GPIO9 MOSI

以下是我的boot.py代码(Code for boot.py):

try:
    from machine import SDCard
    import uos

    sd = SDCard(slot=2,width=8,sck=7, miso=8, mosi=9, cs=21)
    vfs = uos.VfsFat(sd)
    uos.mount(vfs, "/sd")
    uos.chdir("/sd")
    print(uos.listdir())
except:
    print(uos.listdir())

在micropython中boot.py是单片机上电后首先运行的脚本
在我的脚本中我创建SDCard对象后我使用 uos.VfsFat 类创建一个 FAT 文件系统对象然后我把/sd目录挂载到了系统中并且把当前工作目录切换到了/sd下,成功挂载SDCard后我们可以对SDCard进行读写操作(In MicroPython boot.py it is the script that runs first after the microcontroller is powered on
In my script, after I create the SDCard object, I use uos. VfsFat class creates a FAT file system object, then I mount the /sd directory to the system and switch the current working directory to /sd, after successfully mounting SDCard, we can read and write to SDCard)Example:

# 打开 test.txt 文件,如果 SD 卡目录没有会重新创建 test.txt 文件(Open the test.txt file, and if the SD card directory doesn't have one, the test.txt file will be recreated)
 with open("/sd/test.txt", "w") as f:
 for i in range(1, 50):
 # 从这个文件写数据( Write data from this file)
 f.write(str(i)+"\n")
 # 从 sd 卡目录下读取 test.txt 文件内容(Read the contents of the test.txt file from the SD card directory)
 with open("/sd/test.txt", "r") as f:
 # 打印读取的内容(Print the content of the read)
 print(f.read())

官方对于Xiao ESP32S3 sense的micropython编程的教程太少了,所以我希望自己写一份教程供大家参考,英文使用机器翻译有不对欢迎指正:)
There are too few official tutorials on Xiao ESP32S3 sense’s micropython programming, so I hope to write a tutorial for your reference:)

1 Like