Created
September 22, 2020 08:40
-
-
Save smukkejohan/7dcdd7ba9bc8012112f27e0fdea3c7c0 to your computer and use it in GitHub Desktop.
debounce and analogread dmjx example 2020
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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