Skip to content

Instantly share code, notes, and snippets.

@alistairjevans
Created May 21, 2019 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alistairjevans/60e68aba3ffcfc7936e018bb30fb3704 to your computer and use it in GitHub Desktop.
Save alistairjevans/60e68aba3ffcfc7936e018bb30fb3704 to your computer and use it in GitHub Desktop.
Basic digital speed sampler.
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