This is something I wanted to be able to do a little while ago but couldn't find any tutorials, so I created my own! It's just a simple console application which reads characters printed to the serial from an Arduino. It can be integrated with code to write characters to the serial from C#, to enable two way communication between the Arduino and the C# program.
I have one that I send to anyone that asks. It posts a Windows form and has proper threading to deal with the serial port in one thread and the user interface in another thread. It's a bit long to post here, and requires a number of files that in general don't need to be looked at but do need to be present. Getting them all in the right place from a series of forum posts is challenging.
PaulS, your code is very nice, with a good interface - it looks a lot better than a console application! If anyone just wants to read data from an Arduino though, and are happy with the console application, the following code is much shorter and to the point:
//Code to read serial data. Find out more at http://www.therobotlab.co.uk/2011/read-serial-c-sharp-arduino-tutorial/.
//-------------------------------------------------------------------------------------------------------------------------------------
//Set up the serial port. Use the following values for an Arduino, changing "COM3" to your own Serial Port.
SerialPort sp = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
static void Main(string[] args)
{
//Open the Program function
new Program();
}
private Program()
{
//Set the datareceived event handler
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
//Open the serial port
sp.Open();
//Read from the console, to stop it from closing.
Console.Read();
}
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//Write the serial port data to the console.
Console.Write(sp.ReadExisting());
}