Arduino UNO basics for C#
There are many ways to send a command from the pc to an arduino. Sandeep Bansil provides a good example of connecting and reading a serial port.
Below is a working example of how to write to a serial port based on the state of a checkbox on a windows form amd how to process the request from the pc on the arduino.
This is a verbose example, there are cleaner solutions but this is clearer.
In the example the arduino waits for either an 'a' or a 'b' from the pc. the pc sends an 'a' when a checkbox is checked and sends a 'b' when a checkbox is unchecked. The example assumes digital pin 4 on the arduino.
Arduino code
#define DIGI_PIN_SOMETHING 4
unit8_t commandIn;
void setup()
{
//create a serial connection at 57500 baud
Serial.begin(57600);
}
void loop()
{
//if we have some incomming serial data then..
if (Serial.available() > 0)
{
//read 1 byte from the data sent by the pc
commandIn = serial.read();
//test if the pc sent an 'a' or 'b'
switch (commandIn)
{
case 'a':
{
//we got an 'a' from the pc so turn on the digital pin
digitalWrite(DIGI_PIN_SOMETHING,HIGH);
break;
}
case 'b':
{
//we got an 'b' from the pc so turn off the digital pin
digitalWrite(DIGI_PIN_SOMETHING,LOW);
break;
}
}
}
}
Windows C#
This code will reside in your form .cs file. The example assumes that you have attached form events for OnOpenForm, OnCloseForm and the OnClick event to the checkbox. From each of the events you can call the respective methods below....
using System;
using System.IO.Ports;
class fooForm and normal stuff
{
SerialPort port;
private myFormClose()
{
if (port != null)
port.close();
}
private myFormOpen()
{
port = new SerialPort("COM4", 57600);
try
{
//un-comment this line to cause the arduino to re-boot when the serial connects
//port.DtrEnabled = true;
port.Open();
}
catch (Exception ex)
{
//alert the user that we could not connect to the serial port
}
}
private void myCheckboxClicked()
{
if (myCheckbox.checked)
{
port.Write("a");
}
else
{
port.Write("b");
}
}
}
Tip:
If you want to read a message from the arduino then add a timer to your form with an interval of 50
or 100
milliseconds.
In the OnTick
event of the Timer you should check for data using the following code:
//this test is used to see if the arduino has sent any data
if ( port.BytesToRead > 0 )
//On the arduino you can send data like this
Serial.println("Hellow World")
//Then in C# you can use
String myVar = port.ReadLine();
The result of readLine()
will be that myVar
contains Hello World
.
I'm sure you know that Arduino has a few samples that you can use with C#
Here's their C# page
Since you're using Visual Studio, you might be interested in this cool Visual Studio plugin for Arduino development. http://www.visualmicro.com