Skip to content

Commit 157ec97

Browse files
Optimize SoftwareSerial::recv
Similar to SoftwareSerial::write, this rewrites the loop to only touch the MSB and then shift those bits up, allowing the compiler to generate more efficient code. Unlike the write function however, it is not needed to put all instance variables used into local variables, for some reason the compiler already does this (and doing it manually even makes the code bigger). On the Arduino Uno using gcc 4.3 this saves 26 bytes. Using gcc 4.8 this saves 30 bytes. Note that this removes the else clause in the code, making the C code unbalanced, which looks like it breaks timing balance. However, looking at the code generated by the compiler, it turns out that the old code was actually unbalanced, while the new code is properly balanced.
1 parent c69c0b5 commit 157ec97

File tree

1 file changed

+3
-5
lines changed

1 file changed

+3
-5
lines changed

libraries/SoftwareSerial/SoftwareSerial.cpp

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -242,15 +242,13 @@ void SoftwareSerial::recv()
242242
DebugPulse(_DEBUG_PIN2, 1);
243243

244244
// Read each of the 8 bits
245-
for (uint8_t i=0x1; i; i <<= 1)
245+
for (uint8_t i=8; i > 0; --i)
246246
{
247247
tunedDelay(_rx_delay_intrabit);
248+
d >>= 1;
248249
DebugPulse(_DEBUG_PIN2, 1);
249-
uint8_t noti = ~i;
250250
if (rx_pin_read())
251-
d |= i;
252-
else // else clause added to ensure function timing is ~balanced
253-
d &= noti;
251+
d |= 0x80;
254252
}
255253

256254
// skip the stop bit

0 commit comments

Comments
 (0)