uint8_t window[10];
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
// Slide the window
for (uint8_t i = 0; i < 9; i++) {
window[i] = window[i + 1];
}
// Add the new character
window[9] = Serial.read();
// Output the current window data for debugging
dumpWin();
// Check the framing characters
if ((window[0] == 0xAA) && (window[9] == 0xAC)) {
// Calculate the checksum
uint8_t cs = 0;
for (uint8_t i = 2; i < 8; i++) {
cs += window[i];
}
// If the checksum matches...
if (cs == window[8]) {
// ...we have a valid packet!
}
}
}
}
void dumpWin() {
for (int i = 0; i < 10; i++) {
Serial.print(window[i], HEX);
Serial.print(" ");
}
Serial.println();
}
Since you can't really use the hardware UART for both communication with your sensor and communication with the PC you may want to investigate the use of SoftwareSerial instead of the hardware UART pins for communicating with the sensor.