This tutorial was featured on the official Arduino blog on 3/9/2011
This week is all about analog inputs for the arduino. I’ll show you how you can use a voltage divider circuit (see episode 3) and a variable resistor to make an analog sensor. We’ll also use a Sharp IR distance sensor as an analog input to detect distance and movement (with some clever programming). By the end of this episode, you will be able to create your own emergency lighting system! Without further adieu, check out this week’s tutorial on analog inputs for the arduino…
One more thing: You only have 1 more week to submit your arduino projects and win a soldering station – get going!
You can download the files associated with this episode here:
Distributed under the GNU General Public (Open-Source) License.
Please Attribute and Share-Alike.













Pingback: Tweets that mention JeremyBlum.com » Arduino Tutorial 4: Analog Inputs -- Topsy.com
Pingback: Must-See Beginner Tutorials For Arduino | dev.SquareCows.com
May 19, 2011 at 10:00 am
For your motion little light and moting project I don’t understand how it will work. If lastDist = current distance then your circuit should always be on.
int motionPin = 0;
int lightPin = 1;
int ledPin = 9;
//Distance Variables
int lastDist = 0;
int currentDist = 0;
//Threshold for Movement
int thresh = 200;
void setup()
{
//The LED pin needs to be set as an output
pinMode(ledPin, OUTPUT);
}
void loop()
{
// read the sensor
int lightVal = analogRead(lightPin);
currentDist = analogRead(motionPin);
//Does the current distance deviate from the last distance by more than the threshold?
if ((currentDist > lastDist + thresh || currentDist < lastDist – thresh) && lightVal < 800)
{
digitalWrite(ledPin, HIGH);
delay(1000);
}
else
{
digitalWrite(ledPin, LOW);
}
lastDist = currentDist;
}
May 19, 2011 at 4:46 pm
Don’t forget that it’s in a loop. It gets reset at the beginning of the loop each time.
May 26, 2011 at 9:50 am
Thanks now I get it.
July 7, 2011 at 11:00 am
Very nice. As a rank beginner it took me a little while to realize I needed to click on the serial monitor icon in order to see the output.
July 8, 2011 at 8:20 pm
Thanks for the info about using Eagle to read the .sch file. I had been hoping it might help me understand the wiring for the last phase of tutorial, adding the Sharp distance sensor. If at some point you could add a photo close up of the board after that had been added it would be very helpful. Even if that’s not possible, thanks for your great work.
July 9, 2011 at 4:13 pm
The distance sensor wires right in. Red to 5V, Black to Ground, Yellow to an analog input of your choice.
July 14, 2011 at 10:39 pm
Could you post a picture of the board itself? I’m completely new to the Arduino and have very little experience with electronics and I’m not sure what wires go where. Thank you, the tutorials are great.
July 14, 2011 at 11:35 pm
It’s no different from looking at the schematic. There are only three wires, and they plug right into signal, ground, and power on the arduino. There is a picture on this page: http://luckylarry.co.uk/arduino-projects/arduino-using-a-sharp-ir-sensor-for-distance-calculation/
July 24, 2011 at 2:59 pm
I apologize. I was referring to the project where the LED gradually gets brighter as the room gets darker using the map function. And I am unfortunately unable to download the schematic.
July 24, 2011 at 3:14 pm
Never mind. I figured it out. :)
July 17, 2011 at 11:39 am
Thanks, that’s helpful. My current concern is that the output on all the other analog pins seem affected, e.g., using Recipe 4.9 in the Arduino Cookbook, which takes output from all the Arduino pins, if I stay away from the sensor which is on A1, I see something like this:
A0 = 284
a1 = 68
a2 = 136
a3 = 174
a4 = 216
a5 = 230
while if I put my hand a foot away from the sensor, they all change radically with a1 going to about 430 while all the others jump to between 300 and 405. Shouldn’t the others stay unaffected by what’s happening via A1? This is with a setup like the luckylarry picture; only the Sharp rangefinder present.
July 17, 2011 at 12:00 pm
Ah, I just found this, so I guess that what I’m seeing is normal:
“Note
If the analog input pin is not connected to anything, the value returned by analogRead() will fluctuate based on a number of factors (e.g. the values of the other analog inputs, how close your hand is to the board, etc.).”
http://www.arduino.cc/en/Reference/AnalogRead
July 17, 2011 at 2:01 pm
Good catch, you’ve found the issue. You’re just seeing noise on the other inputs. If it bothers you, can always connect them to ground.
July 26, 2011 at 6:48 pm
I typed a similar code using a microphone, however, even though the serial monitor shows the value of the sound level to be less than 900, the led still turns on. Why is this?
int ssense =0;
int ledPin =9;
void setup(){
pinMode(ledPin, OUTPUT);
}
void loop(){
int val = analogRead(ssense);
if(val > 900) digitalWrite(ledPin, HIGH);
delay(5000);
else digitalWrite(ledPin, LOW);
}
July 27, 2011 at 12:42 am
You can’t have anything between an if and an else statement. You are ne er actually executing the else statement. Use curly brackets and include the delay in the if statement.
August 14, 2011 at 7:41 am
Hi, thanks for ur tutorials. I just wanted to ask what was actually that java com 23 that u used in putting the signals of 1, 0 ,1 etc….
September 24, 2011 at 11:39 pm
Hey Jeremy! Awesome tutorial series. I’m a complete newbie to this world. My first project is an electronic trip-wire. I’m using info from this tutorial regarding the photoresistor and a simple keychain laser pointer. The wiring is all like in your video and I have serial monitor up printing values every half-second.
Right now, room light, the value is 384. If I cover with black paper, I can get it to 155. I will shine the laser pointer on it and get reading of 1006. As soon as I turn the laser off, though, I expect the reading to fall back to room level of 384.
Instead, the reading skyrockets to 3845!
Back to the black paper and 1525 is the low point. Laser again, I hit around 9840 for a few readings then, laser still on, it dropped back to 1005. Laser off, back to 3803.
What’s going on with these numbers?
TIA!
-Matthew
October 28, 2011 at 2:18 pm
That’s really strange… I’m not entirely sure, but I suspect you can fix it by replacing the photoresitor with phototransistor that will switch open and closed when you aim the laser at it.
October 11, 2011 at 4:05 pm
hi mr jere
i need help u how i can programing my arduino board because i need it for my project its about home automation using arduino
October 28, 2011 at 2:30 pm
Please post a specific question if you need help. I cannot write all your code for you.
November 21, 2011 at 9:21 pm
Hi Jeremy
Love your videos. I am trying to write analog values from a LDR just like I’ve seen in the videos. I get the values to the serial monitor just like you have but I can’t write them to 24LC32A. When I read back to serial screen there are no values there. I have the physical set up OK: the select pins are all grounded etc.
What am I doing wrong?
/***************************************************************
* Write values to eeprom 24LC32A and read them back one value **
* at a time until memory full **
***************************************************************/
#include
int LDRreading;
//int data = ‘A’;
byte high = 0×00;
byte low = 0×00;
boolean ledState = 0;
void setup(void) {
Wire.begin();
Serial.begin(9600);
}
void loop() {
int LDRreading = analogRead(A0);
Serial.println(LDRreading);
// send the eeprom a byte
Wire.beginTransmission(0×50);
Wire.send(high);
Wire.send(low);
Wire.send(byte(LDRreading));
Wire.endTransmission();
delay(200);
// receive data back……….
Wire.beginTransmission(0×50);
Wire.send(high);
Wire.send(low);
Wire.endTransmission();
Wire.requestFrom(0×50, 1);
delay(200);
//……..and print it to serial
Serial.print(“LDR is “);
Serial.print(int(Wire.receive()));
Serial.print(” address “);
Serial.print(int(high));
Serial.print(” “);
Serial.println(int(low));
digitalWrite(13,(ledState = !ledState));
if (low == 255) high++;
low++;
//if (high == 0x0F) {
//low = 0×00;
//high = 0×00;
//}
}
Help!
December 12, 2011 at 8:15 pm
First off, Your Videos are excellent and I am learning something new every time I watch one. Keep up the good work.
Is there a good way to set a 2.5v or center ref? I would like to have an analog input from a joystick 0v-5v and limit it’s output to something like 1v-4v and keep the 2.5v center ref before feeding the signal to a motor controller?
It looks like the mapping functions will work but how would a center value be set? Also if the analog signal from the joystick was lost I would like the output signal to automatically go to a 2.5v value. I think this would be a PWM output but a have seen a filter used to simulate analog outputs.
Any suggestions?
December 13, 2011 at 6:01 pm
This is what I have so far. I have not figured out how to set options with dip switches or how to condition the output signal.
//Steering control: 0v-2.4v left, 2.5v center, 2.6v-5v right
//Gas_Brake control: 0v-2.4v brake on, 2.5v center, 2.6v-5v gas on
//Setup
int input_steer = 0; //Inputs: Analog “input_steer” is for steering left and right on analog pin 0
int input_gas = 1; //Inputs: Analog “input_gas” is for gas and brake on analog pin 1
int output_steer = 10; //Outputs: Analog “output_steer” is for motor controller steering input
int output_gas = 11; //Outputs: Analog “output_gas” is for motor controller gas and brake input
int value_steer; //Value for reading the steering signal
int value_gas; //Value for reading the gas_brake signal
//analogRead takes 0v-5v and converts it to 0-1023
//Conversion: Analog input to Analog output value ¼ 0-1023 to 0-255
//analogWrite outputs 0-255 PWM to analog output pin
void setup() //Setup
{ //I do not know if anything is needed
}
void loop() //Setup
{
value_steer = analogRead(input_steer); //Check the input_steer convert to 0-1023
value_steer /= 4; // Converts 0-1023 to 0-255
analogWrite(output_steer, value_steer); // Output the output_steer convert to 0-255
value_gas = analogRead(input_gas); //Check the input_gas convert to 0-1023
value_gas /= 4; // Converts 0-1023 to 0-255
analogWrite(output_gas, value_gas); //Output the output_gas convert to 0-255
}
January 2, 2012 at 6:33 pm
You can set an external voltage reference of 2.5V for the ADC. Check this out: http://www.arduino.cc/en/Reference/AnalogReference?from=Reference.AREF
December 22, 2011 at 1:23 am
hi jeremy,
I am very new to arudino and i need some help.I have a question on anolog input pins.Can i make an anolog pin(analog input pin 0) to sense and after it crosses a threshold value to output a logic high i.e-the same anolog pin to sense and output a digital vaule.I am running short of digital pins.
January 2, 2012 at 6:34 pm
Yes, you can use pinMode to make it an output. But how are planning to make that work – isn’t it connected to your analog voltage source?
January 3, 2012 at 2:35 pm
Hello Jeremy,
Thank you for the videos, although I don’t understand english very well, they have helped me a lot.
I would like to suggest you to put subtitles in your videos. It would be much better to understand to people that don’t know english very well.
I have a doubt about voltage dividers. Imagine I have the following circuit:
——————
| |
+ R1
- |
| R2
| |
——————
R1=R2=100ohm and the source is 9V. The voltage between R1 and R2 would be 4.5V, right? Now imagine that I need that voltage to light a led, for example:
——————
| |
+ R1
- |—–R3—–
| R2 |
| | led
———————————–
In that case because of R3 the voltage would not be anymore 4.5V. Am I alright? What is the application of voltage dividers? In case of arduino, would not the arduino itself change the voltage from the voltage divider?
Sorry if it is a dumb question and sorry for my bad english. Thanks.
January 3, 2012 at 2:40 pm
The blog ate the spaces in the circuits. I will try puting some dots instead:
——————
|…………….|
+…………….R1
- …………….|
|…………….R2
|…………….|
——————
The second one:
——————
|…………….|
+…………….R1
- …………….|—–R3—-
|…………….R2………..|
|…………….|…………led
———————————-
January 3, 2012 at 7:03 pm
In the second image, R2 and R3 are in parallel, which would indeed change the voltage at that point. However, you can compensate for that by adjusting R1.
When you hook a voltage divider up to an input on the arduino, you do have to worry about the input impedance, but it’s generally much higher than that of the voltage divider, so its impact is fairly minimal.
January 4, 2012 at 7:33 am
I understand. Thank you very much! :)
January 22, 2012 at 7:01 am
is there any way for connecting more number of analog pins to arduino uno or by using any other extra a\d converters
mostly to connect accelerometers and flex sensors to control servo’s
February 13, 2012 at 10:31 am
Yes, you could get an ADC IC that communicates with the arduino via I2C or SPI. Here’s an example: http://www.sparkfun.com/products/8636
March 4, 2012 at 8:13 am
hello sir..i want to light led when maxsonar detect certain range in pwm mode..but id failed to that although my code got no error..can you take a look on my code
const int pwPin = 6;
int ledPin = 9;
int ledPin1=10;
int ledPin2=11;
long pulse, inches, cm;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);// will call sound
}
void loop() {
pinMode(pwPin, INPUT);
//Used to read in the pulse that is being sent by the MaxSonar device.
//Pulse Width representation with a scale factor of 147 uS per Inch.
pulse = pulseIn(pwPin, HIGH);
//147uS per inch
inches = pulse/147;
//change inches to centimetres
cm = inches * 2.54;
Serial.print(inches);
Serial.print(“in, “);
Serial.print(cm);
Serial.print(“cm”);
Serial.println();
delay(500);
if(cm =70 || cm < 140)
{
digitalWrite(ledPin1, HIGH);
}
if (cm <=140)
{
digitalWrite(ledPin2, HIGH);
}
}
April 15, 2012 at 1:30 am
Jeremy, I was asked a question by my son who has just started working with the Arduino Uno and had been asked at work. He and I have searched the web high and low and checked the spec. sheets on this product searching for an answer to the following question without results:
What is the input Impedance and capacitance of the Analog and the Digital I/O inputs?? I am about ready to try to contact the factory direct on this question. Your help would be appreciated.
Thank you, August
May 4, 2012 at 1:13 pm
They say on the datasheet that its input pins are high impedance and supposed to be optimized to use impedance circuits up to 10 kohms. But mind the fact they have pull up resistors configurable from code !
April 24, 2012 at 4:51 pm
Hello Jeremy.
I built a system that includes a constant 12V motor. I want that my micro controller will measure the current coming from the motor (about 400mA).
I connected a 0.5 Ohm resistor in line between minus motor voltage leg and ground.
The pin that connected to minus motor goes to analog input on ATMEGA1280.
When I measure voltage between analog input pin ang ground I see -0.250V that means that after analogInput function I’ll get around 50 if it positive , but I see only 0.
I think the problem is that it is negative but I cannot solve it with hardware, please help me if I can do some thing with the code.
AnalogFanValue = analogRead(AnalogFanPin);
Thank you.
April 27, 2012 at 1:31 am
Great tutorial. I have a question about analog inputs. I am using a hall sensor to measure current on my arduino. If I only use 1 input port for 1 hall sensor, I get great results. But when I put 2 hall sensors, each one in its own analog input ports, I get cross talk. Any idea how I can prevent this cross talk?
June 20, 2012 at 9:28 am
i have an arduino deumilanove
i want 54 adc channels whereas deumilanove has just 6 channels
what should i do please reply
July 13, 2012 at 12:49 pm
Does anyone know what kind of connector cable I need to connect the IR Distance Sensor used in this video to a breadboard. I ordered the exact model, but can’t figure out what kind of connector I need.
Thanks!
August 5, 2012 at 3:04 pm
It’s a JST style 3 pin connector. You can find them on sparkfun.
July 22, 2012 at 7:55 am
Remember to check the connector type for sensors. Many of them work better if the jumper wire or pigtail is ordered along with the sensor. Like the SHARP – GP2Y0A41SK0F should have a SEN-08733 jumper wire.
October 10, 2012 at 11:16 pm
I am having problem to read analog inputs like when I am trying to connect three sensors LM35, LDR, and Soil Moisture probe to A0, A1, A2, all the three sensors draw +5 from Arduino when I am trying to connect only LDR and LM35 itz workin fine then after connecting Soil moist. probe LM35 temperature readings become very fluctuvating. I feel there is some problem as the moist level increases probes start conducting there trouble starts as at zero moisture it is working fine.
October 15, 2012 at 2:19 am
I’ve been surfing the web and about wiped out until I came across this website. Now I’m subscribed to your Youtube channel and on Facebook. Thanks for these great tutorials.
October 15, 2012 at 4:05 pm
Glad to hear it!
October 20, 2012 at 9:27 pm
hey jeremy…
u r jst awesum with ur explanation….im jst new to electronics so cud u please tell me the circuit conn for d infrared sensor and LDR expt…??
December 3, 2012 at 7:16 pm
Dear Jeremy,
I made your instruction for the tutorial nr.4
But the only problem that i have faced was that the values that i get back from the photo resistor and also i have tried with temperature resistor were a little bit silly.
As a matter of fact i got back values in this order: 1023,547,0,84,705,1023,867,0,0,215,1020,1023,832,0,0,236,1023,1023,778,0,0,170,719 and etc.
The temperature and the photo sensor are from 20 kohms and i have tried with varies values of resistors for the fix resistor (from the voltage divider) that goes to ground such as 10, 16,9, 19, 20, 22, 27 kohms and etc, but the results are identical.
What is wrong? And maybe you can give me some tip if i did something wrong. As a matter of fact i have few times carefully watched your video and also parallel i have did the exercise.
Best and kind regards and i hope that you have time for a fast reply.
December 11, 2012 at 10:10 pm
I am using an arduino uno and an analog sensor. The sensor has its own 24v power source and out a value between 0-10v. I have built a voltage divider to bring the output down to 0-5 volts. I am not sure how to connect this to the arduino. The sensor only has 3 wires, +, – and the sensor output. Is it possible to connect the sensor wire to the arduino and leave it at that or do I need to connect something else? this is my first project, I learned everything I know about electric and arduinos from watching your tutorials.
Thanks,
December 18, 2012 at 1:21 pm
Connect the positive lead to a 24V power source. connect the negative lead to both the ground of the 24V power source, and the ground of the arduino. Send the signal line through the voltage divider, and feed the output of that voltage divider into an ADC pin on the Arduino.
December 28, 2012 at 10:37 am
Hello Jeremy,
I’m just starting to know a thing about programming microcontrollers, for a school project. May I ask, is it possible to program the Arduino with an ultrasonic sonar sensor (US-100) to be able to detect moving objects? By that I mean, for example, you place a sensor and a car is moving towards it or something like that.
Thanks a lot.
January 4, 2013 at 3:40 pm
Yes, that’s totally possible.
January 21, 2013 at 10:51 pm
hello! I’m just wondering if it’s possible to have a single output reading from an analog input..?
or if the state of analog input just changed (example, an LDR, from bright to dim), that’s when it will print an output on serial monitor..?
many thanks :)
January 30, 2013 at 8:20 pm
Hey Jeremy,
I’m working on a capstone project using the arduino uno to control a tracked robot. I’ve never used arduino and haven’t had any training with it but i was wondering how the last part of this tutorial would be modified so the ir sensor would read an object in front of the robot and stop and shift directions.. any help would be much appreciated.
February 5, 2013 at 7:31 am
hai,
am doing a project on navigation system for blind people using ultrasonic sensors. I want to first differentiate between different obstacles like wood, concrete, metals etc using ultrasonic sensors. Is it possible using ultrasonic sensors?? after reflection does the frequency changes?? if so is there any cmd to find the frequency of reflected wave??
Also i have another problem. I just tried to read the analog input values but i get only 0.
Pls help me out.
February 24, 2013 at 5:24 pm
Hi Jeremy.
I’m building a project which uses a thermistor in a wheatstone bridge, where I will have an arduino read an analog signal. My questions are: 1) Can I assign arduino different outputs so I can light up more than one LED for different temperature values? and 2) Am I able to translate a digital output that I am going to get from arduino into a temperature reading?
Thank you in advance.
Pingback: Arduino Programming | Harrier T4 Primary/Secondary Flying Control Demonstrator
April 4, 2013 at 12:23 pm
Could you please send me a schematic for the light and sensor project cause i cant see how exactly the connections are I would like to construct it my own. Thank you. Nice work btw…:)
April 27, 2013 at 5:04 pm
The schematics are available for download above.
April 16, 2013 at 11:23 pm
Hey Jeremy. Excellent tutorials, especially for a first time programmer like myself. I am working on a project where I have an LM19 temperature sensor, an LED, and potentiometer. I use the potentiometer to set a temperature. That temperature is compared to the actual temperature, and the LED should blink if outside a certain range. My issue is when both the temperature sensor and potentiometer are hooked up to the arduino, the actual temperature goes crazy. I have heard the problem is related to the arduino only having a single ATD converter, but I still do not know how to fix my issue. Here is my code. Any suggestions? Thanks!
#include
int tempsens = 5; // temperature sensor is attached to analog pin 5
int templed = 12; //temperature led is attached to digital pin 12
int potpin = 0; // potentiometer is attached to analog pin 0
// initialize variables
int settemp;
int acttemp;
float tempin;
float tempana;
void setup()
{
Serial.begin(9600); // baud rate
pinMode(templed, OUTPUT); // initialize ledPin as and output
}
void loop()
{
settemp = analogRead(potpin); // pull data from temperature potentiometer
settemp = map(settemp, 0, 1023, 0, 80); // map digital value of temperature potentiometer to a value betwee 0C and 80C
tempin = analogRead(tempsens); // pull data from temperature sensor
tempana = (5.0/1024.0)*tempin; // convert to analog voltage
acttemp = -1481.96+sqrt(2.1962E6+(1.8639-tempana)/(3.88E-6)); // conver analog temperature to actual temperature
// led blinks if outside of desired temperature range and is held on if inside desired temperature range
if (acttemp (settemp +5))
{
digitalWrite(templed, HIGH); // led is turned on
delay(100); // keep led on for 100 ms
digitalWrite(templed, LOW); // led is turned off
delay(100); // keep led off for 100 ms
}
else
{
digitalWrite(templed, HIGH); // led is held on
}
// print to screen
Serial.print(“Desired “);
Serial.print(settemp);
Serial.print(“C,Actual “);
Serial.print(acttemp);
Serial.print(“C.”);
delay(200); // display every 200 ms
}
April 29, 2013 at 2:52 am
I am facing a similar problem. The temperature sensor works absolutely fine when working alone but if the down key on LCD is used to start the temperature sensor then the temperature fluctuates a lot.
any help would be appreciated.
here is the code:
#include
LiquidCrystal lcd(8,9,4,5,6,7);
float tempC;
int lm35Pin = 3;
int pin0 = 0;
int a = 0;
void setup(){
Serial.begin(9600);
lcd.begin(16,2);
}
void loop()
{
pin0=analogRead(pin0);
if(pin0 < 380)//using down key button on LCD to start the temperature sensor
{
a=1;
delay(100);
}
if(a == 1)
{
tempC = analogRead(lm35Pin);
tempC = (5.0*tempC*100.0)/1024;
lcd.setCursor(0,1);
lcd.print(tempC);
delay(500);
}
}
April 20, 2013 at 5:50 am
Sir do you have codes for Heart rate sensor using photo diode and Infrared? Thanks for your help.
Pingback: Tutorials for Arduino Getting Acquainted with Arduino - Arduino for ProjectsArduino for Projects
May 2, 2013 at 5:47 pm
Hello Jeremy,
I am working on a motion platform project that I need to control air pressure from a compressor to four locations similar to a cars tires. I want to use a Arduino board to set up a loop program that will inflate and deflate the four locations as programmed. My problem is I don’t know the best method / parts to use to accomplish my project and ask if you would let me know how you would do it or any suggestions / ideas?
Thanks!
May 9, 2013 at 9:14 am
hello,
while doing arduino programming for robots , after verification it often comes expected constructor, destructor, or type conversion before ‘(‘ token. How do you solve it.
May 10, 2013 at 3:13 am
Nice Article I now understand Analog reading from arduino
Pingback: Arduino SD Cards and Datalogging -Arduino for Projects
Pingback: Arduino Analog Inputs -Arduino for Projects