Arduino Project #2. How to Read an Analog Input

The magic of Arduino is done thru the use of transducers. Transducers are devices that converts between physical signals and electricity. They can either be a sensor or an actuator. Sensors detect light, force, temp, etc., and convert it to electricity. Actuators, the opposite of sensors, convert electricity into light, sound, motion, and others.

In this project, you will learn about how Arduino reads input from the analog input pin. You will also learn how to use the Serial Monitor of the Arduino IDE to take such readings.

Components and Materials

  • Arduino UNO
  • 10k potentiometer
  • Jumper Wires
  • Breadboard

Circuit

Circuit for the AnalogReadSerial sketch.

Create the circuit as shown in the picture. The outer pins of the potentiometer must be connected to +5V and the ground of the Arduino. Connect the wiper pin to analog pin A0.

The Sketch

The sketch above is an example code from the Arduino IDE that can be opened thru File > Examples > 01.Basics > AnalogReadSerial. The comments were removed for readability. Let us check out and analyze the important parts of the sketch.

setup()

The setup() method contains a single line at line 2 that says:

Serial.begin(9600);

The function Serial.begin() means to start serial communication between the computer and the Arduino Board. The number between the parenthesis states the speed of communication in bauds or bits per second. This number must also be set at the Serial Monitor of the Arduino IDE.

loop()

Let us now tackle the code inside the loop() method

int sensorValue = analogRead(A0);

The line of code above declares a variable with the name sensorValue that is of the data type int which means integer. The value will be derived from the input coming to the board thru analog pin A0.

The command analogRead() means to read the analog value coming thru the analog pin stated in between the parenthesis. The Arduino board has a 10-bit ADC (analog-to-digital converter) that handles the data coming thru the analog pin. The values may range from 0 up to 1023.

In plain terms, the line above says: read the value coming in to analog pin A0 and save it as an integer inside sensorValue.

Serial.println(sensorValue);

The line above sends sensorValue to the Serial Monitor of the Arduino IDE.

delay(1);

The delay of 1ms ensures that the current value is always updated.

Program Execution

Now that you have understood the sketch, we can upload the program to the Arduino board. Once the program is uploaded, click the Serial Monitor open to see the reading coming from the board. Turning the potentiometer knob will cause the reading to vary from 0 at the lowest to 1023 at the highest.

Have you tried this program? Tell us if you have questions in the comments section below.

Leave a Reply

Your email address will not be published. Required fields are marked *