问题描述
我现在正在努力处理一些事情,我正在尝试根据一些变量生成 NMEA 消息,现在这些 0,0 需要是一个变量,所以我需要将我的变量连接到此消息字符指针。有什么建议吗?
char * message = "$CONFI,0";
Serial.println(generateChecksum(message),HEX);
int generateChecksum(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;
}
解决方法
这是在 C 中执行此操作的一种非常标准的方法。使用 sprintf
格式化字符串,但使用不应溢出缓冲区的版本,并使用从闪存而不是 RAM 获取格式字符串的版本:
#include <stdio.h>
#define NEMASIZE 30
char nemamessage[NEMASIZE+1];
... etc ...
n = snprintf_P(nemamessage,NEMASIZE,F("$CONFI,%d,%d"),a,b,c);
// now check n!!
这是在 AVR libc 库中:https://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html
而且我不知道 NEMA 字符串可以有多大,因此请根据需要进行调整! :-)