78Views4Replies

Author Options:

Hello guys, I'm doing a alarm system. But my push button doesn't stop the piezo and led when I pressed it. Answered

This is my code.

const int buzzerPin = 5;
const int ledPin = 6;
const int motionPin = 7;
const int buttonPin = 12;

boolean buzzer_mode = false;


int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 100;  // Interval at which LED blinks
int button_state=0;

void setup()
{

  pinMode(ledPin,OUTPUT);
  pinMode(buzzerPin,OUTPUT);
 

  pinMode(buttonPin, INPUT);
 

  delay(100);
}

void loop()
{

  if (digitalRead(motionPin))
  {
    buzzer_mode = true;
  }
  else
  {
    buzzer_mode = false;
  }


  if (buzzer_mode==HIGH)
  {
    unsigned long currentMillis = millis();
    if(currentMillis - previousMillis >= interval)
    {
      previousMillis = currentMillis;
     
      if (ledState == LOW)
      {
        ledState = HIGH;
      }
      else
      {
        ledState = LOW;
      }

    digitalWrite(ledPin, ledState);
    }
    tone(buzzerPin,1000);
  }
  else
  {

    noTone(buzzerPin); 
    digitalWrite(ledPin, LOW);
  }


   button_state = digitalRead(buttonPin);
  if (button_state==HIGH)
  {
     buzzer_mode = false;
    digitalWrite(ledPin, LOW);
  }
  else
  {
    buzzer_mode = true;
  }
}

Discussions

None
steveastrouk

1 year ago

Presumably because its always triggered by the motion sensor ?

None
DejunLsteveastrouk

Answer 1 year ago

Hi steveastrouk, I think you are right. The piezo will stop at 3-4 sec after triggered the motion sensor. Do you know how to change the code to stop the piezo with push button

None
steveastroukDejunL

Answer 1 year ago

Yes, don't loop back to look to test for the sensor, until the pushbutton is released.

None
KISELIN

1 year ago

Hi . Maybe the next is wrong??

if (button_state==HIGH)
{
buzzer_mode = false;
digitalWrite = LOW; TO "digitalWrite" WHAT??

}

None
DejunLKISELIN

Answer 1 year ago

Hi KISELIN, that code should be digitalWrite(ledPin, LOW); sorry for confusing you, I will edit the code right now. Thank you for the reply!