Arduino Basics Lesson 1-3: “Analog Input!”

Arduino Basics Lesson 1-3: “Analog Input!”

For the “Arduino For Kooks” course, I recommend you get the Arduino Starter Kit available here.

In the previous lesson, we learned how to use a button to create a simple digital input on the Arduino. We also learned how to use the serial monitor to display the button state. In this lesson, we’re going to use a potentiometer to create an analog input and read it on the serial monitor.

The Circuit:

Connect a jumper wire from the +5V pin to pin 1 (the left pin, input, if you’re looking down the shaft) of a 10k potentiometer. Connect a second jumper wire from pin 2 (the right pin, ground) to the ground pin on the Arduino. Connect a third jumper from pin 3 (center pin, signal) to A0 on the Arduino.

The Sketch:

/*
  AnalogReadSerial

  Reads an analog input on pin 0, prints the result to the Serial Monitor.
  Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.

*/

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

Now, with just a few more lines of code, you can determine the actual voltage going through the potentiometer and into the Arduino:

/*
  ReadAnalogVoltage

  Reads an analog input on pin 0, converts it to voltage, and prints the result to the Serial Monitor.
  Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.

*/

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float voltage = sensorValue * (5.0 / 1023.0);
  // print out the value you read:
  Serial.println(voltage);
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.