#include<LiquidCrystal.h>
#include<Servo.h>
int trigPin=2;
int echoPin=3;
int distance;
const int rs = 12, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
long duration;
Servo servo;
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
servo.attach(9);
lcd.begin(16, 2);
}
void loop()
{
for(int i=15;i<=165;i++)
{
servo.write(i);
delay(200);
printOut();
}
for(int i=165;i>15;i--)
{
servo.write(i);
delay(200);
printOut();
}
}
int calculateDistance()
{
digitalWrite(trigPin,LOW);
delayMicroseconds(2);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
duration=pulseIn(echoPin,HIGH);
distance=duration*0.034/2;
return distance;
}
void printOut()
{
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Servo Pos: ");
lcd.print(servo.read());
lcd.setCursor(0, 1);
lcd.print("Distance: ");
lcd.print(calculateDistance());
}
Comments