Using Digital Pins for Output
Assumptions
I am assuming that you have already done the following:
- Created a project in Visual Studio and referenced the Rhyduino.dll assembly.
- Connected an Arduino Duemilanove to your computer via a USB cable, and the computer recognizes the connection.
- The connected Arduino is running the StandardFirmata.pde sketch from the Arduino IDE version 0018.
Overview
This example demonstrates how to connect to an Arduino, put a digital pin into output mode, and then toggle the value of the pin. Specifically, we will use digital pin 13 because it is connected to an LED on the Arduino board.
Step by Step
You begin by building the basic connection like described in the
Opening a Connection to an Arduino topic. The code below assumes that the Arduino is connected to COM3.
using Rhyduino;
class Program
{
static void Main()
{
using (var arduino = new Arduino("COM3"))
{
// Do work
}
}
}
Next we add code to put the desired pin into output mode. This code would go in the section with the "Do work" comment.
arduino.DigitalPins[13].SetPinMode(PinMode.Output);
As you can see from the code, we use the
DigitalPins property of the Arduino class to manage the pins. The property is indexed such that the index value used matches the pin number on the Arduino. The valid index values are 2-13. The Arduino has additional digital pins (0-1) but those are reserved for the serial communication between your PC and the Arduino. Modification of the pin mode or value is accomplished by calling methods on the
DigitalPin object.
Setting the pin mode is accomplished by calling the
SetPinMode() method and passing in an element from the
PinMode enumeration.
Finally, set the value of the pin by using the
SetPinValue() method and passing it an element from the DigitalPinValue enumeration.
arduino.DigitalPins[13].SetPinValue(DigitalPinValue.High);
Full Code Listing
Below is the full code listing for a program that blinks the on-board LED on and off.
using System;
using System.Threading;
using Rhyduino;
class Program
{
static void Main()
{
using (var arduino = new Arduino("COM3"))
{
// Place digital pin 13 into output mode.
arduino.DigitalPins[13].SetPinMode(PinMode.Output);
// Now set the pin to alternating high and low values with
// a pause in between. On a stock Arduino Duemilanove, this will
// blink the LED on the device.
for (var i = 0; i < 20; i++)
{
arduino.DigitalPins[13].SetPinValue(
((i % 2) == 0)
? DigitalPinValue.High
: DigitalPinValue.Low
);
Thread.Sleep(TimeSpan.FromSeconds(.25));
}
}
}
}