Hello,
I have a code set up for an LCD, Buzzer, and Ultrasonic sensor to measure distance, however when I add the code for the servo the screen delays along with the servo delay that I have for it. How would I write the code for the servo that it doesn't interact with the LED and Ultrasonic sensor?
Any help would be extremely appreciate it.
Here's my code:
#include <LiquidCrystal.h>
#include <Servo.h>
const int rs = 30, en = 29, d4 = 40, d5 = 39, d6 = 38, d7 = 37;
LiquidCrystal lcd (rs, en, d4, d5, d6, d7);
const int echoPin = 23;
const int trigPin = 24;
const int Buzzer = 27;
Servo Servo1;
long duration;
int distanceInch;
int safetyDistance;
void setup() {
lcd.begin(16, 2);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(Buzzer, OUTPUT);
Serial.begin(9600);
Servo1.attach(22);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
buzzer();
servo();
}
void buzzer() {
duration = pulseIn(echoPin, HIGH);
distanceInch = (duration * 0.0133) / 2.0;
if (distanceInch >= 15 || distanceInch <= 0)
{
digitalWrite(Buzzer, HIGH);
lcd.setCursor(0, 0);
lcd.print("NO OBJECT[>15in]");
lcd.print(distanceInch);
lcd.setCursor(0, 1);
lcd.print(" DETECTED!");
delay(1000);
lcd.clear();
}
else
{
digitalWrite(Buzzer, LOW);
lcd.setCursor(0, 0);
lcd.print("DISTANCE(in)");
lcd.print(distanceInch);
lcd.setCursor(0, 1);
lcd.print(" OBJECT DETECTED!");
delay(1000);
lcd.clear();
}
}
void servo(){
Servo1.write(0);
delay(1000);
Servo1.write(90);
delay(1000);
Servo1.write(180);
delay(1000);
}