Use SPI bus concurrently from two tasks
Posted: Mon Mar 12, 2018 10:32 pm
My ESP32 app talks to two SPI slaves connected to the same SPI bus. Two tasks run concurrently (on the same cpu) and each one talks to one of the slaves. The program runs without problem if I use a mutex to ensure that only one task accesses the SPI bus at a time.
However, I would like to better interleave the SPI transactions of the two tasks and get rid of the mutex. The ESP-IDF documentation (http://esp-idf.readthedocs.io/en/latest ... aster.html) says:
The function spi_device_transmit doesn't help either as it internally uses spi_device_get_trans_result as well. The documentation contains even a warning that is related to this fact:
However, I would like to better interleave the SPI transactions of the two tasks and get rid of the mutex. The ESP-IDF documentation (http://esp-idf.readthedocs.io/en/latest ... aster.html) says:
While it might internally be capable of handling a multithreaded environment, the API doesn't seem to really support it. The problem is the function spi_device_get_trans_result: It returns the oldest queued result of any SPI transaction – without regard to who submitted it in the first place. So it mixes up the transaction results of the two tasks. There seems to be no way to restrict it to transactions started by the same task or even to a specific transaction. So in effect, you cannot wait for the result of a SPI transaction that you have started if another task is using the same SPI bus.The spi_master driver allows easy communicating with SPI slave devices, even in a multithreaded environment. It fully transparently handles DMA transfers to read and write data and automatically takes care of multiplexing between different SPI slaves on the same master.
The function spi_device_transmit doesn't help either as it internally uses spi_device_get_trans_result as well. The documentation contains even a warning that is related to this fact:
Have I missed something? Or is the SPI master really incapable of working in a multithreaded environment without additional synchronization – contrary to what the documentation suggests?Do not use this when there is still a transaction queued that hasn’t been finalized using spi_device_get_trans_result.