PaulStoffregen / AltSoftSerial

Software emulated serial using hardware timers for improved compatibility
http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
328 stars 131 forks source link

Receive does not work correctly at slow baud rates with long sequences of identical bits #7

Closed lutorm closed 8 years ago

lutorm commented 9 years ago

I was trying to receive data at 1200baud on an 8MHz Atmega328 and had the problem that certain characters were not received correctly. 0x00 became 0xff, etc. I finally realized the problem was with characters that had at least 6 identical bits. It appears that in that case, the timer B will wrap around sufficiently that "offset" in the CAPTURE_INTERRUPT handler becomes negative, so it would simply exit out of the loop instead of put the received bits into the rx_byte.

The fix was to add a second check that checks if the offset is so negative that it could not possibly be due to a pin change before the target time. If

                       if (offset < 0) break;

is changed to

                        // if it's not yet time to sample, do
                        // nothing. However, for long stretches of
                        // identical bits, enough time may pass that
                        // the offset becomes negative, so we must
                        // check whether the negative offset is due to
                        // this.

                        if (offset < 0 &&
                            offset > -(0xffff-rx_stop_ticks)) 
                                break;

then it works correctly for me. (However, I haven't thought about whether this will result in problems at higher baud rates where rx_stop_ticks might be so small that 0xffff-rx_stop_ticks may not fit in the int16_t.)

Otherwise it seems to work great, thanks for writing it!

Regards,

/Patrik

igittigitt commented 8 years ago

I can approve the above using 2400 bauds. I send a series of bytes from a PC via serial and can reproduce das some bytes get never transmitted correctly. This can be reproduced every time with the same result.

PaulStoffregen commented 8 years ago

I've fixed several subtle bugs and added support for slower baud rates.

Please give the latest code a try and let me know if it resolves this issue for you?

PaulStoffregen commented 8 years ago

I'm pretty sure the recent fixes solve this problem, so I'm closing this issue.

If there's still a problem, please open a new issue. Remember to always post code & hardware details necessary to reproduce the problem.

lutorm commented 8 years ago

I don't have an easy way to update the device that's running my tweaked code, but it's been running flawlessly for 18 months now at 1200 baud.