Skip to content

Commit 58491aa

Browse files
committed
spi: Added block-level SPI writes to the C++ api
virtual int write(const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length); The main benefit of block-level SPI writes is the performance improvement from not acquiring a mutex lock between each byte sent on the SPI bus. The block write may also be poked through the hal level for additional speed improvements.
1 parent 186f406 commit 58491aa

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

drivers/SPI.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,23 @@ int SPI::write(int value) {
7878
return ret;
7979
}
8080

81+
int SPI::write(const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length) {
82+
int total = (tx_length > rx_length) ? tx_length : rx_length;
83+
84+
lock();
85+
aquire();
86+
for (int i = 0; i < total; i++) {
87+
char out = (i < tx_length) ? tx_buffer[i] : 0xff;
88+
char in = spi_master_write(&_spi, out);
89+
if (i < rx_length) {
90+
rx_buffer[i] = in;
91+
}
92+
}
93+
unlock();
94+
95+
return total;
96+
}
97+
8198
void SPI::lock() {
8299
_mutex->lock();
83100
}

drivers/SPI.h

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,25 @@ class SPI {
115115
*
116116
* @returns
117117
* Response from the SPI slave
118-
*/
118+
*/
119119
virtual int write(int value);
120120

121+
/** Write to the SPI Slave and obtain the response
122+
*
123+
* The total number of bytes sent and recieved will be the maximum of
124+
* tx_length and rx_length. The bytes written will be padded with the
125+
* value 0xff.
126+
*
127+
* @param tx_buffer Pointer to the byte-array of data to write to the device
128+
* @param tx_length Number of bytes to write, may be zero
129+
* @param rx_buffer Pointer to the byte-array of data to read from the device
130+
* @param rx_length Number of bytes to read, may be zero
131+
* @returns
132+
* The number of bytes written and read from the device. This is
133+
* maximum of tx_length and rx_length.
134+
*/
135+
virtual int write(const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length);
136+
121137
/** Acquire exclusive access to this SPI bus
122138
*/
123139
virtual void lock(void);

0 commit comments

Comments
 (0)