#include <LiquidCrystal.h> // initialize the library "Liquid crystal"
const int echoPin = 6;// attach D2 of the Arduino to pin Echo of the sonar sensor
const int trigPin = 7;//attach D3 of the Arduino to pin Trig of the sonar sensor
const int buttonPin = 20;// button pin onboard of the microcontroller
int LEDstate = 0;
// declare the Pins needed for the LCD screen
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
pinMode(tPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(ePin, INPUT); // Sets the echoPin as an INPUT
pinMode(buttonPin, INPUT); //set button as input
pinMode(LED_BUILTIN, OUTPUT); // set LED as output
Serial.begin(9600); // // Serial Communication is set at 9600 baud
Serial.print("Welome\n");
Serial.print("Thomas Pinckers\n");
Serial.print("2107027\n");
Serial.print("Sensors and Actuators\n");
lcd.begin(16, 2);
digitalWrite(LED_BUILTIN, HIGH);
}
void loop() {
// Clears the trigPin condition
int centimeter = distance();
if(centimeter >= 10 || centimeter <= 180){ // looks if the distance is between 180 adn 10
Display(99, centimeter);
}
if(centimeter < 10){ // looks if the distance is les than 10
Display(1, centimeter);
}
if(distance() > 180){ // looks if the distance is more than 180
Display(2, centimeter);
}
MakeLED(); // checks if the button is pressed
}
int distance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // Sets the trigPin HIGH (LOW) for 2 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds
long duration = pulseIn(echoPin, HIGH);
// Calculating the distance
int centimeter = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
return(centimeter);
}
void Display(int state, int centimeter) { // state if the screan
lcd.clear();
switch(state){
case 1:
lcd.setCursor(1, 1);
lcd.print("Distance: < 10");
break;
case 2:
lcd.setCursor(1, 1);
lcd.print("Distance: > 180");
LEDstate = 1;
break;
default:
lcd.setCursor(1, 1);
lcd.print("Distance: ");
lcd.print(centimeter);
break;
}
lcd.setCursor(0, 0);
lcd.print("Student : Jaimy");
}
void MakeLED() {
int LEDbutton = digitalRead(button1);
int lastState;
if(LEDbutton != lastState){
if(LEDbutton == HIGH){
LEDstate = 0;
}
}
digitalWrite(LED_BUILTIN, LEDstate); // make the LED output the same as the state
lastState = LEDbutton;
}