Skip to content

Instantly share code, notes, and snippets.

@smukkejohan
Created September 24, 2019 08:43
Show Gist options
  • Save smukkejohan/75e206e736e8e8925510a113ff115d6a to your computer and use it in GitHub Desktop.
Save smukkejohan/75e206e736e8e8925510a113ff115d6a to your computer and use it in GitHub Desktop.
button with debounce and change of state with no delays DMJX
#include <Arduino.h>
int buttonPin = 2;
int ledPin = 13;
int buttonState = HIGH;
int lastButtonState = LOW;
int ledState = LOW;
bool blinkFast = true;
unsigned long fastBlinkInterval = 100;
unsigned long slowBlinkInterval = 600;
unsigned long elapsedTimeInMillis = 0;
unsigned long lastBlinkTime = 0;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 20;
void setup() {
Serial.begin(9600);
// put your setup code here, to run once:
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
while(!Serial) {
;
}
Serial.println("Hej HEJ!");
}
// logical operators:
// != NOT -> er det ikke det samme
// == COMPARISON -> er det det samme
// && og
// || eller
// < mindre end
// støre
// ++ = +1
// --
// var = nyvar ASSIGNMENT
// += assignment + værdi
// -= assignment - værdi
/*int mitTal = 4;
mitTal += 2;
mitTal = mitTal + 2;
*/
void loop() {
// put your main code here, to run repeatedly:
elapsedTimeInMillis = millis();
int buttonReading = digitalRead(buttonPin);
if(buttonReading != lastButtonState) {
//buttonState = buttonReading;
lastDebounceTime = elapsedTimeInMillis;
}
if( (elapsedTimeInMillis - lastDebounceTime) > debounceDelay ) {
// er der gået mere end 2 millissekunder siden sidste ændring
if(buttonReading != buttonState) {
buttonState = buttonReading;
if(buttonState) {
blinkFast = !blinkFast;
}
Serial.print("buttonState: ");
Serial.print(buttonState);
Serial.print(" blinkFast: ");
Serial.println(blinkFast);
}
}
lastButtonState = buttonReading;
if(blinkFast) {
// blink hurtigt
if((elapsedTimeInMillis - lastBlinkTime) > fastBlinkInterval ) {
ledState = !ledState;
lastBlinkTime = elapsedTimeInMillis;
}
// gem interval mellem blink
// hvis tid der er gået siden led sidst
// tændte eller slukkede er større end interval
// så tænd eller sluk
} else {
// blink langsomt
if((elapsedTimeInMillis - lastBlinkTime) > slowBlinkInterval ) {
ledState = !ledState;
lastBlinkTime = elapsedTimeInMillis;
}
}
digitalWrite(ledPin, ledState);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment