Streaming Fletcher Checksum

Calculate the Fletcher-16 checksum as data streams into the serial port….

johngfletcher-image

John G. Fletcher

nt dex0=-1;
boolean comComplete0 = false;
char buffer0[200];
byte sum01, sum02;

void setup() {
  // initialize both serial ports:
  Serial.begin(9600);
  //Serial1.begin(9600);
}

void loop() { 
    // if the SerialEvent() function detected a string 
    // that ended in a line feed ('/n'), then 
    // print the fletcher-16 checksum and the serial data
    // to port 0
    if (comComplete0) {   
      Serial.print(“sum1=");
      Serial.print(sum01);
      Serial.print(",");
      Serial.print(“sum2=");
      Serial.print(sum02);
      Serial.print(“:  “);
      Serial.println(buffer0);
      dex0 = -1;
      //reset the comComplete flag
      comComplete0 = false;
      //reset the checksum
      sum01 = 0;
      sum02 = 0; 
    }

void serialEvent() {
  while (Serial.available()) {
    dex0 ++;
    byte inChar = Serial.read();
    //The next lines calculate the fletcher checksum and
    //as each character is read from the com port.
    //put it into the global variables sum01 and sum01
    //
    sum01 = (sum01 + inChar) % 255;
    sum02 = (sum01 + sum02) % 255;   
    if (inChar == '\n') {           //line feed
      buffer0[dex0] = inChar;
      dex0++;
      buffer0[dex0] = '\0';
      dex0--;
      comComplete0 = true;
      return;
    }
    buffer0[dex0] = inChar;
  }
  return;
}