Hi there!
I read several posts similar to my issue but couldn't find (or understand) a solution.
I have a Teensy 3.6 and configured the serial1 port with Serial1.setTimeout(10);
On that serial I receive up to 10 bytes at once then 300ms of silence. I double-checked this on my oscilliscope. My problem is with that line: rbufLen=Serial1.readBytes(rbuf,32); I always receive 32 bytes no matter what timeout I set. Even setting timeout at 1ms won't solve my issue. The other device sends up to 10 bytes then 300ms pause.
My code:
unsigned char printbuffer[32];
unsigned int rbufLen; //how many bytes received at once
void setup()
{
Serial.begin(9600);
while (!Serial) { ; }
Serial1.begin(9600);
Serial1.setTimeout(10); // 10ms timeout
}
void loop()
{
Serial.println(
"\nType '1' to read data"
"\n '2' for ?"
);
while (!Serial.available()) {
}
char c = Serial.read();
if (c =='1') {
rbufLen=Serial1.readBytes(rbuf,32); //Serial1.flush();
sprintf(printbuffer, "Rx: %d \n", rbufLen); Serial.printf(printbuffer);
}
}
Serial1 is the interface where I receive the data packets consisting of 10 bytes.
serial is the usb debug interface on which I send a '1' and receive how many bytes I got on Serial1. They have different setups.
Could be the fact the other device send these bytes continuously whether I read them or not?
I suppose if no data avaliable then rbufLen=Serial1.readBytes(rbuf,32); would return 0. There's always data on the line. I tried checking Serial1.available() before readBytes but the result is the same. Obviously, if I plug the serial1 cable I get 0 read bytes. Otherwise readBytes always return 32 or whatever value I set at length.
I need to read a timestamp the other device sends continously.
/*
// This is Required to check compilation on Wokwi (UNO)
#include <SoftwareSerial.h>
SoftwareSerial Serial1(4,5);
*/
// Serial.print() did not work on Wokwi (UNO) with unsigned char array therefore
// declared as char array
char printbuffer[32];
unsigned int rbufLen; //how many bytes received at once
// Missing declaration from post #1
char rbuf[32];
void setup()
{
Serial.begin(9600);
while (!Serial) { ; }
Serial1.begin(9600);
Serial1.setTimeout(10); // 10ms timeout
Serial.println(
"\nType '1' to read data"
"\n '2' for ?"
);
}
void loop()
{
if (Serial.available()) {
char c = Serial.read();
if (c =='1') {
sprintf(printbuffer, "Rx: %d \n", rbufLen);
Serial.print(printbuffer);
}
}
if (Serial1.available()) {
rbufLen=Serial1.readBytes(rbuf,32); //Serial1.flush();
}
}
Try with Bd = 2400 for both TX/RX and timeout = 1ms.
At Bd = 9600, time gap between the arrival of successive frames (bytes) is: 41 us; whereas, your timeout = 10 ms. So, you will always be receiving the bytes.