Talking to an Arduino from .NET / C#

I’ve been meaning to post this for a while but got caught up with work stuff again. Thinking that talking to an Arduino from C# should be fairly easy, I spent a good hour or so fiddling with it because I could never get the Arduino to run my sketch after establishing the serial connection. Turns out, the DTR Enable line needs to be set to high for it to start executing the program.  Here’s a quick hack which interacts with the program I posted previously:

private static System.IO.Ports.SerialPort serialPort1;
static void Main(string[] args)
{

    System.ComponentModel.IContainer components = new System.ComponentModel.Container();
    serialPort1 = new System.IO.Ports.SerialPort(components);
    serialPort1.PortName = "COM4";
    serialPort1.BaudRate = 9600;

    serialPort1.Open();
    if (!serialPort1.IsOpen)
    {
        Console.WriteLine("Oops");
        return;
    }

    // this turns on !
    serialPort1.DtrEnable = true;

    // callback for text coming back from the arduino
    serialPort1.DataReceived += OnReceived;

    // give it 2 secs to start up the sketch
    System.Threading.Thread.Sleep(2000);

    using (serialPort1)
    {
            Console.WriteLine("sending green command");
            serialPort1.Write(new byte[] { 114 } , 0, 1);
            System.Threading.Thread.Sleep(1000);

            Console.WriteLine("sending red command");
            serialPort1.Write(new byte[] { 103 }, 0, 1);

            System.Threading.Thread.Sleep(15000);
    }

}
private static void OnReceived(object sender, SerialDataReceivedEventArgs c)
{
    int ch;
    try
    {
        // write out text coming back from the arduino
        Console.Write(serialPort1.ReadExisting());
    }
    catch (Exception exc) { }
}

Comments

15 Responses to “Talking to an Arduino from .NET / C#”

  1. Mike Barrett on February 16th, 2009 8:14 pm

    rad! I’ve really got to get back into EE stuff, and Arduino seems pretty awesome.

    my buddy Ada does some cool electronics stuff, you can find some of her projects here: http://www.ladyada.net/make/index.html

  2. jochen on February 18th, 2009 10:23 pm

    You actually know Ada? Yeah, been to that web site a ton of times. Cool stuff, small world.

    I’ve been hacking C code here at the hotel, insane fun — next steps to get my own PCBs printed :-)

  3. Wes on February 19th, 2009 1:06 am

    Hi,

    I’m trying to learn how to get my Sanguino to communicate with my computer using your example but I keep getting errors. I’m using visual c# 2008 express and the AVR software but I’m a novice in both. Any suggestions?

    Thanks,

    -Wes

  4. jochen on February 19th, 2009 9:45 am

    I’m not sure how compatible the Sanguino is with the Arduino and it’s bootloader software. I don’t have one to try.

  5. wes on February 19th, 2009 1:02 pm

    Hi,

    I’ve got the Sanguino portion runnig fine. I’m having troubles with the C# code. The Sanguino is just Arduinos big brother, I used the c program from you privous post and compiled it in the AVR without any problems

  6. jochen on February 19th, 2009 2:49 pm

    Hmmm. What errors are you getting? In the simplest case your Sanguino might just not be on COM4 ;-)

  7. wes on February 19th, 2009 6:57 pm

    The errors I get are in Visual Studio C# 2008 express when I’m try to debug the c# code. If you send me an email or let me know where to send you an email. I’ll send you a screen shot with the errors I’m getting in VS.

  8. teh b on December 10th, 2009 4:56 pm

    your code was just what i was looking for, working great, thanks man!

  9. Visual Micro on April 1st, 2010 11:02 pm

    Arduino in Visual Studio Beta

    I’m keen to hear from anyone that would like to beta test an arduino extension for visual studio called [i]Visual Micro[/i]. The extension makes it easy to build on new or existing sketches.

    Visual Micromaintains sketch compatibility with arduino whilst allowing visual studios C++ intellisense to work with ANY core and ALL libraries.

    The product is “boards.txt” and “serial port” aware, retains the board and port per project and allows arduino library folders to be added via a single menu click.

    For anyone who doesn’t know or can’t remember arduino class, struct and method names the intellisense is very useful. You can read more about more Visual Micro features here

    If you would like to register as a beta tester please send us an email or use the link on the Visual Micro home page.

    Thanks

    Visual Micro Development Team

  10. Cristian Capannini on January 5th, 2012 5:46 am

    Hello i want transform this c# code into visual c# to read data into a text box. How can i? thanks for any help :D .
    I will use this program with ARDUINO UNO to manage
    activation time of the waterpump into my new home.
    Thanks! :D.
    If you want my program of water pump i will send you the code of arduino. Plz help me to build me the program.
    Thanks!

  11. Cristian Capannini on January 9th, 2012 3:21 am

    I resolved it. If you want my code i’ll post it! :D

  12. rod lopez on February 2nd, 2012 4:23 am

    Thanks a ton! Your post was great help, I didn’t know the
    serialPort1.DataReceived += OnReceived;
    was necessary! :D

  13. Arduino for Visual Studio on June 10th, 2012 2:20 pm

    I don’t use the DataReceieved event anymore. I ran some tests and found that if you have high traffic volumes reading serial data in the event blocks the windows serial port and causes serial corruptions.

    Instead I believe that it is better to use a timer at regular intervals such as 10hz. In the timer function we can test if serialPort.bytesToRead > 0 as an indicator that there is data to be read.

    The other problem with the DataReceived event is that we don’t have any control over when it is raised. Sometimes it can be raised for every incoming byte.

  14. Marco Bertschi on October 17th, 2012 10:45 am

    I wrote a detailed description of how to process commands in Arduino here:

    http://www.codeproject.com/Articles/473828/Arduino-Csharp-and-serial-interface

    However, good post! Thank you :D

  15. Branden on November 8th, 2012 10:07 am

    I am looking for some help with arduino /c#. I have researched online and am so confused. I started my my interface with java, but found c# to be much easier to learn. Basically, i have a 3 page gui that will control rgb lighting via jeenodes. I have figured out the com port connections and am now stuck trying to figure out how to read the color of the connected rgb lighting and making the background button color match as well as write the color. I have multiple leds and buttons. I am using the color picker and have figured out how to make the button background the picked c olor but do not know how to send it to the arduino. The purpose of the read is to show the current color until a new one has been picked. I also dont know how to write the arduino code to read and write the c# interface to the arduino. Any help is greatly appreciated as i am so confused.

Leave a Reply




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

-->