#include <Servo.h>
#include <LiquidCrystal_I2C.h>
#define ECHO_PIN 2
#define TRIG_PIN 3
Servo myservo; // create servo object to control a servo
#define I2C_ADDR 0x27
#define LCD_COLUMNS 16
#define LCD_LINES 2
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
int pos = 0; // variable to store the servo position
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
// Init LCD
lcd.init();
lcd.backlight();
// Print something
lcd.setCursor(3, 0);
lcd.print("Distance: ");
}
void loop() {
float distance = readDistanceCM();
bool isNearby = distance < 100;
digitalWrite(LED_BUILTIN, isNearby);
Serial.print("Measured distance: ");
Serial.println(distance);
lcd.clear(); // clear the LCD display
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
if (distance < 50) {
// Move servo to 0 degrees if the distance is less than 50 cm
myservo.write(0);
} else if (distance >= 50 && distance < 100) {
// Move servo to 90 degrees if the distance is between 50 and 100 cm
myservo.write(90);
} else {
// Move servo to 180 degrees if the distance is greater than or equal to 100 cm
myservo.write(180);
}
delay(100);
}