March 11, 2013

Programming Serial with C Sharp

I have been programming for my Ardunio and Raspberry PI. For the Ardunio, I have connected to my Raspberry PI through USB. Once I got the Ardunio drivers working, now I can communicate from the Raspberry PI, through Serial. Although there are multiple avenues on communicating with the Ardunio, I decided to load up mono on the Raspberry PI and use .Net to communicate to the Ardunio. Here is how I did it.

Let�s start with initializing the serial port:

CreateSerial creates a serial port with a port on your computer. If you are wondering if it works with mono, THEN YES IT DOES. Now because mono doesn�t give the same names to ports as windows, I put a console.writeline there to get an idea of what ports I have available to connect. After you pick a port, the rest is just standard stuff that is associated with communicating serial to an Ardunio. Stuff like, BaudRate, DataBIts StopBits and etc.

The important things to note are the following:

  1. serialPort.DataReceived
  2. serialPort.WriteLine

These 2 functions are the ways to communicate with the serial port. First, the DataReceived function, we need a call back to handle the event of when the serial port has received data:

Then we can just call WriteLine as we want to write data to the serial port we want to use. The main program can be as simple as this :

Now you can send and receive data from a serial port relatively easy. Do note, you will need to close the port, otherwise you will block other software from accessing the port, but that�s an easy close function call. This is what I used to communicate with an Ardunio to give it messages, and it was super easy. In a later article, I�ll go over how I used this in my Arudino project.