Created
September 22, 2020 08:57
-
-
Save smukkejohan/d482f089f8b4a372682602f54bbbcf2d to your computer and use it in GitHub Desktop.
Debounce, analogRead and delay with timer DMJX 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; | |
unsigned long lastBlinktime = 0; | |
int blinkState = 0; | |
void blinkPWM(unsigned long blinkSpeed, int intensity) { | |
if( (millis() - lastBlinktime) > blinkSpeed ) { | |
blinkState = !blinkState; | |
lastBlinktime = millis(); | |
} | |
if(blinkState) { | |
analogWrite(ledPin, intensity); | |
} else { | |
analogWrite(ledPin, 0); | |
} | |
} | |
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, 0); | |
} else { | |
//analogWrite(ledPin, 0); | |
blinkPWM(drejeKnapValue, 255); | |
} | |
lastButtonState = reading; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment