JeremyBlum.com

v3.1

Tutorial 4 for Arduino: Analog Inputs

| 111 Comments

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:

GNU GPL License Distributed under the GNU General Public (Open-Source) License.
Please Attribute and Share-Alike.


111 Comments

  1. Pingback: Tweets that mention JeremyBlum.com » Arduino Tutorial 4: Analog Inputs -- Topsy.com

  2. Pingback: Must-See Beginner Tutorials For Arduino | dev.SquareCows.com

  3. 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;
    }

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. 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);

    }

    • 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.

  9. 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….

  10. 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

    • 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.

  11. 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

  12. 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 = 0x00;
    byte low = 0x00;
    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(0x50);
    Wire.send(high);
    Wire.send(low);
    Wire.send(byte(LDRreading));
    Wire.endTransmission();
    delay(200);

    // receive data back……….
    Wire.beginTransmission(0x50);
    Wire.send(high);
    Wire.send(low);
    Wire.endTransmission();
    Wire.requestFrom(0x50, 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 = 0x00;
    //high = 0x00;
    //}

    }

    Help!

  13. 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?

    • 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
      }

  14. 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.

  15. 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?

  16. 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.

    • The blog ate the spaces in the circuits. I will try puting some dots instead:

      ——————
      |…………….|
      +…………….R1
      – …………….|
      |…………….R2
      |…………….|
      ——————

      The second one:

      ——————
      |…………….|
      +…………….R1
      – …………….|—–R3—-
      |…………….R2………..|
      |…………….|…………led
      ———————————-

      • 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.

  17. 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

  18. 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);

    }

    }

  19. 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

    • 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 !

  20. 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.

  21. 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?

  22. i have an arduino deumilanove
    i want 54 adc channels whereas deumilanove has just 6 channels
    what should i do please reply

  23. 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!

  24. 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.

  25. 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.

  26. 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.

  27. 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…??

  28. 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.

  29. 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,

    • 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.

  30. 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.

  31. 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 :)

  32. 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.

  33. 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.

  34. 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.

  35. Pingback: Arduino Programming | Harrier T4 Primary/Secondary Flying Control Demonstrator

  36. 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…:)

  37. 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
    }

    • 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);
      }
      }

  38. Sir do you have codes for Heart rate sensor using photo diode and Infrared? Thanks for your help.

  39. Pingback: Tutorials for Arduino Getting Acquainted with Arduino - Arduino for ProjectsArduino for Projects

  40. 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!

  41. 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.

  42. Nice Article I now understand Analog reading from arduino

  43. Pingback: Arduino SD Cards and Datalogging -Arduino for Projects

  44. Pingback: Arduino Analog Inputs -Arduino for Projects

  45. I have been following your tutorial series recently. I have a problem :
    What can I use in place of infra red distance sensor to do the same kind of job as it is not available anywhere.

  46. hello Jeremy
    can i use any kind of npn transistor(bc547/548) for DC MOTOR or some particular kind of transistor.

  47. Pingback: Arduino tutorial on using Analog Inputs | ControllerFeed

  48. hello jermey,
    how to connect 2 ldr sensor in analog input so that they can control to different leds,servo at a time

  49. Hello Jeremy I’m having some problems with something a was wondering if you could help me I wanted to know how to control a DC motor with a flex sensor. It would be that I bend the flex sensor to make the motor go faster and when its in the straight position it would stop. So from straight its at 0 rpms and then when I start to bend it it start accelerating to as fast as it can go

  50. what exactly does ‘serial’ do?

Leave a Reply

Required fields are marked *.