// https://forum.arduino.cc/t/attiny85-simple-tap-tempo-that-counts-every-other-pass-on-a-reed-switch/1417576/
byte buttonPin = 12; // arduino pin to count revolutions
int buttonCount; // count button presses
unsigned long buttonTimer, buttonTimeout = 50; // used in readButton() debounce timer
bool currentButtonState, lastButtonRead; // record button states
unsigned long revTime, revTimeOld; // timing variables
float mspr, spr, rpm; // calculation variables must be type float
int revCount; // count revolutions
void setup() {
Serial.begin(115200); // start serial communication
pinMode(buttonPin, INPUT_PULLUP); // configure sensor pin, LOW = pressed, HIGH = released
}
void loop() {
debounceButton();
}
void debounceButton() {
bool currentButtonRead = digitalRead(buttonPin); // read button pin
if (currentButtonRead != lastButtonRead) { // if THIS read is not the same as LAST read...
buttonTimer = millis(); // ...start a timer by storing millis()
lastButtonRead = currentButtonRead; // ... and store current state
}
if ((millis() - buttonTimer) > buttonTimeout) { // if button change was longer than debounce timeout (NOT NOISE)
if (currentButtonState == HIGH && lastButtonRead == LOW) { // ... and State is "NOT pressed" while Button "IS PRESSED"
//==================================================
getrpm(); // The button WAS pressed... call function or do an action
//==================================================
}
currentButtonState = currentButtonRead; // update button state for first if() condition test
}
}
void getrpm() {
revTime = millis(); // store new time of one revolution
mspr = revTime - revTimeOld; // milliseconds per revolution = difference between old time and new time
revTimeOld = revTime; // store previous/old revolution time
spr = mspr / 1000; // secconds per revolution = (millisecons per rev) / 1000
rpm = 60 / spr; // revolutions per minute = inverse of (sec / rev * min / 60 sec)
Serial.print("ms/rev: "); // print type of value
spacepad(mspr); // send to formatter
Serial.print(" | sec/rev:");
spacepad(mspr / 1000);
Serial.print(" | rev/min:");
spacepad(rpm);
Serial.println();
}
void spacepad(float value) { // align columns
if (value <= 999) // decimal excludes using "val < 1000"
Serial.print(" ");
if (value <= 99)
Serial.print(" ");
if (value <= 9)
Serial.print(" ");
Serial.print(value); // print the value
}