#include <LiquidCrystal_I2C.h> //initialize the liquid crystal library
#include <Wire.h> // this library allows you to communicate with I2C devices
LiquidCrystal_I2C lcd(0x27, 16, 2); // lcd (I2C address, number of rows, number of columns)
const int trigPin = 2;
const int echoPin = 5;
float duration, distance;
#include <Servo.h> // library to control servo motors | https://docs.arduino.cc/learn/electronics/servo-motors/
Servo myservo; // create servo object to control a servo
void setup() {
myservo.attach(4); // attaches the servo on pin 9 to the servo object
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
lcd.init(); //initialize lcd screen
lcd.backlight(); // turn on the backlight
lcd.blink(); // Print a message to the LCD.
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration*.0343)/2;
int val = map(distance, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
myservo.write(val); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
lcd.setCursor(0,0);
lcd.print("Angle: ");
lcd.setCursor(0, 1); // set the cursor to column 0, line 1 (line 1 is the second row, counting begins with 0)
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print(val);
Serial.println(val);
delay(100);
}