gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:01:10 24 4
gpt4 key购买 nike

我正在尝试通过串行向 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 发送一个 header 字节以了解接下来是有用的信息。
  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]);

}

希望对您有所帮助!

关于c++ - 使用 Objective-c 通过串行向 Arduino 发送颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19256421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com