在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同

Using sscanf on an Arduino gives a mismatch with const char * and return value always the same despite different values for the input

本文关键字:返回值 输入 不匹配 sscanf Arduino char const      更新时间:2023-10-16

arduino IDE编译器非常宽容,并且允许将变量定义为"字节",这是一个uint8_t或无符号字符,它似乎正在运行。但它不会直接插入此测试代码。我正在使用Arduino IDE和PlatformIO来比较结果。为了调试,我将此代码插入 OnlineGBD C++模拟器。我需要提供代表二进制值的十六进制字节,就好像我像这样插入它一样:

const char s[] = { 0x37, 0x74, 0x37, 0 } ; 00110111,01110100,00110111,0 写文本包

我必须将模拟器中的"byte b[6]"更改为"char b[6]"才能使其运行,但 printf 看起来它给了我指针,而不是内存位置中的内容。我的第二个 Printf 尝试将"b"变量格式化为 %p 和 %x 进行测试,并在值前面加上 0x7ffe,因此 (void**(b 是 0x7ffexxxx,b 的值是 xxxxxxxxxx。

最后,nBytes 的返回值始终为"7"。它显然应该给我它找到的字节数。我想我在指针和字符之间感到困惑。谢谢。

void RegisterList::writeTextPacket(const char *s) volatile{
int nReg;
byte b[6];
int nBytes;
nBytes=sscanf(s,"%x %x %x %x %x %x",&nReg, b, b+1, b+2, b+3, b+4)-1;  // return number of bytes
printf("%dn",nBytes);
printf("%d, %p, %x, %x, %x, %x, %x", nReg, (void**) b, b, b+1, b+2, b+3, b+4);
loadPacket(nReg,b,nBytes,0,1);  // loadPacket(int nReg, byte *b, int nBytes, int rep, int flag)
} 

成功!谢谢你的大力帮助。将"byte"更改为"uint8_t"(Arduino有一个"typdef uint8_t byte"来处理这个问题(并将%hhx替换为%x摆脱了警告。而这个测试代码:

const char *s="16 A9 69 55 C6 A8";
int nReg;
uint8_t b[6];
int nBytes;
nBytes=sscanf(s,"%d %hhx %hhx %hhx %hhx %hhx",&nReg, b, b+1, b+2, b+3, b+4)-1;  // return number of bytes
printf("%dn",nBytes);
printf("%d, %X, %X, %X, %X, %X", nReg, *b, *(b+1), *(b+2), *(b+3), *(b+4));

给出这个正确的结果,并只计算整数 nReg 数后面的十六进制数:

5

16, A9,69, 55, C6, A8