=============================
This project is essentially a FreeRTOS+FAT Media Driver for the Raspberry Pi Pico, using Serial Peripheral Interface (SPI), based on SDBlockDevice from Mbed OS 5, and/or a 4-bit Secure Digital Input Output (SDIO) driver derived from ZuluSCSI-firmware. It is wrapped up in a complete runnable project, with a little command line interface, some self tests, and an example data logging application.
Ported to SDK 2 and Pico 2.
Add support for running without Chip Select (CS) (formerly Slave Select [SS]).
spi_mode
to the hardware configuration.
For SPI attached cards, SPI Mode 3 can significantly improve performance.
See SPI Controller Configuration.sd_read_blocks
sd_write_blocks
in sd_card_spi.c
Pick up Lab-Project-FreeRTOS-FAT bug fix: Add missing error check #68. The bug could cause a memory overwrite if the Media Driver returned an error.
Fix bug in SPI sd_write_blocks that caused single block writes to be sent with CMD25 WRITE_MULTIPLE_BLOCK instead of CMD24 WRITE_BLOCK.
sd_sync
. get_num_sectors
.
This error was visible in bench
in the reported disk capacity.command_line
example: Run big_file_test
in separate task.
This frees up the CLI to run commands like run-time-stats
.
rp2040_sdio_tx_poll
called the DMA IRQ handler for any exception to "Verify that IRQ handler gets called even if we are in hardfault handler".
However, it was using a mask for all exceptions, including PendSV and SysTick which are normal in FreeRTOS. This occasionally caused writes to fail with a CRC error.rp2040_sdio_stop
always disabled the channel on DMA_IRQ_1.command_line
example: Use the RTOS Daemon (Timer Service) Task instead of a separate task to execute unmount request from card detect interrupt
Pick up Lab-Project-FreeRTOS-FAT Fix dynamic FAT variant detection
Implement ACMD42_SET_CLR_CARD_DETECT
:
At power up the CS/DAT3 line has a 50KOhm pull up enabled in the SD card.
This resistor serves two functions: Card detection and Mode Selection.
This pull-up should be disconnected by the user, during regular data transfer,
with SET_CLR_CARD_DETECT (ACMD42) command.
command_line
example enhancements:
info
enhanced to report SD card Allocation Unit (AU_SIZE) or "segment" (available only on SDIO-attached cards)format
now creates a single primary partition and attempts to align this on an SD card segment.
FreeRTOS-Kernel
removed as a submodule of this library.
It should be up to the application to manage the FreeRTOS library.
There is some increased risk of incompatibilities with FreeRTOS versions with this change.
See Dependencies.FreeRTOSFATConfig.h
and FreeRTOSFATConfig.h
configuration files
have been removed from this library.
These are for application specific customization and should be provided by the application,
not the library.
However, examples are provided in the example applications in the examples
directory.
See Other Application-Specific Customization.
configNUM_CORES
got renamed to configNUMBER_OF_CORES
in FreeRTOS,
so SMP was not working in v2.0.0.For required migration actions, see Appendix A: Migration actions.
Note: Release 1 remains available on the v1.0.0 branch.
dma_claim_unused_channel
.irq_add_shared_handler
or irq_set_exclusive_handler
(configurable) and enabled.dma_claim_unused_channel
irq_add_shared_handler
or irq_set_exclusive_handler
(configurable) and enabled.SPI and SDIO can share the same DMA IRQ.
For the complete
examples/command_line application,
configured for oneSDIO-attached card, MinSizeRel
build,
as reported by link flag -Wl,--print-memory-usage
:
[build] Memory region Used Size Region Size %age Used
[build] FLASH: 160400 B 2 MB 7.65%
[build] RAM: 221584 B 256 KB 84.53%
The high RAM consumption is because I chose to devote 192 kB to the FreeRTOS Heap4:
#define configTOTAL_HEAP_SIZE 192 * 1024
in FreeRTOSConfig.h on the theory that if you're running FreeRTOS, you're more likely to use pvPortMalloc() than malloc(). mount
ing the SD card takes 2504 bytes of heap. After running the cvef
(Create and Verify Example Files) test:
> heap-stats
Configured total heap size: 196608
Free bytes in the heap now: 193480
Minimum number of unallocated bytes that have ever existed in the heap: 192424
so the maximum heap utilization was 4184 bytes, or about 1.6 % of the Pico's RAM.
Writing and reading a file of 200 MiB of psuedorandom data on the same
Silicon Power 3D NAND U1 32GB microSD card inserted into a
Pico Stackable, Plug & Play SD Card Expansion Module
at the default Pico system clock frequency (clk_sys
) of 125 MHz, MinSizeRel
build, using the command
big_file_test bf 200 x.
once on SPI and one on SDIO.
SDIO, baud rate 31,250,000 Hz:
SPI, baud rate, baud rate 31,250,000 Hz:
Results from a port of SdFat's bench:
...
write speed and latency
speed,max,min,avg
KB/Sec,usec,usec,usec
10922.7,12672,5723,5992
11397.6,6009,5704,5752
...
read speed and latency
speed,max,min,avg
KB/Sec,usec,usec,usec
13273.1,4964,4907,4932
13306.8,4940,4907,4918
...
...
write speed and latency
speed,max,min,avg
KB/Sec,usec,usec,usec
2463.8,41867,26204,26594
2491.9,26558,26175,26296
...
read speed and latency
speed,max,min,avg
KB/Sec,usec,usec,usec
2359.5,27882,27664,27766
2361.7,27847,27675,27758
...
For high data rate applications, it is possible to obtain higher write and read speeds by writing or reading to multiple SD cards simultaneously.
For example, using the command mtbft 80 /sd0/bf to write a 80 MiB file to a single SDIO-attached SD card, I got a transfer rate of 6.46 MiB/s.
Using the command mtbft 40 /sd0/bf /sd3/bf to write 40 MiB files on two SDIO-attached SD cards, I got a transfer rate of 12.4 MiB/s.
(This test includes the time to fill or check the buffer in the transfer rate calculation, so the actual write or read performance is higher.)
This gives a speedup of about 1.9 X for two cards vs a single card.
The main reason to use SDIO is for the much greater speed that the 4-bit wide interface gets you. However, you pay for that in pins. SPI can get by with four GPIOs for the first card and one more for each additional card. SDIO needs at least six GPIOs, and the 4 bits of the data bus have to be on consecutive GPIOs. It is possible to put more than one card on an SDIO bus (each card has an address in the protocol), but at the higher speeds (higher than this implementation can do) the tight timing requirements don't allow it. I haven't tried it. Running multiple SD cards on multiple SDIO buses works, but it does require a lot of pins and PIO resources.
You can mix and match the attachment types. One strategy: use SDIO for cache and SPI for backing store. A similar strategy that I have used: SDIO for fast, interactive use, and SPI to offload data.
There are a variety of RP2040 boards on the market that provide an integrated µSD socket. As far as I know, most are useable with this library.
Prerequisites:
Raspberry Pi Pico or some other kind of RP2040 board
Something like the Adafruit Micro SD SPI or SDIO Card Breakout Board[^3] or SparkFun microSD Transflash Breakout
Warning: Avoid Aduino breakout boards like these: Micro SD Storage Board Micro SD Card Modules. They are designed for 5 V Arduino signals. Many use simple resistor dividers to drop the signal voltage, and will not work properly with the 3.3 V Raspberry Pi Pico. However, see The 5V Arduino SD modules might work with a simple trick.
Breadboard and wires
Raspberry Pi Pico C/C++ SDK
(Optional) A couple of ~10 kΩ - 50 kΩ resistors for pull-ups
(Optional) 100 nF, 1 µF, and 10 µF capacitors for decoupling
(Optional) 22 µH inductor for decoupling
Please see here for an example wiring table for an SPI attached card and an SDIO attached card on the same Pico. SPI and SDIO at 31.5 MHz are pretty demanding electrically. You need good, solid wiring, especially for grounds. A printed circuit board with a ground plane would be nice!
gpio_pull_up
is weak: around 56uA or 60kΩ.
If a pull up is needed, it's best to add an external pull up resistor of around 5-50 kΩ to 3.3v.
The internal gpio_pull_up
can be disabled in the hardware configuration by setting the no_miso_gpio_pull_up
attribute of the spi_t
object.If you have only one SD card, and you are short on GPIOs, you may be able to run without CS/SS. I know of no guarantee that this will work for all SD cards. The Physical Layer Simplified Specification says
Every command or data block is built of 8-bit bytes and is byte aligned with the CS signal... The card starts to count SPI bus clock cycle at the assertion of the CS signal... The host starts every bus transaction by asserting the CS signal low.
It doesn't say what happens if the CS signal is always asserted. However, it worked for me with:
You will need to pull down the CS/SS line on the SD card with hardware. (I.e., connect CS to GND. CS is active low.)
In the hardware configuration definition, set ss_gpio
to -1.
See An instance of sd_spi_if_t
describes the configuration of one SPI to SD card interface..
-DFREERTOS_KERNEL_PATH=/path/to/FreeRTOS-Kernel
on the CMake
command line
to point to the installation.
See FreeRTOS-Kernel/portable/ThirdParty/GCC/RP2040/.--recurse-submodules
.git clone --recurse-submodules https://github.com/carlk3/FreeRTOS-FAT-CLI-for-RPi-Pico.git FreeRTOS+FAT+CLI
pico_enable_stdio_uart
and pico_enable_stdio_usb
in CMakeLists.txt as you prefer.
(See 4.1. Serial input and output on Raspberry Pi Pico in Getting started with Raspberry Pi Pico and 2.7.1. Standard Input/Output (stdio) Support in Raspberry Pi Pico C/C++ SDK.) cd FreeRTOS+FAT+CLI/examples/command_line
mkdir build
cd build
cmake ..
make
command_line
example for operation.
This library can support many different hardware configurations.
Therefore, the hardware configuration is not defined in the library.
Instead, the application must provide it.
The configuration is defined in "objects" of type spi_t
(see sd_driver/spi.h
),
sd_spi_if_t
, sd_sdio_if_t
, and sd_card_t
(see sd_driver/sd_card.h
).
sd_card_t
describe the configuration of SD card sockets.sd_card_t
is associated (one to one) with an sd_spi_if_t
or sd_sdio_if_t
interface object,
and points to it with spi_if_p
or sdio_if_p
[^5].sdio_if_p
specify the configuration of an SDIO/PIO interface.sd_spi_if_t
is assocated (many to one) with an instance of spi_t
and points to it with spi_t *spi
. (It is a many to one relationship because multiple SD cards can share a single SPI bus, as long as each has a unique slave (or "chip") select (SS, or "CS") line.) It describes the configuration of a specific SD card's interface to a specific SPI hardware component.spi_t
describe the configuration of the RP2040 SPI hardware components used.
There can be multiple objects (or "instances") of all three types.
Attributes (or "fields", or "members") of these objects specify which pins to use for what, baud rates, features like Card Detect, etc.0
or false
. (This is the user's responsibility if using Dynamic Configuration, but in a Static Configuration
[see Static vs. Dynamic Configuration],
the C runtime initializes static memory to 0.)Illustration of the configuration dev_brd.hw_config.c
sd_card_t
describes the configuration of one SD card socketstruct sd_card_t {
const char *device_name;
const char *mount_point; // Must be a directory off the file system's root directory and must be an absolute path that starts with a forward slash (/)
sd_if_t type;
union {
sd_spi_if_t *spi_if_p;
sd_sdio_if_t *sdio_if_p;
};
bool use_card_detect;
uint card_detect_gpio; // Card detect; ignored if !use_card_detect
uint card_detected_true; // Varies with card socket; ignored if !use_card_detect
bool card_detect_use_pull;
bool card_detect_pull_hi;
//...
}
device_name
Device name. This is arbitrary, but if the string contains spaces the command_line
example will have problems with it. This is the name that you pass to the mount
command or the FF_SDDiskInit
API call.mount_point
An absolute path that specifies a directory off the file system's root directory where the SD card will appear after it is mounted and addedtype
Type of interface: either SD_IF_SPI
or SD_IF_SDIO
spi_if_p
or sdio_if_p
Pointer to the instance sd_spi_if_t
or sd_sdio_if_t
that drives this SD carduse_card_detect
Whether or not to use Card Detect, meaning the hardware switch featured on some SD card sockets. This requires a GPIO pin.card_detect_gpio
Ignored if not use_card_detect
. GPIO number of the Card Detect, connected to the SD card socket's Card Detect switch (sometimes marked DET)card_detected_true
Ignored if not use_card_detect
. What the GPIO read returns when a card is present (Some sockets use active high, some low)card_detect_use_pull
Ignored if not use_card_detect
. If true, use the card_detect_gpio
's pad's Pull Up / Pull Down resistors;
if false, no pull resistor is applied.
Often, a Card Detect Switch is just a switch to GND or Vdd,
and you need a resistor to pull it one way or the other to make logic levels.card_detect_pull_hi
Ignored if not use_card_detect
. Ignored if not card_detect_use_pull
. Otherwise, if true, pull up; if false, pull down.sd_sdio_if_t
describes the configuration of one SDIO to SD card interface.typedef struct sd_sdio_if_t {
// See sd_driver\SDIO\rp2040_sdio.pio for SDIO_CLK_PIN_D0_OFFSET
uint CLK_gpio; // Must be (D0_gpio + SDIO_CLK_PIN_D0_OFFSET) % 32
uint CMD_gpio;
uint D0_gpio; // D0
uint D1_gpio; // Must be D0 + 1
uint D2_gpio; // Must be D0 + 2
uint D3_gpio; // Must be D0 + 3
PIO SDIO_PIO; // either pio0 or pio1
uint DMA_IRQ_num; // DMA_IRQ_0 or DMA_IRQ_1
bool use_exclusive_DMA_IRQ_handler;
uint baud_rate;
// Drive strength levels for GPIO outputs:
// GPIO_DRIVE_STRENGTH_2MA
// GPIO_DRIVE_STRENGTH_4MA
// GPIO_DRIVE_STRENGTH_8MA
// GPIO_DRIVE_STRENGTH_12MA
bool set_drive_strength;
enum gpio_drive_strength CLK_gpio_drive_strength;
enum gpio_drive_strength CMD_gpio_drive_strength;
enum gpio_drive_strength D0_gpio_drive_strength;
enum gpio_drive_strength D1_gpio_drive_strength;
enum gpio_drive_strength D2_gpio_drive_strength;
enum gpio_drive_strength D3_gpio_drive_strength;
//...
} sd_sdio_t;
Specify D0_gpio
, but pins CLK_gpio
, D1_gpio
, D2_gpio
, and D3_gpio
are at offsets from pin D0_gpio
and are set implicitly.
The offsets are determined by sd_driver\SDIO\rp2040_sdio.pio
.
As of this writing, SDIO_CLK_PIN_D0_OFFSET
is 30,
which is -2 in mod32 arithmetic, so:
These pin assignments are set implicitly and must not be set explicitly.
CLK_gpio
RP2040 GPIO to use for Clock (CLK).
Implicitly set to (D0_gpio + SDIO_CLK_PIN_D0_OFFSET) % 32
where SDIO_CLK_PIN_D0_OFFSET
is defined in sd_driver/SDIO/rp2040_sdio.pio
.
As of this writing, SDIO_CLK_PIN_D0_OFFSET
is 30, which is -2 in mod32 arithmetic, so:
CMD_gpio
RP2040 GPIO to use for Command/Response (CMD)
D0_gpio
RP2040 GPIO to use for Data Line [Bit 0]. The PIO code requires D0 - D3 to be on consecutive GPIOs, with D0 being the lowest numbered GPIO.
D1_gpio
RP2040 GPIO to use for Data Line [Bit 1]. Implicitly set to D0_gpio + 1.
D2_gpio
RP2040 GPIO to use for Data Line [Bit 2]. Implicitly set to D0_gpio + 2.
D3_gpio
RP2040 GPIO to use for Card Detect/Data Line [Bit 3]. Implicitly set to D0_gpio + 3.
SDIO_PIO
Which PIO block to use. Defaults to pio0
. Can be changed to avoid conflicts.
If you try to use multiple SDIO-attached SD cards simultaneously on the same PIO block,
contention might lead to timeouts.
DMA_IRQ_num
Which IRQ to use for DMA. Defaults to DMA_IRQ_0. Set this to avoid conflicts with any exclusive DMA IRQ handlers that might be elsewhere in the system.
use_exclusive_DMA_IRQ_handler
If true, the IRQ handler is added with the SDK's irq_set_exclusive_handler
. The default is to add the handler with irq_add_shared_handler
, so it's not exclusive.
baud_rate
The frequency of the SDIO clock in Hertz. This may be no higher than the system clock frequency divided by CLKDIV
in sd_driver\SDIO\rp2040_sdio.pio
, which is currently four. For example, if the system clock frequency is 125 MHz, baud_rate
cannot exceed 31250000 (31.25 MHz). The default is 10 MHz.
This is used to divide the system clock frequency (clk_sys
) to get a ratio to pass to the SDK's sm_config_set_clkdiv. As it says there, "An integer clock divisor of n will cause the state machine to run 1 cycle in every n. Note that for small n, the jitter introduced by a fractional divider (e.g. 2.5) may be unacceptable although it will depend on the use case."
In this case, n can be as little as four (which I would consider small).
The fractional divider essentially causes the frequency to vary in a range,
with the average being the requested frequency.
If the hardware is capable of running at the high end of the range,
you might as well run at that frequency all the time.
Therefore, I recommend choosing a baud rate that is some factor of the system clock frequency.
For example, if the system clock frequency is the default 125 MHz:
.baud_rate = 125 * 1000 * 1000 / 10, // 12500000 Hz
or
.baud_rate = 125 * 1000 * 1000 / 4 // 31250000 Hz
The higher the baud rate, the faster the data transfer. However, the hardware might limit the usable baud rate. See Pull Up Resistors and other electrical considerations.
set_drive_strength
If true, enable explicit specification of output drive strengths on CLK_gpio
, CMD_gpio
, and D0_gpio
- D3_gpio
.
The GPIOs on RP2040 have four different output drive strengths, which are nominally 2, 4, 8 and 12mA modes.
If set_drive_strength
is false, all will be implicitly set to 4 mA.
If set_drive_strength
is true, each GPIO's drive strength can be set individually. Note that if it is not explicitly set, it will default to 0, which equates to GPIO_DRIVE_STRENGTH_2MA
(2 mA nominal drive strength).
CLK_gpio_drive_strength
CMD_gpio_drive_strength
D0_gpio_drive_strength
D1_gpio_drive_strength
D2_gpio_drive_strength
D3_gpio_drive_strength
Ignored if set_drive_strength
is false. Otherwise, these can be set to one of the following:
GPIO_DRIVE_STRENGTH_2MA
GPIO_DRIVE_STRENGTH_4MA
GPIO_DRIVE_STRENGTH_8MA
GPIO_DRIVE_STRENGTH_12MA
You might want to do this for electrical tuning. A low drive strength can give a cleaner signal, with less overshoot and undershoot. In some cases, this allows operation at higher baud rates. In other cases, the signal lines might have a lot of capacitance to overcome. Then, a higher drive strength might allow operation at higher baud rates. A low drive strength generates less noise. This might be important in, say, audio applications.
sd_spi_if_t
describes the configuration of one SPI to SD card interface.typedef struct sd_spi_if_t {
spi_t *spi;
// Slave select is here instead of in spi_t because multiple SDs can share an SPI.
uint ss_gpio; // Slave select for this SD card
// Drive strength levels for GPIO outputs:
// GPIO_DRIVE_STRENGTH_2MA
// GPIO_DRIVE_STRENGTH_4MA
// GPIO_DRIVE_STRENGTH_8MA
// GPIO_DRIVE_STRENGTH_12MA
bool set_drive_strength;
enum gpio_drive_strength ss_gpio_drive_strength;
} sd_spi_if_t;
spi
Points to the instance of spi_t
that is to be used as the SPI to drive this interfacess_gpio
Slave Select (SS) (or "Chip Select [CS]") GPIO for the SD card socket associated with this interface.
Set this to -1 to disable it.
(See Running without Chip Select (CS) (formerly Slave Select [SS]).)
Note: 0 is a valid GPIO number, so you must explicitly set it to -1 to disable it.set_drive_strength
Enable explicit specification of output drive strength of ss_gpio_drive_strength
.
If false, the GPIO's drive strength will be implicitly set to 4 mA.ss_gpio_drive_strength
Drive strength for the SS (or CS).
Ignored if set_drive_strength
is false. Otherwise, it can be set to one of the following:
GPIO_DRIVE_STRENGTH_2MA
GPIO_DRIVE_STRENGTH_4MA
GPIO_DRIVE_STRENGTH_8MA
GPIO_DRIVE_STRENGTH_12MA
An instance of spi_t
describes the configuration of one RP2040 SPI controller.
typedef struct spi_t {
spi_inst_t *hw_inst; // SPI HW
uint miso_gpio; // SPI MISO GPIO number (not pin number)
uint mosi_gpio;
uint sck_gpio;
uint baud_rate;
/* The different modes of the Motorola SPI protocol are:
- Mode 0: When CPOL and CPHA are both 0, data sampled at the leading rising edge of the
clock pulse and shifted out on the falling edge. This is the most common mode for SPI bus
communication.
- Mode 1: When CPOL is 0 and CPHA is 1, data sampled at the trailing falling edge and
shifted out on the rising edge.
- Mode 2: When CPOL is 1 and CPHA is 0, data sampled at the leading falling edge
and shifted out on the rising edge.
- Mode 3: When CPOL is 1 and CPHA is 1, data sampled at the trailing rising edge and
shifted out on the falling edge. */
uint spi_mode;
uint DMA_IRQ_num; // DMA_IRQ_0 or DMA_IRQ_1
bool use_exclusive_DMA_IRQ_handler;
bool no_miso_gpio_pull_up;
/* Drive strength levels for GPIO outputs:
GPIO_DRIVE_STRENGTH_2MA,
GPIO_DRIVE_STRENGTH_4MA,
GPIO_DRIVE_STRENGTH_8MA,
GPIO_DRIVE_STRENGTH_12MA */
bool set_drive_strength;
enum gpio_drive_strength mosi_gpio_drive_strength;
enum gpio_drive_strength sck_gpio_drive_strength;
// State variables:
// ...
} spi_t;
hw_inst
Identifier for the hardware SPI instance (for use in SPI functions). e.g. spi0
, spi1
, declared in pico-sdk\src\rp2_common\hardware_spi\include\hardware\spi.h
miso_gpio
SPI Master In, Slave Out (MISO) (also called "CIPO" or "Peripheral's SDO") GPIO number. This is connected to the SD card's Data Out (DO).mosi_gpio
SPI Master Out, Slave In (MOSI) (also called "COPI", or "Peripheral's SDI") GPIO number. This is connected to the SD card's Data In (DI).sck_gpio
SPI Serial Clock GPIO number. This is connected to the SD card's Serial Clock (SCK).baud_rate
Frequency of the SPI Serial Clock, in Hertz. The default is clk_sys
/ 12.
This is ultimately passed to the SDK's spi_set_baudrate. This applies a hardware prescale and a post-divide to the Peripheral clock (clk_peri
) (see section 4.4.2.3. Clock prescaler in RP2040 Datasheet).
The Peripheral clock typically,
but not necessarily, runs from clk_sys
.
Practically, the hardware limits the choices for the SPI frequency to clk_peri
divided by an even number.
For example, if clk_peri
is clk_sys
and clk_sys
is running at the default 125 MHz,
.baud_rate = 125 * 1000 * 1000 / 10, // 12500000 Hz
or
.baud_rate = 125 * 1000 * 1000 / 4 // 31250000 Hz
If you ask for 14,000,000 Hz, you'll actually get 12,500,000 Hz.
The actual baud rate will be printed out if USE_DBG_PRINTF
(see Messages from the SD card driver) is defined at compile time.
The higher the baud rate, the faster the data transfer.
At the maximum clk_peri
frequency on RP2040 of 133MHz, the maximum peak bit rate in master mode is 62.5Mbps.
However, the hardware (including the SD card) might limit the usable baud rate.
See Pull Up Resistors and other electrical considerations.
spi_mode
0, 1, 2, or 3. 0 is the most common mode for SPI bus slave communication.
This controls the Motorola SPI frame format CPOL, clock polarity; and CPHA, clock phase.
SPI mode 0 (CPOL=0, CPHA=0) is the proper setting to control MMC/SDC, but mode 3 (CPOL=1, CPHA=1) also works as well in most cases[^6].
Mode 3 can be around 15% faster than mode 0, probably due to quirks of the ARM PrimeCell Synchronous Serial Port in the RP2040.DMA_IRQ_num
Which IRQ to use for DMA. Defaults to DMA_IRQ_0. Set this to avoid conflicts with any exclusive DMA IRQ handlers that might be elsewhere in the system.use_exclusive_DMA_IRQ_handler
If true, the IRQ handler is added with the SDK's irq_set_exclusive_handler
. The default is to add the handler with irq_add_shared_handler
, so it's not exclusive. no_miso_gpio_pull_up
According to the standard, an SD card's DO MUST be pulled up (at least for the old MMC cards).
However, it might be done externally. If no_miso_gpio_pull_up
is false, the library will set the RP2040 GPIO internal pull up.set_drive_strength
Specifies whether or not to set the RP2040 GPIO pin drive strength.
If set_drive_strength
is false, all will be implicitly set to 4 mA.
If set_drive_strength
is true, each GPIO's drive strength can be set individually. Note that if it is not explicitly set, it will default to 0, which equates to GPIO_DRIVE_STRENGTH_2MA
(2 mA nominal drive strength).mosi_gpio_drive_strength
SPI Master Out, Slave In (MOSI) drive strength, sck_gpio_drive_strength
SPI Serial Clock (SCK) drive strength:
Ignored if set_drive_strength
is false. Otherwise, these can be set to one of the following:
GPIO_DRIVE_STRENGTH_2MA
GPIO_DRIVE_STRENGTH_4MA
GPIO_DRIVE_STRENGTH_8MA
GPIO_DRIVE_STRENGTH_12MA
You might want to do this for electrical tuning. A low drive strength can give a cleaner signal, with less overshoot and undershoot. In some cases, this allows operation at higher baud rates. In other cases, the signal lines might have a lot of capacitance to overcome. Then, a higher drive strength might allow operation at higher baud rates. A low drive strength generates less noise. This might be important in, say, audio applications.
sd_driver/hw_config.h
size_t sd_get_num()
Returns the number of SD cards sd_card_t *sd_get_by_num(size_t num)
Returns a pointer to the SD card "object" at the given (zero origin) index. The definition of the hardware configuration can either be built in at build time, which I'm calling "static configuration", or supplied at run time, which I call "dynamic configuration".
In either case, the application simply provides an implementation of the functions declared in sd_driver/hw_config.h
.
Two other files contain definitions that should be adjusted for your particular hardware and application requirements:
FreeRTOSConfig.h
FreeRTOS is customised using a configuration file called FreeRTOSConfig.h
.
Every FreeRTOS application must have a FreeRTOSConfig.h
header file in its pre-processor include path. See Customisation.FreeRTOSFATConfig.h
Applications that use FreeRTOS-Plus-FAT must provide a FreeRTOSFATConfig.h
header file.
See FreeRTOS-Plus-FAT Configuration.For examples of these files, see examples/commmand_line/include
.
Indefinite timeouts are normally bad practice, because they make it difficult to recover from an error.
Therefore, we have timeouts all over the place.
To make these configurable, they are collected in sd_timeouts_t sd_timeouts
in sd_timeouts.c
.
The definition has the weak
attribute, so it can be overridden by user code.
For example, in hw_config.c
you could have:
sd_timeouts_t sd_timeouts = {
.sd_command = 2000, // Timeout in ms for response
.sd_command_retries = 3, // Times SPI cmd is retried when there is no response
//...
.sd_sdio_begin = 1000, // Timeout in ms for response
.sd_sdio_stopTransmission = 200, // Timeout in ms for response
};
Sometimes problems arise when attempting to use SD cards. At the
FreeRTOS-Plus-FAT API
level, it can be difficult to diagnose problems. You get an
error number,
but it might just tell you pdFREERTOS_ERRNO_EIO
("I/O error"),
for example, without telling you what you need to know in order to fix the problem.
The library generates messages that might help.
These are classed into Error, Informational, and Debug messages.
Two compile definitions control how these are handled in the SD card driver (or " media driver "):
USE_PRINTF
If this is defined and not zero,
these message output functions will use the Pico SDK's Standard Output (stdout
).USE_DBG_PRINTF
If this is not defined or is zero or NDEBUG
is defined,
DBG_PRINTF
statements will be effectively stripped from the code.Messages are sent using EMSG_PRINTF
, IMSG_PRINTF
, and DBG_PRINTF
macros, which can be redefined (see
my_debug.h).
By default, these call error_message_printf
, info_message_printf
, and debug_message_printf
,
which are implemented as
weak functions,
meaning that they can be overridden by strongly implementing them in user code.
If USE_PRINTF
is defined and not zero, the weak implementations will write to the Pico SDK's stdout. Otherwise, they will format the messages into strings and forward to put_out_error_message
, put_out_info_message
, and put_out_debug_message
. These are implemented as weak functions that do nothing. You can override these to send the output somewhere.
FreeRTOS-Plus-FAT uses a macro called FF_PRINTF
, which is defined in the
FreeRTOS-Plus-FAT Configuration file.
See Other Application-Specific Customization.
In general, you use the FreeRTOS-Plus-FAT APIs in your application. One function that is not documented as part of the standard API but is conventional in FreeRTOS-Plus-FAT:
FF_Disk_t *FF_SDDiskInit( const char *pcName )
Initializes the "disk" (SD card) and returns a pointer to an
FF_Disk_t
structure. This can then be passed to other functions in the FreeRTOS-Plus-FAT Native API such as FF_Mount
and FF_FS_Add
. The parameter pcName
is the Device Name; device_name
in
struct sd_card_t.
A typical sequence would be:
FF_SDDiskInit
FF_SDDiskMount
FF_FS_Add
ff_fopen
ff_fwrite
ff_fread
ff_fclose
FF_FS_Remove
FF_Unmount
FF_SDDiskDelete
See FreeRTOS-FAT-CLI-for-RPi-Pico/examples/simple_sdio/ for an example.
You may call sd_init_driver()
to explicitly initialize the block device driver.
It is called implicitly by FF_SDDiskInit
,
but you might want to call it sooner.
For example, you might want to get the GPIOs configured before setting up a card detect interrupt handler.
(See examples/command_line/src/unmounter.c.)
You might want to call it to get the SD cards into SPI mode so that they can share an SPI bus with other devices.
(See Cosideration on Multi-slave Configuration.)
sd_init_driver()
must be called from a FreeRTOS task.
data_log_demo
command.
(Stop it with the die
command.)
It records the temperature as reported by the RP2040 internal Temperature Sensor once per second
in files named something like /sd0/data/2021-02-27/21.csv
.
Use this as a starting point for your own data logging application!If you want to use FreeRTOS+FAT+CLI as a library embedded in another project, use something like:
git submodule add git@github.com:carlk3/FreeRTOS-FAT-CLI-for-RPi-Pico.git
or
git submodule add https://github.com/carlk3/FreeRTOS-FAT-CLI-for-RPi-Pico.git
You will need to pick up the library in CMakeLists.txt:
add_subdirectory(FreeRTOS-FAT-CLI-for-RPi-Pico/FreeRTOS+FAT+CLI build)
target_link_libraries(_my_app_ FreeRTOS+FAT+CLI)
Happy hacking!
You are welcome to contribute to this project! Just submit a Pull Request in GitHub. Here are some ideas for future enhancements:
examples
.FreeRTOS+FAT+CLI
, FreeRTOS-Kernel
, and Lab-Project-FreeRTOS-FAT
have been moved to subdirectory src
.example
is renamed command_line
. The names and syntax of some CLI commands have changed, and new ones added. See Appendix B: Operation of command_line
example.sd_card_t
attribute (or "field" or "member") pcName
has been removed and replaced by device_name
and mount_point
.
device_name
is equivalent to the old pcName
. mount_point
specifies the directory name for the mount point in the root directory.The object model for hardware configuration has changed.
If you are migrating a project from
Release 1.0.0,
you will have to change the hardware configuration customization. The sd_card_t
now contains a new object that specifies the configuration of either an SPI interface or an SDIO interface. See the
Customizing for the Hardware Configuration
section.
For example, if you were using a hw_config.c
containing
static sd_card_t sd_cards[] = { // One for each SD card
{
.pcName = "sd0", // Name used to mount device
.spi = &spis[0], // Pointer to the SPI driving this card
.ss_gpio = 17, // The SPI slave select GPIO for this SD card//...
that would now become
static sd_spi_if_t spi_ifs[] = {
{
.spi = &spis[0], // Pointer to the SPI driving this card
.ss_gpio = 17, // The SPI slave select GPIO for this SD card
//...
static sd_card_t sd_cards[] = { // One for each SD card
{
.device_name = "sd0", // Name used to mount device
.mount_point = "/sd0",
.type = SD_IF_SPI,
.spi_if_p = &spi_ifs[0], // Pointer to the SPI interface driving this card
//...
command_line
exampletio
work OK. For example:
tio -m ODELBS /dev/ttyACM0
>
help
command describes the available commands:
setrtc <DD> <MM> <YY> <hh> <mm> <ss>:
Set Real Time Clock
Parameters: new date (DD MM YY) new time in 24-hour format (hh mm ss)
e.g.:setrtc 16 3 21 0 4 0
date: Print current date and time
format
mount
unmount
info
cd