Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.