0

New here, sorry If my formatting is bad.

int button = 2;
int relay = 3;
int speaker = 4;

void setup() 
{

  pinMode(button, INPUT_PULLUP);
  pinMode(relay, OUTPUT);
  pinMode(speaker, OUTPUT);

}

void loop() 
{
  if(digitalRead(button) == 0)
  {
    digitalWrite(relay, HIGH);
    tone (speaker, 100, 300);
    delay (3000);
  }
  else
  {
    digitalWrite(relay, LOW);
  }
}

I want the relay to trigger and stay open only while the button is pressed. However for some reason touching pin 2 triggers the relay and sound, even if I'm not connecting it to the ground.

If i remove the tone (speaker, 100, 300); it only triggers when the button connecting pin 2 to ground is pressed, but obviously doesn't play the tone.

6
  • how is the speaker wired?
    – Juraj
    Commented Aug 23, 2018 at 18:17
  • @Gerben, sorry, I had it right on the board but copied it wrong to here. Commented Aug 23, 2018 at 18:22
  • @Juraj, The red wire is in pin 4 and the black is in GND on POWER Commented Aug 23, 2018 at 18:22
  • is it a piezo speaker? because normal speaker should not be connected without resistor?
    – Juraj
    Commented Aug 23, 2018 at 18:48
  • @juraj The piezo is a speaker, however that can't be the issue entirely as even if I don't plug in the speaker, just the code causes the error. Commented Aug 23, 2018 at 19:19

1 Answer 1

0

I want the relay to trigger and stay open only while the button is pressed. However for some reason touching pin 2 triggers the relay and sound, even if I'm not connecting it to the ground.

Touching a pin is like connecting it to ground with a resistor (human body is conductive). It may or may not be stronger then the pull-up resistor.

If i remove the tone (speaker, 100, 300); it only triggers when the button connecting pin 2 to ground is pressed, but obviously doesn't play the tone.

Activation of the neighbor pin influences the pull-up on pin 2. Try external pull-up on pin 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.