Saturday, December 25, 2010

Arduino and C#

In the previous article we use Serial Monitor tool to view received data and send data through serial port. Today we will write our standalone Serial Monitor like tool in C#.
We will create new Window Forms Application and add the following components from the picture
C# serial tool

The refresh button will add com ports to the combo box. Let see how it is implemented
using System.IO.Ports;
...
private void refresh_button_Click(object sender, EventArgs e)
{
portlist_comboBox.Items.Clear();
foreach (string s in SerialPort.GetPortNames())
{
portlist_comboBox.Items.Add(s);
}
}
view raw 1.cs hosted with ❤ by GitHub

Now when we have the name of serial port, we need to create serial port object and connect it, then send/receive data.
private void connect_button_Click(object sender, EventArgs e)
{
...
string port_name = portlist_comboBox.SelectedItem.ToString(); // get serial port name
serial_port_ = new SerialPort(port_name, 9600); // set port name and speed 9600 bits/second
serial_port_.Open(); // connect to port
thread_ = new Thread(read_serial_port); // create thread for reading received data
thread_.Start();
...
}
...
public void read_serial_port()
{
while (serial_port_.IsOpen)
{
try
{
string str = serial_port_.ReadLine(); //
add_output(str); // add to output text box.
}
catch (TimeoutException) { }
}
}
...
private void send_button_Click(object sender, EventArgs e)
{
serial_port_.Write(send_textBox.Text);
send_textBox.Clear();
}
view raw 2.cs hosted with ❤ by GitHub

Be careful, do not write data directly to the output text box in read_serial_port function, because you can't access a control created in another thread. To do that you need to invoke some updater function like this
delegate void SetTextCallback(string newText);
private void add_output(string text)
{
if (this.output_textBox.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(add_output);
this.Invoke(d, new object[] { text });
}
else
{
this.output_textBox.Text += text;
}
}
view raw 3.cs hosted with ❤ by GitHub

Lets write the "echo" program in Arduino and see how our tool works.
void setup()
{
Serial.begin(9600);
}
void loop()
{
if (0 < Serial.available()) // See is there any coming data
{
char data = Serial.read(); // read first byte
Serial.println(data); // print data in HEX
}
}
view raw 1.pde hosted with ❤ by GitHub

Now we will upload above code to Arduino and run the tool. And it works. hurray:)
Working serial tool
Thats all. Next time we will connect accelerometer to the Arduino and write a tool to see values of sensor on the computer.

1 comment: