#include <Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27,20,4);
// Sensor HC-SR84. ---------- >
#define echoPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
// End sensor section -------------<
void setup()
{
Serial.begin(9600);
//LCD ----------------- <
lcd.init();
lcd.backlight();
//Sensor ------------>
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
}
void loop()
{
// Remap range from 0 to 400 to 0 to 100;
int acquiredValue = distance;
int value = map(acquiredValue, 0, 400, 0, 40);
int valueNew = (value, DEC);
// ---------------- <
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Displays the distance range from 0 to 400 to 0 to 100;
Serial.print("NEW VALUE: ");
Serial.println(value);
// Serial.println(value, DEC);
Serial.println("___________________");
// Print distnace position
lcd.setCursor(0, 0);
lcd.print(value);
delay(100);
}