int led = 3; // led pin
int but = 4; // button pin
int but_state = 1; // state of button
int prev_but = 1; // previous loop button state
int led_state = 0; // state of led
void setup() {
pinMode(led, OUTPUT);
pinMode(but, INPUT);
}
void loop() {
but_state = digitalRead(but); // read the button
// if the button was just pressed
if (but_state == 0 && prev_but == 1){
// toggle the led
if (led_state == 0){
led_state = 1;
}
else {
led_state = 0;
}
}
if (led_state == 1){
digitalWrite(led, HIGH);
}
else {
digitalWrite(led,LOW);
}
// remember the button state
prev_but = but_state;
}
int led = 3; // led pin
int but = 4; // button pin
volatile int led_state = 0; // variables used in intterupts must be declared volatile
void setup() {
pinMode(led, OUTPUT);
pinMode(but, INPUT);
// when but pin goes HIGH to LOW call the function but_pressed()
attachInterrupt(digitalPinToInterrupt(but), but_pressed, FALLING);
}
void loop() {
if (led_state == 1) {
digitalWrite(led, HIGH);
}
else {
digitalWrite(led, LOW);
}
}
void but_pressed() {
if (led_state == 1) {
led_state = 0;
}
else {
led_state = 1;
}
}