So I am trying to learn how to integrate Visual C# to control my Arduino. I have the Visual C# program correct, I know that for sure. My problem lies in the Arduino code. How it works is the Arduino is looking for certain letters the from serial. Depending on what letter is printed to the serial the Arduino is supposed to light up an RGB LED accordingly. For prototyping purposes I was just using the serial monitor to print the letters. I cannot figure out why it will not work.
void setup()
{
Serial.begin(9600);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
digitalWrite(12, HIGH);
digitalWrite(11, HIGH);
digitalWrite(10, HIGH);
}
void loop()
{
char myChar;
myChar = Serial.read();
if(myChar = 'r')
{
digitalWrite(12, HIGH);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
}
else if (myChar = 'g')
{
digitalWrite(12, LOW);
digitalWrite(11, HIGH);
digitalWrite(10, LOW);
}
else if (myChar = 'b')
{
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, HIGH);
}
else
{
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
}
}
Hi matt
char myChar;
myChar = Serial.read();
You should use Serial.available() to check if a character has been received before you call Serial.read(). Have a look at the first example on this page: Gammon Forum : Electronics : Microprocessors : How to process incoming serial data without blocking
if(myChar = 'r')
There is a difference in C between = and ==. Check out this: http://arduino.cc/en/Reference/If
Regards
Ray
KenF
October 24, 2014, 8:09pm
#3
Without attempting to work out your problem. Could I suggest that a switch statement might be easier to maintain.
For example
void setup()
{
Serial.begin(9600);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
digitalWrite(12, HIGH);
digitalWrite(11, HIGH);
digitalWrite(10, HIGH);
}
void loop()
{
char myChar;
if (Serial.available())
{
myChar = tolower(Serial.read());
switch(myChar)
{
case 'r':
digitalWrite(12, HIGH);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
break;
case 'g':
digitalWrite(12, LOW);
digitalWrite(11, HIGH);
digitalWrite(10, LOW);
break;
case 'b':
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, HIGH);
break;
default:
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
}
}
}
Edited as per econjack's suggestion.
I like Ken's solution, since it's pretty clean. I would make one suggestion. Change the statement:
myChar = Serial.read();
to:
myChar = tolower(Serial.read());
That way, if they enter a capital letter, it still hits the right switch expression.
KenF
October 24, 2014, 9:16pm
#5
econjack:
I would make one suggestion. Change the statement:
myChar = Serial.read();
to:
myChar = tolower(Serial.read());
That way, if they enter a capital letter, it still hits the right switch expression.
Have to agree with this. I'll do it right away