Datasheet

Light-Sensitive Navigation with Phototransistors • Chapter 6
Robotics with the BOE Shield-Bot 183
#include <Servo.h> // Include servo library
Servo servoLeft; // Declare left and right servos
Servo servoRight;
void setup() // Built-in initialization block
{
tone(4, 3000, 1000); // Play tone for 1 second
delay(1000); // Delay to finish tone
servoLeft.attach(13); // Attach left signal to pin 13
servoRight.attach(12); // Attach right signal to pin 12
servoLeft.writeMicroseconds(1700); // Full speed forward
servoRight.writeMicroseconds(1300);
}
void loop() // Main loop auto-repeats
{
if(volts(A3) > 3.5) // If A3 voltage greater than 3.5
{
servoLeft.detach(); // Stop servo signals
servoRight.detach();
}
}
float volts(int adPin) // Measures volts at adPin
{ // Returns floating point voltage
return float(analogRead(adPin)) * 5.0 / 1024.0;
}
How the Volts Function Works
The Arduino’s A0, A1…A5 sockets are connected to Atmel microcontroller pins that are
configured for analog to digital conversion. It’s how microcontrollers measure voltage: they
split a voltage range into many numbers, with each number representing a voltage. Each of
the Arduino’s analog inputs has a 10-bit resolution, meaning that it uses 10 binary digits to
describe its voltage measurement. With 10 binary digits, you can count from 0 to 1023;
that’s a total of 1024 voltage levels if you include zero.
By default, the Arduino’s
analogRead function is configured to use the 0…1023 values to
describe where a voltage measurement falls in a 5 V scale. If you split 5 V into 1024 different
levels, each level is 5/1024
ths
of a volt apart. 5/1024
ths
of a volt is approximately
0.004882813 V, or about 4.89 thousandths of a volt. So, to convert a value returned
by
analogRead to a voltmeter-style value, all the volts function has to do is multiply by 5
and divide by 1024.