-
Notifications
You must be signed in to change notification settings - Fork 1
/
nmea-checksum.ino
65 lines (55 loc) · 2.3 KB
/
nmea-checksum.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
void setup() {
Serial.begin(9600);
Serial.println();
printSentenceWithChecksum("$POV,P," + String(1018.35) + "*", false); // 39
printSentenceWithChecksum("test$test*", false); // 16
printSentenceWithChecksum("$test*", false); // 16
printSentenceWithChecksum("$POV,P,951.78*", false); // 05
printSentenceWithChecksum("$POV,P,951.84*", false); // 06
}
void printSentenceWithChecksum(String sentence, bool printLogs) {
String sentenceWithChecksum = withChecksum(sentence, printLogs);
Serial.println(sentenceWithChecksum);
}
String withChecksum(String sentence, bool printLogs) {
// http://www.hhhh.org/wiml/proj/nmeaxor.html
bool started = false;
char checksum = 0;
for (int index = 0; index < sentence.length(); index++) {
if (index > 0 && sentence[index - 1] == '$') {
if (printLogs) Serial.println("Found first checksum char:");
if (printLogs) Serial.println(sentence[index]);
if (printLogs) Serial.println(sentence[index], HEX);
if (printLogs) Serial.println("Set as initial 'last step result'.");
if (printLogs) Serial.println();
checksum = sentence[index];
started = true;
continue; // Skip the rest of this loop iteration.
}
if (sentence[index] == '*') {
if (printLogs) Serial.println("Reached the end of checksum chars.");
if (printLogs) Serial.println("Final checksum:");
if (printLogs) Serial.println(checksum, HEX);
if (printLogs) Serial.println();
break; // Exit the loop.
}
// Ignore everything preceeding '$'.
if (!started) {
continue; // Skip the rest of this loop iteration.
}
if (printLogs) Serial.println("Xoring last step result and current char.");
if (printLogs) Serial.println(checksum, HEX);
if (printLogs) Serial.println(sentence[index]);
if (printLogs) Serial.println(sentence[index], HEX);
checksum = checksum xor sentence[index];
if (printLogs) Serial.println("Got new last step result:");
if (printLogs) Serial.println(checksum, HEX);
if (printLogs) Serial.println();
}
String sentenceWithChecksum = sentence + (checksum < 10 ? "0" : "") + String(checksum, HEX);
if (printLogs) Serial.println("Sentence with checksum:");
if (printLogs) Serial.println(sentenceWithChecksum);
return sentenceWithChecksum;
}
void loop() {
}