#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define TRIG 2
#define ECHO 4
#define BT_UP 16
#define BT_DOWN 5
#define BT_SET 17
#define som 18
int contador = 0, nun1 = 200, nunset = 0;
int t1 = 0, t2 = 0;
int distancia = 0;
long duration;
int distance;
bool set1 = 0, set2 = 0, set3 = 0, time_set = 0;
int s1 = 0;
bool tr = 0;
LiquidCrystal_I2C LCD(0x27, 16, 2);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("by Gabriel Luz");
LCD.init();
LCD.backlight();
LCD.setCursor(0,0);
LCD.print(" Gabriel Luz ");
LCD.setCursor(0,1);
LCD.print("TEC.MECATRONICA");
delay(1000);
LCD.clear();
pinMode(TRIG, OUTPUT);
pinMode(som, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(BT_UP, INPUT);
pinMode(BT_DOWN, INPUT);
pinMode(BT_SET, INPUT);
LCD.setCursor(0,1);
LCD.print("V: ");
LCD.print(nun1);
LCD.print(" ");
LCD.setCursor(8,1);
LCD.print("sel: ");
LCD.print(nunset);
LCD.print(" ");
LCD.setCursor(0,0);
LCD.print("D: ");
LCD.print(distancia);
LCD.print(" ");
LCD.setCursor(7,0);
LCD.print("Alarm OFF");
}
void loop() {
alarme();
sensor();
botoes();
delay(10);
}
void alarme(){
if(distancia < nunset && tr == 0){
tr = 1;
LCD.setCursor(7,0);
LCD.print("Alarm ON ");
}
if(distancia >= nunset && tr == 1){
tr = 0;
LCD.setCursor(7,0);
LCD.print("Alarm OFF");
}
if(tr == 1){
s1++;
if(s1 == 20)s1 = 0;
if(s1 < 5){
tone(som, 440 ,10);
}
if(s1 > 5 && s1 < 10){
tone(som, 550 ,10);
}
if(s1 > 10 && s1 < 15){
tone(som, 660 ,10);
}
if(s1 > 15 ){
tone(som, 550 ,10);
}
}
}
void sensor(){
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
duration = pulseIn(ECHO, HIGH);
contador = duration * 0.017;
if(distancia != contador){
distancia = contador;
LCD.setCursor(0,0);
LCD.print("D: ");
LCD.print(distancia);
LCD.print(" ");
}
}
void botoes(){
if(digitalRead(BT_UP) == 1 && set1 == 0){
nun1 = nun1 + 10;
if(nun1 > 400)nun1 = 400;
set1 = 1;
LCD.setCursor(0,1);
LCD.print("V: ");
LCD.print(nun1);
LCD.print(" ");
}
if(digitalRead(BT_DOWN) == 1 && set2 == 0){
nun1 = nun1 - 10;
if(nun1 < 0)nun1 = 0;
set2 = 1;
LCD.setCursor(0,1);
LCD.print("V: ");
LCD.print(nun1);
LCD.print(" ");
}
if(digitalRead(BT_SET) == 1 && set3 == 0){
set3 = 1;
nunset = nun1;
time_set = 1;
}
if(digitalRead(BT_UP) == 0 && set1 == 1)set1 = 0;
if(digitalRead(BT_DOWN) == 0 && set2 == 1)set2 = 0;
if(digitalRead(BT_SET) == 0 && set3 == 1)set3 = 0;
if(time_set == 1){
t1++;
t2++;
if(t2 < 5 ){
LCD.setCursor(8,1);
LCD.print("sel: ");
LCD.print(nunset);
LCD.print(" ");
} else{
LCD.setCursor(8,1);
LCD.print(" ");
if(t2 == 10)t2 = 0;
}
}
if(t1 == 31){
t1 = 0;
time_set = 0;
LCD.setCursor(8,1);
LCD.print("sel: ");
LCD.print(nunset);
LCD.print(" ");
}
}