Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- uint8_t buffer[1024];
- size_t bufferSize = 0;
- unsigned long lastSerialReadTime = 0;
- void setup() {
- Serial.begin(115200);
- //...
- }
- void loop() {
- if (Serial1.available() > 0) {
- unsigned long currentTime = millis();
- unsigned long timeDifference = currentTime - lastSerialReadTime;
- lastSerialReadTime = currentTime;
- // For serial communication, each byte typically consists of 10 bits
- // 1 start bit, 8 data bits, and 1 stop bit.
- // Here baud rate is 2400.
- // time = 10/2400 => 4.1667ms
- // So it would take approximately (5ms) to receive one byte of data
- if (timeDifference <= 5) {
- if (bufferSize < sizeof(buffer)) {
- buffer[bufferSize++] = Serial1.read();
- }
- } else {
- if (bufferSize > 0) {
- Serial.write(buffer, bufferSize);
- bufferSize = 0;
- }
- }
- }
- }
- // Optimized Version:
- //-----------------------------------------------------------------------------
- const uint16_t BUFFER_SIZE = 256;
- uint8_t buffer[BUFFER_SIZE];
- size_t bytesRead = 0;
- unsigned long lastReadTime = 0;
- void setup() {
- Serial.begin(115200);
- //...
- }
- void loop() {
- while (Serial1.available()) {
- uint8_t byte = Serial1.read();
- if (bytesRead >= BUFFER_SIZE || (bytesRead > 0 && millis() > lastReadTime)) {
- Serial.write(buffer, bytesRead);
- bytesRead = 0;
- }
- buffer[bytesRead++] = byte;
- // For serial communication, each byte typically consists of 10 bits
- // 1 start bit, 8 data bits, and 1 stop bit.
- // Here baud rate is 2400.
- // time = 10/2400 => 4.1667ms
- // So it would take approximately (5ms) to receive one byte of data
- lastReadTime = millis() + 5;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement