Problem with on-on switch

Hello,

I have a small project that involves on-on type switch. I have connected the switch to Arduino Uno board, wrote some simple code and run it. Switch is connected to pins 2 and 3. Buzzer is connected to pin 8, and I'm using build in LED (just for now).

Generally speaking... it works. When I pull the switch down I get sound, when I pull it up, LED blinks (or the other way around... does not matter). But... every now and then:
-when LED is set to be blinking, buzzer makes sound

  • when buzzer is set to be making noise, LED blinks
    and this happens in a random way.

I figure out, that there must be something wrong with both switch state detection and my code (to compensate the erratic behavior). The question is: what shall I correct (in both code and schematix) to eradicate described behavior ?

The sketch (simplified, to show the problem):

int led = 13;

int buttonPin1 = 2;
int buttonPin2 = 3;

int buttonState1 = 0;
int buttonState2 = 0;

void setup(){
  pinMode(led, OUTPUT); 
  
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);    
}

void loop(){
  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);
  
  if(buttonState1 == HIGH){
    make_sound;
  }
  
  if(buttonState2 == HIGH){
    make_noise;
  }
}

int make_sound(){
	for(int i = 0; i < 4; i++){
        digitalWrite(led, HIGH);
        delay(50);
        digitalWrite(led, LOW);
        delay(200);
	}
}

int make_noise(){
	for(int i = 0; i < 4; i++){
		tone(8,1000,10);
        delay(250); 
	}
}

And the schematic (shared via my dropbox):
https://www.dropbox.com/sh/2kobwl0s6y71dyo/5rYSO98xed#/

Thanks in advance for any response.
BR :slight_smile:
blackest

It looks likes one of your data pins is "floating" when not connected. You should use a pull down resistor (4K7 - 10K) directly from each data pin as you are switching to VCC as "ON". If the pin not "ON" it is certainly "LOW". In your case you cannot be sure.

I used 10k resistors as you described... and it work.
Thank you :slight_smile: