Arduino code
void setup() {
Serial.begin(9600);
pinMode(GREEN_LED, OUTPUT);
pinMode(RED_LED, OUTPUT);
pinMode(BLUE_LED, OUTPUT);
Serial.write("x\n");
}
void loop() {
if(Serial.available() > 0){
if(first == true){ Serial.read(); first = false; }
if(Serial.peek() == 'r'){
analogWrite(RED_LED, (Serial.readString() + Serial.readString() + Serial.readString()).toInt());
}
else if(Serial.peek() == 'g'){
analogWrite(GREEN_LED, (Serial.readString() + Serial.readString() + Serial.readString()).toInt());
}
else if(Serial.peek() == 'b'){
analogWrite(BLUE_LED, (Serial.readString() + Serial.readString() + Serial.readString()).toInt());
Serial.write("x\n");
}
else{
error();
}
Serial.println(String(brightnessR) + "," + String(brightnessG) + "," + String(brightnessB) + "\n");
}
}
While simple there is an issue, probably due to my inability to understand the Serial methods. It begins with sending a test byte down the serial to tell the C# program on the computer that it can begin sending information. Next it checks if there are any bytes in the serial and if so it checks if the first byte matches any of the either r, g, or b and grabs the next three bytes from the serial and turns it into an integer.
On the visual studio side
string getRGB(Color rgb)
{
String rValue = "r";
if (type == 0)
{
if(rgb.R < 100)
{
rValue += "0";
}
if (rgb.R < 10)
{
rValue += "0";
}
type++;
return rValue + (rgb.R).ToString() + "\n";
}
String gValue = "g";
if (type == 1)
{
if (rgb.G < 100)
{
gValue += "0";
}
if (rgb.G < 10)
{
gValue += "0";
}
type++;
return gValue + (rgb.G).ToString() + "\n";
}
String bValue = "b";
if (type == 2)
{
if (rgb.B < 100)
{
bValue += "0";
}
if (rgb.B < 10)
{
bValue += "0";
}
type = 0;
return bValue + (rgb.B).ToString() + "\n";
}
return "";
}
public void SerializeRGB()
{
Color RGB = GetColorFromScreen(new Point(1160, 450));
if (LineOpen())
{
Updater(getRGB(RGB));
}
else
{
Values.Text = "Error\nError\nError";
}
}
public void Updater(String n)
{
Values.Text = n;
WriteSerial(n);
}
On visual studio if it detects that the arduino has requested data with the 'x' then it sends a string through the serial comprised of either r000 g000 b000 with the appropriate rgb values of the middle pixel on my screen.
The idea of this program is to translate screen colors onto a LED RGB strip hooked up to the Arduino. Currently the problem comes in that the program cannot identify whether there is an r,g or b at the beginning of the string and never gives a true for an if(){} statement and always end up on the else{}.
If anyone could help me solve this serial communication problem it would be very appreciated :)
Notes: Serial.readString() returns a string, Serial.read() returns the next byte in the serial.