NMEA0183 checksum

Hi Everyone. I have a project to transfer temperature data over to a raspberry pi serial port "masqueraded" as a NMEA0183 sentence.

It kind of works, the problem is that as a standard a NMEA sentence contains a hex checksum at the end , with a value based on the sentence itself. In some software, this checksum can be ignored but others has this as a demand and cannot be excluded.

Hence, I need a smooth way to calculate this checksum, add it to the sentence and send it off. Currently my code looks like this:

int potPin= 0; //initialize analog pin 0 for tempsensor
void setup()
{
Serial.begin(4800);// set baud rate at”4800”
}
void loop()
{
  int val; //define variable
  int dat; //define variable
  val=analogRead(0); //read the analog value and assign it to val variable
  dat=(125*val)>>8; //temperature calculation formula
  
Serial.print("$IIXDR,C,"); // display character
Serial.print(dat); //output and display value of dat
Serial.println(",C,TempAir"); //display characters
delay(500); //wait for 0.5 second
}

With the serial output being: $IIXDR,C,20,C,TempAir

I like it to look like this: $IIXDR,C,20,C,TempAir*3A

with 3A being the checksum of the first output - the $ sign.

Thanks in advance, and sorry for hurting your eyes with the coding :)

Try a Google search on;

arduino generate nmea checksum

There is a remote chnace that soemone has needed to do this before (hint).

I modified the sketch from here to meet your requirement. Note that the input string has no checksum so the for loop in the function is modified to not expect a checksum.

#include <stdio.h>
#include <string.h>

char* nmeaData = "$IIXDR,C,20,C,TempAir";


void setup()
{
   Serial.begin(115200);
   
   Serial.println(nmea0183_checksum(nmeaData), HEX);
}

void loop()
{

}

int nmea0183_checksum(char *nmea_data)
{
    int crc = 0;
    int i;

    // ignore the first $ sign,  no checksum in sentence
    for (i = 1; i < strlen(nmea_data); i ++) { // removed the - 3 because no cksum is present
        crc ^= nmea_data[i];
    }

    return crc;
}

That is glorious. Thanks!