// C++ code
//
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
int distancia = 0;
LiquidCrystal_I2C lcd_1(39, 16, 2);
Servo servo_8;
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
void setup()
{
lcd_1.init();
pinMode(A0, INPUT);
servo_8.attach(8, 500, 2500);
pinMode(7, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
lcd_1.clear();
lcd_1.backlight();
}
void loop()
{
servo_8.write(map(analogRead(A0), 0, 1023, 0, 180));
distancia = 0.01723 * readUltrasonicDistance(2, 3);
lcd_1.clear();
lcd_1.setCursor(0, 0);
// El reducido la palabra distancia
lcd_1.print("Distancia:");
lcd_1.print(distancia);
lcd_1.print(" cm");
if (distancia < 30) {
lcd_1.setCursor(4, 1);
lcd_1.print("Peligro");
tone(7, 523, 1000); // play tone 60 (C5 = 523 Hz)
digitalWrite(4, HIGH);
delay(50); // Wait for 50 millisecond(s)
digitalWrite(4, LOW);
noTone(7);
delay(50); // Wait for 50 millisecond(s)
}
if (distancia >= 30 && distancia < 80) {
lcd_1.setCursor(1, 1);
lcd_1.print("Objeto cercano");
digitalWrite(5, HIGH);
tone(7, 523, 1000); // play tone 60 (C5 = 523 Hz)
delay(100); // Wait for 100 millisecond(s)
digitalWrite(5, LOW);
noTone(7);
delay(100); // Wait for 100 millisecond(s)
}
if (distancia >= 80) {
lcd_1.setCursor(3, 1);
lcd_1.print("Sin peligro");
digitalWrite(6, HIGH);
tone(7, 523, 1000); // play tone 60 (C5 = 523 Hz)
delay(150); // Wait for 150 millisecond(s)
digitalWrite(6, LOW);
noTone(7);
delay(150); // Wait for 150 millisecond(s)
}
// He añadido la siguiente espera
// para que no parpadee tanto la pantalla
}