How to open a connection to an Arduino

Assumptions

I am assuming that you have already done the following:
  1. Created a project in Visual Studio and referenced the Rhyduino.dll assembly.
  2. Connected an Arduino Duemilanove to your computer via a USB cable, and the computer recognizes the connection.

Writing Code

The central object in the Rhyduino library is the Arduino class. Everything starts there.

As simple as it gets

For the first example I will show you the simplest possible way to create an instance of this class and associate
it with your physical Arduino.

    using Rhyduino;

    class Program
    {
        static void Main()
        {
            using (var arduino = new Arduino("COM3"))
            {
                // Do work
            }
        }
    }

As you can see from the example, I have chosen to import the Rhyduino namespace with a using statement. It's a matter of personal preference. You choose not to, you'll just have to use fully-qualified object names.

The next thing you'll notice is that I've placed the Arduino constructor call inside a using block. The Dispose() method should always be called when you're done using an instance of the Arduino object; putting it in a using block makes sure that it's called automatically when the object goes out of scope. I often forget to dispose of objects when I'm done with them, so this saves me (and you) the headache.

There is no default constructor. At a minimum, you need to specify the COM port that the Arduino is physically connected to. If you are unsure which COM port the Arduino is using, you can use Windows Device Manager to identify the connected device.

DeviceManager.png

The code shown doesn't actually open a connection to the device immediately, rather, it waits an operation requiring a connection is performed, and then it opens the connection. Additionally, it assumes that you will be communicating with the device at the default baud rate of 57,600 baud. This is the value that is used in the StandardFirmata.pde sketch. The same value needs to be used in both places.

Being more direct

The following example builds on the previous example by showing you how to specify the COM port, baud rate, and open the connection immediately

    using Rhyduino;

    class Program
    {
        static void Main()
        {
            using (var arduino = new Arduino("COM3", 57600, true))
            {
                // Do work
            }
        }
    }

The advantage of opening the connection as part of the constructor is that you will be notified immediately (with an exception) if Rhyduino is unable to connect to the Arduino.

That's all there is to it. If you encounter problems, post them on one of our discussion lists or in the issue tracker. I want to hear about it so I can help you and/or fix the problem.

Last edited Jul 3, 2010 at 6:00 PM by RhyMednick, version 2

Comments

No comments yet.