Skip to content

Commit ab23101

Browse files
committed
Update SPI.h - Optimization of transfer_out
An alternative "output only" transfer that doesn't destroy the contents of the source buffer with the bytes returned from the slave device. * Some code simplifications and const enforcement * Revision with speedup of about 25% in atmega328p tests * NOTE: I can't explain that "*(p++ + 1);" being speedier than "*++p"
1 parent c0964e8 commit ab23101

File tree

1 file changed

+10
-5
lines changed
  • hardware/arduino/avr/libraries/SPI

1 file changed

+10
-5
lines changed

hardware/arduino/avr/libraries/SPI/SPI.h

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
* Copyright (c) 2014 by Paul Stoffregen <paul@pjrc.com> (Transaction API)
44
* Copyright (c) 2014 by Matthijs Kooijman <matthijs@stdin.nl> (SPISettings AVR)
55
* Copyright (c) 2014 by Andrew J. Kroll <xxxajk@gmail.com> (atomicity fixes)
6+
* Copyright (c) 2016 by Pedro M. Ribeiro <pamribeirox@gmail.com> (transfer_out)
67
* SPI Master library for arduino.
78
*
89
* This file is free software; you can redistribute it and/or modify
@@ -260,15 +261,19 @@ class SPIClass {
260261
* contents of the source buffer with the bytes returned from the
261262
* slave device.
262263
* Some code simplifications and const enforcement
263-
* by Pedro Ribeiro pamribeirox@gmail.com
264-
*/
264+
* Revision with speedup of about 25% in atmega328p tests
265+
* NOTE: I can't explain that "*(p++ + 1);" being speedier than "*++p"
266+
*/
265267
inline static void transfer_out(const void *buf, size_t count) {
266268
if (count == 0) return;
267269
uint8_t *p = (uint8_t *)buf;
268-
while (count-- > 0) {
269-
SPDR = *p++;
270-
while (!(SPSR & _BV(SPIF))) ;
270+
SPDR = *p;
271+
while (--count > 0) {
272+
uint8_t out = *(p++ + 1); // ugly but somehow results in a speedup!
273+
while (!(SPSR & _BV(SPIF))) ; // last SPI transfer is over?
274+
SPDR = out;
271275
}
276+
while (!(SPSR & _BV(SPIF))) ; // last SPI transfer is over?
272277
}
273278
// After performing a group of transfers and releasing the chip select
274279
// signal, this function allows others to access the SPI bus

0 commit comments

Comments
 (0)