Hey everyone. Problem I've been trying to troubleshoot for more than I'd like to admit but I just can't figure out what's going on here.
For example with this sketch:
#include <SoftwareSerial.h>
SoftwareSerial output(A2, A3);
void setup() {
Serial.begin(38400);
output.begin(38400);
}
void loop() {
if (Serial.available()) {
output.write(Serial.read());
}
if (output.available()) {
Serial.write(output.read());
}
}
I have a modem connected to arduino hardware serial port and a Software serial port for debugging.
The modem sends and recieves some messages via the RF modem from another device i have setup
from the other device i send the following string
8200FF01234C5453542359454C230A1
This is what gets output on my debugging terminal:
+CTSDSR: 108,302201300001012,1,302201300001069,1,124
8200FF01234C5453542359454C230A1
This is what i expect... Works like it should.
The problem comes in when i try with a different sketch that is looking for particular messages. To simplify my sketch:
void loop() {
if (radio.available()) {
int i = readRadio(serialData, TIMEOUT_LONG);
#ifdef DEBUG
debugSerial.print("[main] Data returned from radio = ");
debugSerial.println(serialData);
#endif
}
}
///////////////////////////////////////////////////////////////////// READ RADIO /////////////////////////////////////////////////////////////////////
int readRadio(char * buf, int timeout) {
unsigned long startTime = millis();
byte bytesRead = 0;
char inByte;
for (;;) {
delay(1);
if (radio.available()) {
inByte = radio.read();
if (inByte == '\r' || inByte == '\n') {
if (bytesRead == 0) {
//buffer is empty, restart
continue;
}
else if (bytesRead > 0) {
//we have data, end
break;
}
}
buf[bytesRead++] = inByte;
}
else {
if ((int)millis() - startTime > timeout) {
//serial timeout
#ifdef DEBUG
if (bytesRead > 0) {
debugSerial.println("[readRadio]Serial timed out");
}
#endif
break;
}
}
}
if (buf) {
buf[bytesRead] = '\0';
}
#ifdef DEBUGSERIAL
if (bytesRead > 0) {
debugSerial.print("[readRadio] bytes returned = ");
debugSerial.println(bytesRead);
debugSerial.print("[readRadio] buffer content = ");
debugSerial.println(buf);
}
#endif
return bytesRead;
}
The output is always missing the last byte. My message from the other device has an incrementing counter on the end... This is what i get out if i send the same message as before
8200FF01234C5453542359454C230A
.
That A character increments by one digit, but it's always missing.
My readRadio function is reading until it gets a cr or lf and in other applications has worked fine. I can't understand why it is now consistently missing that last character.
Any ideas?