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 or Uno 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 Uno IDE (v21).
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
Bare Minimum Rhyduino Example topic. The code below assumes that the Arduino is connected to COM7.
Code Snippet
- using Rhyduino;
-
- class Program
- {
- static
void Main()
- {
- using (var arduino =
new Arduino("COM7"))
- {
-
// Do work
- }
- }
- }
Next we add code to put the desired pin into OUTPUT mode. This code will go in the section with the “Do work” comment.
Code Snippet
- 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.
Code Snippet
- arduino.DigitalPins[13].SetPinValue(DigitalPinValue.High);
Full Code Listing
Below is the full code listing for the BlinkPin13 sample application. It blinks the on-board LED on and off.
Code Snippet
- using System;
- using System.Threading;
- using Rhyduino;
-
- class Program
- {
- static void Main()
- {
- // Place the constructor call inside a using block so that when program execution
- // goes outside the using block the Arduino object will be automatically disposed.
- // [IMPORTANT] Replace the COM port value with the COM port that your device is
- // connected to.
- using (var arduino =
new Arduino("COM7"))
- {
- // 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));
- }
- }
- }
- }