Error in Software Serial Documentation - halfBitDelay should be placed before if (low) check [MKC-558]
Issue arduino/Arduino#1315 is not yet solved. A description of the error can be found here: https://github.com/arduino/Arduino/issues/1315#issue-11938798
It refers to the Serial Tutorial: https://www.arduino.cc/en/Tutorial/SoftwareSerial
Agreed that the code does not match the text, and I think the code is not entirely correct either. Ideally, you sample halfway each bit time, which the code does not do. The implementation suggested in arduino/Arduino#1315 seems better, since it also stays waiting for a start bit when noise is received (instead of returning an undefined value as the code in the tutorial does). For clarity, I think the full code should be:
int SWread()
{
byte val = 0;
//wait for start bit
while (true) {
while (digitalRead(rx));
// Sample again halfway through the start bit
delayMicroseconds(halfBit9600Delay);
if (digitalRead(rx) == LOW)
break;
}
delayMicroseconds(halfBit9600Delay);
for (int offset = 0; offset < 8; offset++) {
delayMicroseconds(bit9600Delay);
val |= digitalRead(rx) << offset;
}
//wait for stop bit + extra
delayMicroseconds(bit9600Delay);
delayMicroseconds(bit9600Delay);
return val;
}
I have not tested this. @frami75 if you are working with this code, maybe you could test the above to confirm it is correct?
I'm sorry, I have no possibility to test this code. I have no experience in Arduino programming and stumbled over it when searching for information about programming of serial communication. I was only confused, as the code didn't match the description, but as it was a topic here some years ago I was convinced, that it's really a bug. Hopefully there is someone who can make the correction.