Hackers – Basic Arduino inputs and outputs

Rheostat_bb

This week in the Hackers group at CoderDojo Athenry, we built on last week’s work on blinky lights, in which we made a simple circuit involving LEDs and resistors connected to an Arduino, and wrote code to get the LEDs to blink.

An LED is an example of an output from our microcontroller. We would also like to have inputs. Examples of circuit inputs are:

  • Switches
  • Dials
  • Sensors that measure something

We focused on dials, specifically a variable resistor or rheostat. This is the kind of knob or dial you find on dimmer switches, volume controls on old radios, electric guitars, and many others.

A variable resistor has 3 connectors: the two outer ones connect across a voltage source (e.g. 5V and ground pins on the Ardiuno) and the voltage at the middle pin can be adjusted from 0 to 5V by turning the knob.

We connected the middle pin of the variable resistor to Analog input 2 of the Arduino. The connections are shown above.

Then, the code to read its value is:

potValue = analogRead(potPin);

where potValue and potPin are ints that were defined already.

The value that you get is in the range 0-1024, and changes as you turn the dial.

Here is a full Arduino program to read a value and display it on the Serial Monitor window if you have a computer connected to your Arduino:

int potPin = 2;    // select the input pin for the potentiometer
int potValue = 0;  // value to read from potentiometer

void setup() {
  Serial.begin(9600);  // need for print commands later
}

void loop() {
  potValue = analogRead(potPin);    // read the value from the sensor
  Serial.println(potValue);
}

In the group, we used this as the basis to improve last week’s program. This time, the speed at which the LED blinks is controlled by turning the potentiometer dial.

The previous code to control how long the LED blinks for was:

delay(one_second);

We changed this to:

delay(potValue);

Of course, we also had to add the code to read the potentiometer value at the top of the loop() function.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s