I have created a sub, which add a checksum to a NMEA-protocol. My question is: is there an easier way to calculate the checksum? I think, that my sub sometimes works and sometimes it doesn`t.
NMEA is the NMEA-protocol as string without the checksum,
B4X:
Sub Globals
Dim buffer(0) as Byte
End Sub
Sub Checksum_NMEA
buffer()=bit_NMEA.stringToBytes(NMEA,1,StrLength(NMEA)-2)
laenge=ArrayLen(buffer())
summe=buffer(0)
for j=1 to laenge-1
summe=bit_NMEA.XOR(summe,buffer(j))
next
checksum=bit_NMEA.DecToHex(summe)
NMEA=NMEA & checksum & crlf
End Sub
Looks and tests fine for me, admittedly on a limited set of data. However I think that the checksum should always be two characters and your Sub could fail because bit_NMEA.DecToHex doesn't return two characters for a number less than 16 so you should check for this and correct it.
B4X:
...
checksum=bit_NMEA.DecToHex(summe)
If summe < 16 Then
checksum = "0" & checksum
End If
...
Hi,
I did this a couple of months before and shared it here in the forum:
B4X:
Sub Globals
'dll: bitwise.dll, object: bit
nmea = "$GPGGA,102334.994,4841.7903,N,01004.0063,E,0,00,50.0,572.3,M,,,,0000*3F" 'example
Dim checksum
n = 1
End Sub
Sub App_Start
Form1.Show
bit.New1
sign = StrAt(nmea,1)
Do Until sign = "*"
sign = Int(Asc(sign))
checksum = bit.XOR(checksum,sign)
n = n + 1
sign = StrAt(nmea,n)
Loop
Msgbox("ASCII: " & checksum & CRLF & "HEX: " & StrToUpper(bit.DecToHex(checksum)))
End Sub