To begin using the ESP32 SPI API the driver/spi_master.h header file needs to be included in a project; see ESP32_SPI_API.h.
The first 2 declarations of variables, see ESP32_SPI_API.cpp, are the receive and transmit buckets. The variables uint8_t txData[2] = { }; and uint8_t rxData[25] = { }; are to be used as transmission and receive buckets.
The device that will receive the SPI data receives up to, 16 bits and determined, from reading a device spec sheet, the length of the longest message to be received, with a few added bytes for safety.
The SPI devices sends data to the MCU in 8 bit chunks. The variables uint8_t low; and int8_t high; will be used to store the extracted SPi data from the device and serve to facilitate reassembling the numbers into 16 bit numbers. If signed values are transferred then changing uint8_t to int8_t may in order.
Starting the show begins with initializing the SPI channel.
int fInitializeSPI_Channel( int spiCLK, int spiMOSI, int spiMISO, spi_host_device_t SPI_Host, bool EnableDMA)
{
esp_err_t intError;
spi_bus_config_t bus_config = { };
bus_config.sclk_io_num = spiCLK; // CLK
bus_config.mosi_io_num = spiMOSI; // MOSI
bus_config.miso_io_num = spiMISO; // MISO
bus_config.quadwp_io_num = -1; // Not used
bus_config.quadhd_io_num = -1; // Not used
intError = spi_bus_initialize( HSPI_HOST, &bus_config, EnableDMA) ;
return intError;
}
There is a gottcha with using the ESP32 SPI API under the Arduino IDE.
This does not work
spi_bus_config_t buscfg={
.miso_io_num = PIN_NUM_MISO,
.mosi_io_num = PIN_NUM_MOSI,
.sclk_io_num = PIN_NUM_CLK,
.quadwp_io_num = -1,
.quadhd_io_num = -1,
.max_transfer_sz = 32,
};
Many ESP32 SPi API examples show that the way to setup the configuration structure, see above. This methood, simply, does not work in the Arduino IDE.
More importantly the ESP32 has a 'bug' with declared structures. When a structure is declared, on an ESP32, the memory is set aside for structure storage but the structure elements are not cleared or set to default values, automatically.
By declaring a structure and explicitly cause the structures default values to be set is the only way to make sure that the structure is not filled with some random values; spi_bus_config_t bus_config = { };
After the SPI bus configuration channel is initialized, the SPI pin numbers are assigned and an expected max byte transfer size is declared, the SPI channel configuration is used to configure a SPI buss channel; spi_bus_initialize( HSPI_HOST, &bus_config, EnableDMA); that will be used.