Skip to content

Commit 73293bc

Browse files
committed
Fix SPI transfer16
When the SPI device is configured for MSB first, the 16 bit data being sent and received on the SPI bus has the bytes swapped if the SPI.transfer16() method is used. Swapping the bytes before and after the call to spi_transfer() fixes the problem. Tested using an AS5147P magnetic encoder spi device. Before the fix, saw frame errors due to the bytes being swapped, when the same unmodified code worked perfectly on an AVR based SparkFun RedBoard. Signed-off-by: Theodore A. Roth <[email protected]>
1 parent 1e9f4fa commit 73293bc

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

Diff for: libraries/SPI/SPI.cpp

+11
Original file line numberDiff line numberDiff line change
@@ -201,10 +201,16 @@ byte SPIClass::transfer(uint8_t _pin, uint8_t data, SPITransferMode _mode)
201201
uint16_t SPIClass::transfer16(uint8_t _pin, uint16_t data, SPITransferMode _mode)
202202
{
203203
uint16_t rx_buffer = 0;
204+
uint16_t tmp;
204205

205206
if (_pin > SPI_CHANNELS_NUM)
206207
return rx_buffer;
207208

209+
if (spiSettings[_pin].msb) {
210+
tmp = ((data & 0xff00) >> 8) | ((data & 0xff) << 8);
211+
data = tmp;
212+
}
213+
208214
if(_pin != g_active_id) {
209215
spi_init(&_spi, spiSettings[_pin].clk, spiSettings[_pin].dMode, spiSettings[_pin].msb);
210216
g_active_id = _pin;
@@ -218,6 +224,11 @@ uint16_t SPIClass::transfer16(uint8_t _pin, uint16_t data, SPITransferMode _mode
218224
if((_pin != BOARD_SPI_OWN_SS) && (_mode == SPI_LAST) && (_spi.pin_ssel == NC))
219225
digitalWrite(_pin, HIGH);
220226

227+
if (spiSettings[_pin].msb) {
228+
tmp = ((rx_buffer & 0xff00) >> 8) | ((rx_buffer & 0xff) << 8);
229+
rx_buffer = tmp;
230+
}
231+
221232
return rx_buffer;
222233
}
223234

0 commit comments

Comments
 (0)