Can't get alarm to turn off on uno wifi r2 board

I’m creating an alarm by having it trigger by the ultrasonic sensor and have a led light up too but the only thing is I can’t get to turn off after I trigger it. I need help with my coding.

int piezo = 8;
int LED = 7;
int USsensor = A0;

int Cnote = 262;
int Bnote = 493;

int distance = 0;
int value = 0;

int alarm = 0;
int trigger = 500;

void setup() {
// put your setup code here, to run once:
pinMode(piezo, OUTPUT);
pinMode(LED, OUTPUT);
}

void loop() {
// put your main code here, to run repeatedly:
value = analogRead(USsensor);
distance = value * 3;
if (distance < trigger)
{
alarm = 1;
}
else if (distance < 0)
{
alarm = 0;
}
if (alarm == 1)
{
tone (piezo,Cnote);
for (int i = 0; i < 255; i++)
{
analogWrite(LED, i );
delay (5);
}
tone (piezo, Bnote);
for (int i = 255; i > 0; i–)
{
analogWrite(LED, i);
delay (5);
}
if (alarm == 0)
{
digitalWrite(LED, LOW);
noTone(piezo);
}
}
}

Take a look at the first topic telling how to get the best from this Forum.
You have posted a lot of text, not code.

Distance can never be less than zero, so once your alarm starts, it will never turn off, as you observe.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.