I currently have an RGB LED connected to my arduino uno. I have just started learning Arduino. Everything works fine in general, and am using code as per the adafruit tutorial. When I interact with the Arduino through the Arduino IDE's own serial monitor, everything works fine. The issue is that I am trying to use C# to control the LED. However, the Arduino is never even getting past the if(Serial.available() > 0) line. My code is below:
C# winforms
public partial class Form1 : Form
{
static SerialPort _serialPort;
public Form1()
{
InitializeComponent();
}
private void btnSend_Click(object sender, EventArgs e)
{
_serialPort = new SerialPort();
_serialPort.PortName = "COM6";//Set your board COM
_serialPort.BaudRate = 9600;
_serialPort.Open();
byte[] sendBuf = { (byte)numRed.Value, (byte)numGreen.Value, (byte)numBlue.Value };
_serialPort.Write(sendBuf, 0, 3);
_serialPort.Close();
}
}
Arduino sketch:
/*
Adafruit Arduino - Lesson 3. RGB LED
*/
int redPin = 9;
int greenPin = 10;
int bluePin = 11;
//uncomment this line if using a Common Anode LED
#define COMMON_ANODE
void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
setColor(0,255,0);
}
void loop()
{
if(Serial.available()){
setColor(50,50,0);//To see if we even get here
delay(500); // so I can see the LED...
char bytes[3];
for(int i=0;i<3;i++){
char ch = Serial.read();
bytes[i]=ch;
setColor(ch,0,0);
delay(500);
setColor(0,0,0);
}
setColor(bytes[0],bytes[1],bytes[2]);
}
}
void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
#endif
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}
Furthermore, when I hit the "send" button on my form, the LED on my arduino labeled "TX" lights up momentarily.
Thanks, hopefully we can figure out why it doesnt work with C# but still works with the IDE Monitor.