My aim is to have a social distancing device that includes an ultrasonic sensor (buzzer) and a basic LED light. I want to have the two actuators in sync so that when the buzzer goes off, the light connects and lights up ONLY when the buzzer is on.
Right now, the light is on and off on a pattern but I think it also lights up with the buzzer I'm not sure if I have written anything right. How do I change it so that it ONLY lights up with the buzzer and nothing else.
Also if anything else is wrong or how to compress it to make it easier to read. Thank you so much it is urgent.
This is my code:
// defines pin numbers
const int trigPin = 6; // Trigpin connected to digital pin 6
const int echoPin = 5; // EchoPin connected to digital pin 5
const int buzzPin = 13; // BuzzPin connected to digital pin 13
const int redPin = 13; // RedPin (LED) connected to digital pin 13
// which Arduino pin everything is connected to
void setup() {
pinMode(trigPin, OUTPUT); // trig pin will be set as output
pinMode(echoPin, INPUT); // echo pin will be set as input
pinMode(buzzPin, OUTPUT); // buzz pin will be set as output to control buzzer
pinMode(redPin, OUTPUT); // declare the LED as an output
// pinMode configures a pin either as an input or output.
// When configured as an input, a pin can detect the state of a sensor like a pushbutton.
// As an output, it can drive an actuator like an LED.
}
void loop() {
// Duration will be the input pulse width and distance will be the distance to the obstacle in centimeters
int duration, distance; // Output pulse with one milliseconds width on trigPin
digitalWrite(trigPin, HIGH);
delay(1);
digitalWrite(trigPin, LOW); // Measure the pulse input in echo pin
duration = pulseIn(echoPin, HIGH); // Distance is half the duration devided by 29.1 (from datasheet)
distance = (duration/2) / 29.1; // If distance less than 1.5 meter and more than 0 (0 or less means over range)
// setting a pin to HIGH sets it to either 5V or 3.3V.
// writing a LOW to pin connects it to ground (GND) or to zero volts
if (distance <= 100 && distance >= 0) { // Buzz
tone(buzzPin, 550); // Tone for when it buzzes
delay(500); // Wait for half a second
noTone(buzzPin); // When it does not buzz
delay(500); // Wait for half a second
// the delay() causes the Arduino to wait for the specified number of milliseconds before continuing on to the next line.
// setting the delay to 500 milliseconds means that the line creates a delay of half a second (0.5 seconds)
digitalWrite(buzzPin, HIGH); // Start buzzing
{
}
} else // Don't buzz and light goes off
digitalWrite(buzzPin, LOW); // Stop buzzing
{
}
digitalWrite(redPin, HIGH); // Turn the LED on
delay(500); // wait half a second
digitalWrite(redPin, LOW); // Turn the LED off
delay(1000);
// Waiting 60 milliseconds won't hurt anyone
delay(60);
} // go back to the beginning of the loop
Can someone please tell me what I'm doing wrong and what I need to write to fix it?
THANK YOU SO MUCH IF YOU HELP ME.