The Woo The Woo -4 years ago 62
C# Question

Turning On Arduino LED

I am trying to get code on an Arduino to be contacted by my C# program, to turn on and off the onboard (pin 13) LED. This is the code that I have loaded into the Arduino:

void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
}
void loop()
{
if (Serial.available() > 0)
{
int b = Serial.read();
if (b == 1)
{
digitalWrite(13, HIGH);
}
else if (b == 0)
{
digitalWrite(13, LOW);
}
Serial.flush();
}
}


I have found and downloaded this code and got the LED to work! (Hooray!)

I have tried to reverse engineer the code into my own, with a simple OnButton and OffButton, but it will not work. Can someone please take a look at the code below and tell me if I'm missing something obvious.

using System.IO;
using System.IO.Ports;

public static System.IO.Ports.SerialPort serialPort1;
private delegate void LineReceivedEvent(string line);

private void establishConnection()
{
System.CompnentModel.IContainer components = new System.ComponentModel.Container();
serialPort1 = new System.IO.Ports.SerialPort(components);
serialPort1.PortName = "COM7";
serialPort1.BaudRate = 9600;
serialPort1.DtrEnable = true;
serialPort1.Open();
}
private void terminateConnection()
{
serialPort1.Close();
}
private void OnButton_Click(object sender, EventArgs e)
{
establishConnection();
serialPort1.Write(new byte[] { Convert.ToByte("1") }, 0, 1);
terminateConnection();
}
private void OffButton_Click(object sender, EventArgs e)
{
establishConnection();
serialPort1.Write(new byte[] {Convert.ToByte("0") }, 0, 1);
terminateConnection();
}


Any help would be greatly appreciated. I can see when I click the C# buttons that the Ardiuno is receiving some kind of command, and it works with the code that I downloaded in the link above... I'm pulling my hair out...

Answer Source

Arduino code:

void setup()
{
 Serial.begin(9600);
 pinMode(13, OUTPUT);
}
void loop()
{
 if (Serial.available() > 0)
 {
  int b = Serial.read();
  if (b == 1)
  {
   digitalWrite(13, HIGH);
  }
  else if (b == 0)
  {
   digitalWrite(13, LOW);
  }
  Serial.flush();
 }
}

C# code:

using System.IO;
using System.IO.Ports;

public static System.IO.Ports.SerialPort serialPort1;
private delegate void LineReceivedEvent(string line);

public Form1()
{
   InitializeComponent();
   System.CompnentModel.IContainer components = new System.ComponentModel.Container();
   serialPort1 = new System.IO.Ports.SerialPort(components);
   serialPort1.PortName = "COM7";
   serialPort1.BaudRate = 9600;
   serialPort1.DtrEnable = true;
   serialPort1.Open();
}
private void OnButton_Click(object sender, EventArgs e)
{
   serialPort1.Write(new byte[] { Convert.ToByte("1") }, 0, 1);
}
private void OffButton_Click(object sender, EventArgs e)
{
   serialPort1.Write(new byte[] { Convert.ToByte("0") }, 0, 1);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download