我正在尝试通过串行向 Arduino 发送颜色。这是在我的 mac 上运行的 Objective-C 代码,它将颜色发送到 Arduino:
unsigned char rgb[4];
rgb[1] = ...some color
rgb[2] = ...some color
rgb[3] = ...some color
rgb[0]=0xff; //I am setting the first value to 0xff so I know where to start reading the bytes
if(_serialFileDescriptor!=-1) {
write(_serialFileDescriptor, rgb, 4);
}
在我发送它之后,Arduino 接收它。我首先检查它读取的第一个字节是否为 0xff 以使 Arduino 与计算机同步。如果是,我继续并获得颜色。现在的问题是,显然第一个字节永远不会是 0xff 并且永远不会输入 if 语句。
void loop(){
//protocol expects data in format of 4 bytes
//(xff) as a marker to ensure proper synchronization always
//followed by red, green, blue bytes
char buffer[4];
if (Serial.available()>3) {
Serial.readBytes(buffer, 4);
if(buffer[0] == 0xff){ //when I comment out the if statement code works fine but //the colors which are read are wrong
red = buffer[1];
green= buffer[2];
blue = buffer[3];
}
}
//finally control led brightness through pulse-width modulation
analogWrite (redPin, red);
analogWrite (greenPin, green);
analogWrite (bluePin, blue);
}
我不明白为什么第一个读取字节是 bever 0xff,即使在 Objective-C 代码中将其设置为此。