I'm creating a code for a school project where when the ultrasonic sensor detect a certain range, the number of LEDs will light up and a buzzer will sound. However, when users press on a PushButton, the code will temporarily stop, and the code will continue when PushButton is released. However, I'm unable to figure of the pushbutton part of the code. Please help me to see where the error was.
const int trig = 9;
const int echo = 10;
const int LED1 = A1;
const int LED2 = A2;
const int LED3 = A3;
const int LED4 = A4;
const int PushButton = 11;
const int buzzPin = 12;
long duration;
int distanceCm;
int buttonState;
void setup()
{
pinMode(trig , OUTPUT);
pinMode(echo , INPUT);
pinMode(LED1 , OUTPUT);
pinMode(LED2 , OUTPUT);
pinMode(LED3 , OUTPUT);
pinMode(LED4 , OUTPUT);
pinMode(PushButton , INPUT_PULLUP);
pinMode(buzzPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
static byte toggle_sw_memmory=0;
//Clears trig
digitalWrite(trig, LOW);
delayMicroseconds(2);
//Sets the trig on HIGH State for 10ms
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
//Read the echo, returns the sound wave travel time in ms
duration = pulseIn(echo, HIGH);
//Caclulating the distance
distanceCm = duration*0.034/2 ;
//Prints the distance on the Serial Monitor
Serial.println("Distance:");
Serial.println(distanceCm);
if(!digitalRead(PushButton))
{
toggle_sw_memmory = !toggle_sw_memmory;
if(toggle_sw_memmory)
digitalWrite(LED(), HIGH);
else
digitalWrite(LED(), LOW);
while(!digitalRead(PushButton));
}
void LED()
{
if ( distanceCm <= 35 )
{
digitalWrite(LED1, HIGH);
}
else
{
digitalWrite(LED1, LOW);
}
if ( distanceCm <= 40 )
{
digitalWrite(LED2, HIGH);
}
else
{
digitalWrite(LED2, LOW);
}
if ( distanceCm <= 45 )
{
digitalWrite(LED3, HIGH);
}
else
{
digitalWrite(LED3, LOW);
}
if ( distanceCm <= 50 )
{
digitalWrite(LED4, HIGH);
digitalWrite(buzzPin, HIGH);
}
else
{
digitalWrite(LED4, LOW);
digitalWrite(buzzPin, LOW);
}
}