Hi, I’m new to Arduino and im trying to do an easy project that consist in the following: when there’s something 5cm away from an ultrasonic sensor, a piezo buzzer emits a sound, when there’s something 4cm away from the ultrasonic sensor, the buzzer emits a sound but faster (with less delay), and so on until there’s something 1 cm away, and if there is something 6cm or more away from the ultrasonic sensor then nothing happens. I’m using an Arduino Uno, a piezo buzzer, an ultrasonic sensor HC-SR04, and an 16x2 lcd, that shows the distance. I was able to write the code but I wanted to know if there is an easier or better way of writing the code. And also, when the buzzer starts sounding, the lcd no longer shows the distance, it shows some weird signs/messages, why is that?. Thank
Code:
[code]
#include <LiquidCrystal.h>
LiquidCrystal lcd(5, 6, 7, 8, 9, 10);
const int triggerPin = 2;
const int echoPin = 3;
const int piezoPin = 11;
int piezoTone = 250;
long time; //variable to store the time traveled
int S; //Variable for storing the distance covered
void setup() {
// put your setup code here, to run once:
lcd.begin(16, 2);
Serial.begin(9600);
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH); //Setting the triggerPin high for 10 microseconds to generate a wave
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
time = pulseIn(echoPin, HIGH); //Setting the echoPin high to recive the wave
S = time*0.034/2;
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.setCursor(0, 1);
lcd.print(S);
lcd.print(" cm");
delay(1000);
if (S == 5) {
tone(piezoPin, piezoTone, 50);
delay(150);
tone(piezoPin, piezoTone, 50);
}
else if (S == 4) {
tone(piezoPin, piezoTone, 50);
delay(125);
tone(piezoPin, piezoTone, 50);
}
else if (S == 3) {
tone(piezoPin, piezoTone, 50);
delay(100);
tone(piezoPin, piezoTone, 50);
}
else if (S == 2) {
tone(piezoPin, piezoTone, 50);
delay(75);
tone(piezoPin, piezoTone, 50);
}
else if (S == 1) {
tone(piezoPin, piezoTone, 50);
delay(50);
tone(piezoPin, piezoTone, 50);
}
}
[/code]