1

我正在尝试通过串行向 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 代码中将其设置为此。

4

1 回答 1

0

我要做的是:

  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]);

}

希望能帮助到你!

于 2013-10-09T07:37:46.260 回答