Home > arduino, electronics > Arduino: A first encounter and a gotcha

Arduino: A first encounter and a gotcha

Today, I started playing with my Arduino Uno board I got a few weeks ago. Contrary to my assumption, getting started with the board was quite easy as most of it was regular C stuff with a couple of built-in functions for specific purposes.

Code organization is pretty simple too:

  • setup(): for board and variable initialization specific to your program. This is executed by Uno when it’s reset.
  • loop(): for your program logic. As the name implies, Uno keeps running this function over and over.

    That out of the way and with no specific application in mind, I started looking for interesting stuff I could do with just an Uno board at hand. Disappointingly and quite obviously, there wasn’t much I could do as all the board has is a bunch of I/O pins. So, I started looking for more resources and found an interesting website by an interesting person at http://www.ladyada.net/learn/arduino/index.html
    I started following the tutorial, until I ran into a problem. I was working on the example in Lesson3 and was trying to connect LEDs to each of the 13 I/O pins. But, the LED wasn’t blinking as brightly as it should, except on the 13th and 0th pins. A brief search on Google made me think that I either blew up the LED or shorted the pins on the board, as the output voltage from pins 1-12 read a value something like 1.5V while the output voltage from 0 and 13 read 2.8V. After manually testing each pin’s output voltage and checking the program, I realized that I made a mistake in code. I forgot to set the pins to OUTPUT. The thing is each pin on the Uno board can be used either for Input or Output, and this has to be explicitly set in the program. Otherwise, the board assumes defaults for each pin. A simple line in the setup() function that said pinMode(pin#, OUTPUT) for each pin did the job.

It made me realize that pin 13 was working because it was already setup as OUTPUT in the blink example that I was using and pin 0 was setup as OUTPUT because it is the Serial “Output” port. A quick look at the official documentation also confirmed the same.

Finally, I ended up connecting an LED to each I/O pin and made alternative LEDs blink. Not quite impressive, but a good learning experience on first encounter. Here is the final code:

/*
  Blink
*/
void setup() {
  /* Setup all pins as output pins and turn on
  LEDs connected to even numbered pins */
  for(int i=2; i<=12; ++i) {
    pinMode(i, OUTPUT);
    digitalWrite(i, i%2==0 ? HIGH : LOW);
  }
}

void loop() {
  /* Reverse state of each LED */
  for(int i=2; i<=12; ++i) {
    digitalWrite(i, digitalRead(i)==LOW ? HIGH : LOW);
  }
  delay(500);
}
  1. No comments yet.
  1. No trackbacks yet.