在我当前的项目中,我有 RFID 徽章,它向我的 Arduino UNO
(例如:2700BBA0E8
)发送一个 10 个字符的 ID。文档说“Printable ASCII”,但我不知道它是否总是 [0-9A-F]
。
在 Arduino 上,内存是有限的:
char
是1字节
int
是2 个字节
long
是4 个字节
int
或 long
比 char[10]
更短并且更易于比较 (strcmp()
vs ==
),所以我想知道如何将接收到的 10 个字符(串行)一个一个地转换为 int
或 long
?
谢谢你的帮助
最佳答案
如前所述,您想将 5 个字节放入只能存储 4 个字节的 long
中。此外,您必须使用结构:
struct RFIDTagId
{
unsigned long low;
unsigned long high; // can also be unsigned char
};
然后使用类似的东西:
unsigned int hex2int(char c)
{
if (c >= 'A' && c <= 'F')
return (c - 'A' + 0x0A);
if (c >= '0' && c <= '9')
return c - '0';
return 0;
}
void char2Id(char *src, RFIDTagId *dest)
{
int i = 0;
dest->low = 0;
for(i = 0; i < 8; ++i)
{
dest->low |= hex2int(src[i]) << (i*4);
}
dest->high = 0;
for(i = 8; i < 10; ++i)
{
dest->high |= hex2int(src[i]) << ((i-8)*4);
}
}
并比较 2 个 id:
int isRFIDTagIdIsEqual(RFIDTagId * lhs, RFIDTagId * rhs)
{
return lhs->low == rhs->low && lhs->high == lhs->high;
}
或者如果你真的有c++:
bool operator==(RFIDTagId const & lhs, RFIDTagId const & rhs)
{
return lhs.low == rhs.low && lhs.high == lhs.high;
}
关于c++ - 10 个字符字符串到 Arduino 上的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38696032/