一、硬件连线
micropython的SPI模块有硬件SPI和软件SPI区分。硬件SPI使用的是ESP32内部集成的SPI电路,而软件方式则是用程序来模拟SPI时序,实现SPI接口功能。
显然硬件SPI方式效率更高,所以驱动外部SPI设备时尽可能使用硬件SPI模块。但硬件SPI模块有引脚限制,引脚直连ESP32内部的SPI模块电路。
ESP32内部有两路硬件SPI电路,引脚分别为VSPI和HSPI,引脚如下图紫色和蓝色:

这里我们选择VSPI来连接,与SD卡的引脚连接如下表:
| SD板 |
ESP32开发板 | GPIO |
|---|---|---|
| GND | GND | |
| VCC | 5V | |
| CS | G5 | 5 |
| MOSI | G23 | 23 |
| SCK | G18 | 18 |
| MISO | G19 | 19 |
二、测试程序
1.SD卡的驱动模块,存为spiSdcard.py
"""
MicroPython driver for SD cards using SPI bus.
Requires an SPI bus and a CS pin. Provides readblocks and writeblocks
methods so the device can be mounted as a filesystem.
Example usage on pyboard:
import pyb, sdcard, os
sd = sdcard.SDCard(pyb.SPI(1), pyb.Pin.board.X5)
pyb.mount(sd, '/sd2')
os.listdir('/')
Example usage on ESP8266:
import machine, sdcard, os
sd = sdcard.SDCard(machine.SPI(1), machine.Pin(15))
os.mount(sd, '/sd')
os.listdir('/')
"""
from micropython import const
import time
_CMD_TIMEOUT = const(100)
_R1_IDLE_STATE = const(1 << 0)
# R1_ERASE_RESET = const(1 << 1)
_R1_ILLEGAL_COMMAND = const(1 << 2)
# R1_COM_CRC_ERROR = const(1 << 3)
# R1_ERASE_SEQUENCE_ERROR = const(1 << 4)
# R1_ADDRESS_ERROR = const(1 << 5)
# R1_PARAMETER_ERROR = const(1 << 6)
_TOKEN_CMD25 = const(0xFC)
_TOKEN_STOP_TRAN = const(0xFD)
_TOKEN_DATA = const(0xFE)
class SDCard:
def __init__(self, spi, cs, baudrate=1320000):
self.spi = spi
self.cs = cs
self.cmdbuf = bytearray(6)
self.dummybuf = bytearray(512)
self.tokenbuf = bytearray(1)
for i in range(512):
self.dummybuf[i] = 0xFF
self.dum

最低0.47元/天 解锁文章
538

被折叠的 条评论
为什么被折叠?



