Arduino 5: Analog Input

Image made with Fritzing (http://fritzing.org/)

Analog input is anything that produces a varying voltage. The most common analog input is a variable resistor, or potentiometer. This example uses a potentiometer to output a varying sound wave to a speaker. Connect the middle pin on the potentiometer to analog pin 1, and the two end pins to +5V and ground. Connect one end of the speaker to pin 11 and the other end to ground.

int res=0;
void setup(){
pinMode(11,OUTPUT);
}
void loop(){
res=analogRead(1);
digitalWrite(11, HIGH);
delayMicroseconds(1000+10*res);
digitalWrite(11, LOW);
delayMicroseconds(1000+10*res);
}

Analog pins don’t need the pinMode command because they are always in input mode. An analog pin can accept a voltage between 0 and 5V, and is read using the function

x = analogRead(pin_number);

This function divides up the interval between 0 and 5V into 1024 levels, reading the voltage on pin_number and returning a value from 0 (0V) to 1023 (5V) and storing it in variable  x.  Sound is generated by turning the speaker on and off on pin 11 very rapidly, between 100 and 1000 times a second, with the timing changing with the variable x. This is accomplished by turning the speaker output pin HIGH or LOW and then pausing in that state using the function

delayMicroseconds(t);

where t is an integer representing a time in microseconds.

4 responses to “Arduino 5: Analog Input

  1. does the robot make a noise when the ward input is changed

  2. What is the value of the potentiometer ?
    How do you calculate the value ?

    Thx.
    Keep up the good work.

Leave a reply to paulbianchi Cancel reply