const int BUFFER_SIZE = 64; // Size of the buffer
char inputBuffer[BUFFER_SIZE]; // Buffer to store incoming data
int head = 0; // Head index for circular buffer
int tail = 0; // Tail index for circular buffer
bool bufferFull = false;
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
char incomingByte = Serial.read();
inputBuffer[head] = incomingByte;
head = (head + 1) % BUFFER_SIZE;
// Check if the buffer is full
if (head == tail) {
bufferFull = true;
}
// Process the data if the buffer is full or a certain condition is met
if (bufferFull || (head != tail && Serial.available() == 0)) {
processData();
}
}
}
// Function to process the data in the buffer
void processData() {
Serial.print("Received: ");
int end = head;
if (bufferFull) {
for (int i = tail; i != head; i = (i + 1) % BUFFER_SIZE) {
Serial.print(inputBuffer[i]);
}
bufferFull = false; // Reset the buffer full flag
} else {
for (int i = tail; i != end; i = (i + 1) % BUFFER_SIZE) {
Serial.print(inputBuffer[i]);
}
}
Serial.println();
// Reset the buffer
tail = head;
}