I am trying to send color from my app running on MAC to Arduino. This is my Arduino Code
const int pins[3] = {
8, 9, 10};
void setup() {
Serial.begin(9600);
for (int i=0; i<3; i++) {
pinMode(pins[i], OUTPUT); // init pin for channel
}
}
void loop() {
int color;
//Wait until we have the start byte)
if(Serial.available()>0)
{
int val=Serial.parseInt();
//Check we're starting at the right place
if (val == 85) {
analogWrite(8, 200);
Serial.write(val);
//Wait until we have the start byte)
while (Serial.available() < 1) { }
val=Serial.parseInt();
if (val == 170) {
Serial.write(val);
// Ensure that we have 3 data bytes
while (Serial.available() < 3) { }
for (int i=0; i<3; i++) {
val = Serial.parseInt();
Serial.write(val);
color = constrain(val, 0, 255);
analogWrite(pins[i], color);
}
}
}
}
}
Now, when I use the Arduino Serial Monitor and type in a string like "85,170,255,255,255" it all works, LED light up, it all is fine. However, when I try to use IOKit to send data from my mac I run in to problems. This is code on my mac:
uint8_t data[5];
data[0] = 85;
data[1] = 170;
data[2] = color.red*255;
data[3] = color.green*255;
data[4] = color.blue*255;
if(_serialFileDescriptor!=-1) {
write(_serialFileDescriptor, &data, 5);
}
I initialized serial port, I checked that serial port is woking by doing: write(_serialFileDescriptor, "any random string to see if data gets sent", 20);
and then checking if it was received by
if(Serial.available()>0)
{
int val=Serial.parseInt();
analogWrite(8, 200); //light up the LED to see if anything got sent
Serial.write(val);
}
Data definitely gets sent through but it is different from what it is supposed to be. For example, when I send 85, reading data back on mac from the output of Serial.write(val);
gives me "<"(which is ASCII for 60). I am confused and stuck, it was a week and I still can not figure it out. Thank you.