1

When I push the button it turns the KY008 off but when I click it again it won't turn it off, but if I jiggle the Laser Diode a little bit the KY008 turns back on.

Code:

int LED = 12;
int BUTTON = 4;

void setup(){
   pinMode(LED,OUTPUT);
   pinMode(BUTTON,INPUT);
}

void loop(){
    if(digitalRead(BUTTON) == HIGH){
        digitalWrite(LED,HIGH);
    }else{ 
    digitalWrite(LED,LOW);
    }
}
3
  • 1
    a) Read stackoverflow.com/editing-help to learn how to format your code. b) Consider posting at Arduino Commented Feb 6, 2018 at 15:33
  • 1
    Do you have external pullup/pulldown resistors? Commented Feb 6, 2018 at 15:37
  • Also KY008 seems to be a laser module not a LED. Commented Feb 6, 2018 at 15:38

1 Answer 1

1

If you use INPUT you need to have a physical pullup (or pulldown) resistor (typically 10k).

Otherwise use INPUT_PULLUP to use the Arduino internal pullup resistors

pinMode(BUTTON, INPUT_PULLUP);

Make sure that your button closes the circuit to ground when pressed.

Also when reading a button you will have a lot of bouncing. The easiest way to prevent the bouncing is to add a delay between reads.

void loop(){
    if(digitalRead(BUTTON) == HIGH){
        digitalWrite(LED,HIGH);
    }else{ 
        digitalWrite(LED,LOW);
    }
    delay(100);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.