Skip to content

Instantly share code, notes, and snippets.

@smukkejohan
Created September 22, 2020 08:40
Show Gist options
  • Save smukkejohan/7dcdd7ba9bc8012112f27e0fdea3c7c0 to your computer and use it in GitHub Desktop.
Save smukkejohan/7dcdd7ba9bc8012112f27e0fdea3c7c0 to your computer and use it in GitHub Desktop.
debounce and analogread dmjx example 2020
#include <Arduino.h>
// Se https://learn.adafruit.com/make-it-switch/debouncing for nærmere beskrivelse
int ledPin = 3;
int buttonPin = 6;
unsigned long debounceTime = 5;
unsigned long lastDebounceTimestamp = 0;
int ledState = HIGH;
int buttonState = HIGH;
int lastButtonState = HIGH;
int drejeknapPin = A14;
void setup() {
// put your setup code here, to run once:
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(drejeknapPin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int drejeKnapValue = analogRead(drejeknapPin); // 0 - 1023 (10 bit)
int intensity = drejeKnapValue * 0.25; // 0 - 255
int reading = digitalRead(buttonPin);
// Tjek om der er en ændring i knappens state
if(reading != lastButtonState) {
// Gem tid for sidste ændring
lastDebounceTimestamp = millis();
}
//
unsigned long timeSinceLastChange = millis() - lastDebounceTimestamp;
if( timeSinceLastChange > debounceTime) {
if(reading != buttonState) {
buttonState = reading;
if(buttonState == HIGH) {
ledState = !ledState;
}
}
}
if(ledState) {
analogWrite(ledPin, intensity);
} else {
analogWrite(ledPin, 0);
}
lastButtonState = reading;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment