Getting Distance Readings from the Ultrasonic Sensor.
#define echoPin 13
#define trigPin 12
long distance;
long duration;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/58.2) * .39; //we now have the distance in inches
delay(200);
//start doing cool stuff with this distance reading!
}
When we built our distance dials, we had to add to the code to set up our Servo, and then turn the servo to the corresponding number of degrees. Everything in bold below is added to the above section of code. Make sure to connect the servo to digital pin 9.
#define echoPin 13
#define trigPin 12
long distance;
long duration;
#include <Servo.h> // Servo.h is a collection of code to control the servo, and we want to
// include these controls in our program
Servo myservo; // We have created a Servo object, and are calling it 'myservo'
int pos = 0;
void setup() {
myservo.attach(9); //using myservo to reference our servo, we use .attach(9) to tell the arduino
//that it will be attached to pin 9
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/58.2) * .39; //inches
if (distance > 8) { // if the object is greater than 8 inches away, we will just assume that it is
// eight inches away. Either way, the servo is pointed in the same direction
distance = 8;
}
pos = map(distance, 0, 8, 1, 180); //convert the distance from 0 to 8 inches to a number between 0 // and 180 degrees
myservo.write(pos); // turn the servo to this position
delay(200);
}