使用 Objective-c 通过串行向 Arduino 发送颜色
Sending color to Arduino through serial using Objective-c
我正在尝试通过串行将颜色发送到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 代码中将其设置为此字节。
我要做的是:
- 从计算机中,向Arduino发送一个标头字节以了解接下来是有用的信息。
- 从计算机发送号码接下来的数据包数量
- 在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]);
}
希望对您有所帮助!
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 将"打开的CV图像"中的"颜色"转换为整数格式
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 如何在内核C++中使用1920x1080x16M图形或类似的16M颜色?(VGA)
- 如何在24位SDL_Surface上设置像素的颜色
- 人脸跟踪arduino代码的优化
- vscode下的Arduino代码出现意外编译错误
- Arduino从Txt读取整数
- 如何从SDL_Surface获取特定像素的颜色
- Arduino C++在构造函数中用参数声明对象数组
- C++ Boost::asio串行通信与Arduino无法写入
- Arduino millis() - millis() 怎么能等于 0 以外的任何东西?
- 在Arduino中将PWM通道命名为LEDC是否有特定原因
- 'val' Arduino 错误代码之前的预期'('
- 我可以在 Arduino 的库文件夹之外安装库吗?
- 如何防止每次 Arduino 启动时颜色数组都是相同的随机数组
- 带有SoftWire(I2C Emulator)库的多个tcs34725 arduino颜色传感器
- C++类创建"does not name a type"(使用 Arduino 和颜色传感器)
- c++在不同颜色之间褪色?(Arduino)
- 使用 Objective-c 通过串行向 Arduino 发送颜色