Arduino Serial 读取并解析 HEX

Arduino Serial read and parse HEX

我正在尝试为 DMX 软件 Freestyler 创建一个 Arduino 接口,但由于知道接收到的数据的编码而难以解析接收到的数据。

下图是我连接到 Freestyler 的串行监视器,用于查看传入数据,格式非常简单,每个通道 3 个字节。第一个字节是startOfMessage,第二个字节是通道号,第三个字节是通道值。

串口监视器显示为十六进制和十进制。

为了测试,我尝试在正确解析 startOfmessage(常量)时打开 LED。

byte myByte; 
void setup(void){
Serial.begin(9600); // begin serial communication
pinMode(13,OUTPUT);
}

void loop(void) {
if (Serial.available()>0) { // there are bytes in the serial buffer to     read
  while(Serial.available()>0) { // every time a byte is read it is   expunged 
  // from the serial buffer so keep reading the buffer until all the bytes 
  // have been read.
     myByte = Serial.read(); // read in the next byte

  }
  if(myByte == 72){
    digitalWrite(13,HIGH);
  }
  if(myByte == 48){
    digitalWrite(13,HIGH);
  }
  delay(100); // a short delay
  }

 }

谁能给我指明正确的方向?

您必须检测 startOfMesage 并使用它读取通道和值。因此,从串行读取字节直到检测到“0x48”

byte myByte, channel, value;
bool lstart = false; //Flag for start of message
bool lchannel = false; //Flag for channel detected
void setup(){
    Serial.begin(9600); // begin serial communication
    pinMode(13,OUTPUT);
}

void loop() {
   if (Serial.available()>0) { // there are bytes in the serial buffer to read
      myByte = Serial.read(); // read in the next byte
      if(myByte == 0x48 && !lstart && !lchannel){ //startOfMessage
         lstart = true;
         digitalWrite(13,HIGH);
      } else {
         if(lstart && !lchannel){ //waiting channel
             lstart = false;
             lchannel = true;
             channel = myByte;
         } else {
            if(!lstart && lchannel){ //waiting value
               lchannel = false;
               value = myByte;
            } else {
               //incorrectByte waiting for startOfMesagge or another problem
            }
         }
      }
   }
}

不是很优雅,但可以工作。