The ultrasonic sensor (eyes) on the front of your robot is used to estimate the distance to an object in front of the robot. It does this by “pinging” (emitting an ultrasonic signal which bounces back to a sensor over the “eyes”). The code then converts the duration of the time it took to emit and sense the signal to a distance.
When the robot is plugged into your computer, and you have an open serial monitor (select “Tools” from your Arduino IDE menu), you will see a continuous stream of output in the monitor describing the distance (in CM) of an object in front of the robot’s ultrasonic sensor (eyes):
// Ultrasonic sensor pins
#define echoPin A0
#define pingPin 3
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
// ultrasonic sensors
pinMode(pingPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int distance = msToCm( ping() );
Serial.println(distance);
}
// Helper function to manage our ultrasonic sensor.
long ping() {
long duration;
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
duration = pulseIn(echoPin, HIGH);
return duration;
}
long msToCm(long microseconds) {
return microseconds / 29 / 2;
}