使用 Objective-c 通过串行向 Arduino 发送颜色

Sending color to Arduino through serial using Objective-c

本文关键字:Arduino 颜色 Objective-c 使用      更新时间:2023-10-16

我正在尝试通过串行将颜色发送到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);
        }

我不明白为什么第一个读取字节是永远0xff,即使在 Objective-C 代码中将其设置为此字节。

我要做的是:

  1. 从计算机中,向Arduino发送一个标头字节以了解接下来是有用的信息。
  2. 从计算机发送号码接下来的数据包数量
  3. 在Arduino上,循环通过每次串行读取到buffer[i]时的数据数。

所以代码看起来像这样(可能需要改进(:

uint8_t dataHeader = 0xff;
uint8_t numberOfData;
uint8_t rgb[3];
uint8_t redPin, greenPin, bluePin;
void setup(){
    Serial.begin(9600);
    // INITIALIZE YOUR PINS AS YOU NEED
    //
    //

}
void loop(){
    if (Serial.available() > 1) {
        uint8_t recievedByte = Serial.read();
        if (recievedByte  == dataHeader) { // read first byte and check if it is the beginning of the stream
            delay(10);
            numberOfData = Serial.read(); // get the number of data to be received.
            for (int i = 0 ; i < numberOfData ; i++) {
                delay(10);
                rgb[i] = Serial.read();
            }
        }
    }
    analogWrite (redPin, rgb[0]);
    analogWrite (greenPin, rgb[1]);
    analogWrite (bluePin, rgb[2]);
}

希望对您有所帮助!