c++ - 10 个字符字符串到 Arduino 上的 int

标签 c++ c avr arduino-uno

在我当前的项目中,我有 RFID 徽章,它向我的 Arduino UNO(例如:2700BBA0E8)发送一个 10 个字符的 ID。文档说“Printable ASCII”,但我不知道它是否总是 [0-9A-F]

在 Arduino 上,内存是有限的:

  • char1字节
  • int2 个字节
  • long4 个字节

intlongchar[10] 更短并且更易于比较 (strcmp() vs ==),所以我想知道如何将接收到的 10 个字符(串行)一个一个地转换为 intlong?

谢谢你的帮助

最佳答案

如前所述,您想将 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/

相关文章:

c++ - 在 C++ 中将字符串附加到 const char* 时出现编译时错误?

c - C 中的原子读取

c - 在 Matlab 的 c 代码中设置 #define

linux平台netbeans6.8中配置gdb编译器

c++ - 防止在 C++ 的构造函数中隐式转换数字类型

c++ - 同步push_back和std::thread

compiler-construction - AVR XYZ 寄存器

c - AVR C : Serial Communication Clear Screen

c++ - "warning: operation of ... may be undefined"用于三元运算——不是 if/else block

c - 从 EEPROM 读取