Advertisement
chayanforyou

Arduino read all serial data

Apr 20th, 2024 (edited)
581
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. uint8_t buffer[1024];
  2. size_t bufferSize = 0;
  3. unsigned long lastSerialReadTime = 0;
  4.  
  5. void setup() {
  6.   Serial.begin(115200);
  7.   //...
  8. }
  9.  
  10. void loop() {
  11.   if (Serial1.available() > 0) {
  12.     unsigned long currentTime = millis();
  13.     unsigned long timeDifference = currentTime - lastSerialReadTime;
  14.     lastSerialReadTime = currentTime;
  15.  
  16.     // For serial communication, each byte typically consists of 10 bits
  17.     // 1 start bit, 8 data bits, and 1 stop bit.
  18.     // Here baud rate is 2400.
  19.     // time = 10/2400 => 4.1667ms
  20.     // So it would take approximately (5ms) to receive one byte of data
  21.     if (timeDifference <= 5) {
  22.       if (bufferSize < sizeof(buffer)) {
  23.         buffer[bufferSize++] = Serial1.read();
  24.       }
  25.     } else {
  26.       if (bufferSize > 0) {
  27.         Serial.write(buffer, bufferSize);
  28.         bufferSize = 0;
  29.       }
  30.     }
  31.   }
  32. }
  33.  
  34.  
  35. // Optimized Version:
  36. //-----------------------------------------------------------------------------
  37.  
  38. const uint16_t BUFFER_SIZE = 256;
  39. uint8_t buffer[BUFFER_SIZE];
  40. size_t bytesRead = 0;
  41. unsigned long lastReadTime = 0;
  42.  
  43. void setup() {
  44.   Serial.begin(115200);
  45.   //...
  46. }
  47.  
  48. void loop() {
  49.   while (Serial1.available()) {
  50.     uint8_t byte = Serial1.read();
  51.  
  52.     if (bytesRead >= BUFFER_SIZE || (bytesRead > 0 && millis() > lastReadTime)) {
  53.       Serial.write(buffer, bytesRead);
  54.       bytesRead = 0;
  55.     }
  56.  
  57.     buffer[bytesRead++] = byte;
  58.  
  59.     // For serial communication, each byte typically consists of 10 bits
  60.     // 1 start bit, 8 data bits, and 1 stop bit.
  61.     // Here baud rate is 2400.
  62.     // time = 10/2400 => 4.1667ms
  63.     // So it would take approximately (5ms) to receive one byte of data
  64.     lastReadTime = millis() + 5;
  65.   }
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement