Created
May 21, 2019 20:08
-
-
Save alistairjevans/60e68aba3ffcfc7936e018bb30fb3704 to your computer and use it in GitHub Desktop.
Basic digital speed sampler.
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
const int SPEEDPIN = 2; | |
// Sample every 500ms | |
const int SAMPLEFREQ = 500; | |
// Variables for storing state. | |
int switchState = 0; | |
int lastSwitchState = 0; | |
// Variable for remembering when we last sampled. | |
unsigned long lastSampleMillis = 0; | |
// Keep track of our transitions | |
unsigned int transitionCount = 0; | |
void setup() | |
{ | |
Serial.begin(9600); | |
} | |
void loop() | |
{ | |
// Each loop, read the state of the pin. | |
switchState = digitalRead(SPEEDPIN); | |
// When we transition from HIGH to LOW, the circuit has been broken | |
if(lastSwitchState == HIGH && switchState == LOW) | |
{ | |
// Increment our count of transitions. | |
transitionCount++; | |
} | |
lastSwitchState = switchState; | |
if(millis() - lastSampleMillis > SAMPLEFREQ) | |
{ | |
// Once per SAMPLEFREQ milliseconds, determine the | |
// speed (in terms of transitions per second). | |
int speed = transitionCount * (1000 / SAMPLEFREQ); | |
// Print out the speed of the sample | |
Serial.println(speed); | |
// Reset the count ready for the next sample. | |
transitionCount = 0; | |
lastSampleMillis = millis(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment