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

Wrong timing on first start bit? #13

Closed DougF42 closed 8 years ago

DougF42 commented 9 years ago

I was looking at "writeByte", at line 124: SET_COMPARE_A(GET_TIMER_COUNT() + 16);

If I am reading the code right, this is setting the length of the start bit for the first byte. Instead of a constant of '16', I think it should be set to "ticks_per_bit" ?

matthijskooijman commented 8 years ago

No, this +16 just means "run the ISR ASAP to begin the start bit". I believe this prevents duplicating code between the ISR and writeByte. The ISR has code to set the line state and, depending on the data to be sent, schedule a compare match to toggle the line state, which is fairly complicated, but works the same for the startbit and the databits.

I believe "16" here is chosen as a fairly short interval, that is certainly enough to complete the read-modify-write cycle that SET_COMPARE_A(GET_TIMER_COUNT() + 16); is. So, AFAICS the code is correct (also logic traces show the start bits have the same value).

PaulStoffregen commented 8 years ago

Ok, I just did a couple quick tests, with this code

#include <AltSoftSerial.h>

AltSoftSerial myser;

void setup() {
  myser.begin(9600);
}

void loop() {
  myser.write(0xA5);
  myser.write((uint8_t)0);
  delay(100);
}

On Teensy 3.2:

file1

On Teensy 2.0:

file2

I believe it's safe to conclude the start bit is fine.