如何使用Arduino在串行数据中附加一个字符串,例如“ AA 00 01 00 FF FF A2”?
电子/通信
0 432
1

下面是我自己写的代码

String comdata;
void loop() {
  while (Serial2.available() > 0) {
    c = Serial2.read();
    //c is "AA 00 01 00 FF FF A2"
    comdata +=c;
  }
  if(comdata.length()>0){
    Serial.println(comdata);
    //YES on HEX mode ;print "AA 00 01 00 FF FF A2"  
    }
    delay(1000);
}
收藏
2021-02-04 02:49 更新 我爱喝牛奶G •  1967
共 1 个回答
高赞 时间
0

如果我理解没有错误,你可以试试下面的代码

uint8_t str[64];
uint8_t chrCtr = 0;
uint16_t twoChr;
boolean isSecondChr = false;

void setup()
{
  Serial.begin(57600);
}

void loop()
{
  uint8_t chr;
  while (Serial.available())
  {
    chr = Serial.read();
    if ('a' <= chr && chr <='f')
    {
      chr &= 0x5F; // make it uppercase
    }
    if ('0' <= chr && chr <= '9' || 'A' <= chr && chr <= 'F')
    {
      if (!isSecondChr)
      {
        twoChr = chr << 8;
        isSecondChr = true;
      }
      else
      {
        twoChr |= chr;
        isSecondChr = false;
        str[chrCtr++] = hexToAscii(twoChr);
        if (chrCtr == 63)
        {
          str[chrCtr] = 0; // A string always terminated by zero
          Serial.println((char *)str);
          chrCtr = 0;
        }
      }
    }
    else if (chr == '#') // input terminated
    {
      str[chrCtr] = 0; // A string always terminated by zero
      Serial.println((char *)str);
      chrCtr = 0;
    }
    else
    {
      isSecondChr = false;
      // other character will be dropped
    }
  }
}

uint8_t hexToAscii(uint16_t hexWord)
{
  return (hexToBin(highByte(hexWord)) << 4) + hexToBin(lowByte(hexWord)); 
}

uint8_t hexToBin(uint8_t hexByte)
{
  return hexByte <= '9' ? hexByte - 48 : hexByte - 55;
}

收藏
2021-02-04 02:50 更新 蝈蝈 •  220