Skip to content

Commit 10218d4

Browse files
committed
libraries: fixed SPI
to handle other bit lengths rather than 8. Thanks to @UlliBien for the fix suggestion. Fixes: #2820
1 parent 55539ae commit 10218d4

File tree

1 file changed

+25
-19
lines changed

1 file changed

+25
-19
lines changed

libraries/SPI/SPI.cpp

+25-19
Original file line numberDiff line numberDiff line change
@@ -307,27 +307,33 @@ uint8_t SPIClass::transfer(uint8_t data) {
307307
}
308308

309309
uint16_t SPIClass::transfer16(uint16_t data) {
310-
union {
311-
uint16_t val;
312-
struct {
313-
uint8_t lsb;
314-
uint8_t msb;
315-
};
316-
} in, out;
317-
in.val = data;
318-
319-
if((SPI1C & (SPICWBO | SPICRBO))) {
320-
//LSBFIRST
321-
out.lsb = transfer(in.lsb);
322-
out.msb = transfer(in.msb);
323-
} else {
324-
//MSBFIRST
325-
out.msb = transfer(in.msb);
326-
out.lsb = transfer(in.lsb);
327-
}
328-
return out.val;
310+
while (SPI1CMD & SPIBUSY) {}
311+
// Set to 16Bits transfer
312+
setDataBits(16);
313+
314+
const bool isBigEndian = !(SPI1C & (SPICWBO | SPICRBO));
315+
316+
// Change byte order for MSBFIRST
317+
if (isBigEndian)
318+
SPI1W0 = (data >> 8) | (data << 8);
319+
else
320+
SPI1W0 = data;
321+
322+
// Start the transmission
323+
SPI1CMD |= SPIBUSY;
324+
// Wait for transmission to complete
325+
while (SPI1CMD & SPIBUSY) {}
326+
data = SPI1W0;
327+
328+
// Change byte order for MSBFIRST
329+
if (isBigEndian)
330+
return (data >> 8) | (data << 8);
331+
332+
// If !isBigEndian, return the normal data.
333+
return data;
329334
}
330335

336+
331337
void SPIClass::transfer(void *buf, uint16_t count) {
332338
uint8_t *cbuf = reinterpret_cast<uint8_t*>(buf);
333339

0 commit comments

Comments
 (0)