/*
Forum: https://forum.arduino.cc/t/calculating-periodic-time-using-micros-on-arduino-nano/1336853
Wokwi: https://wokwi.com/projects/418610438465724417
2024/12/29
ec2021
*/
// Added to create a digital input for the ISR
// The togglePin switches its state (LOW-> HIGH-> LOW-> ...) every timer1 interrupt.
// As the ISR reacts on a falling edge only
// the measured period equals 2 x timerInterval
#include <TimerOne.h>;
const byte togglePin {3};
const unsigned long timerInterval = 500; //micro seconds !!!
#define INPUT_PIN_1 2
volatile unsigned long PT = 0;
// No need for volatile as FREQ and RPM_Reading are not used in the ISR
float FREQ = 0;
float RPM_Reading = 0;
// Moved to ISR
// volatile unsigned long currentTime = 0;
// volatile unsigned long lastTime = 0;
void setup()
{
// TimerOne
Timer1.initialize(timerInterval);
Timer1.attachInterrupt(toggle);
pinMode(togglePin, OUTPUT);
Serial.begin(115200);
pinMode(INPUT_PIN_1, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(INPUT_PIN_1), InterruptSR, FALLING);
}
void loop()
{
// Copy PT to the variable copyPT which is "outside" of the ISR
noInterrupts();
unsigned long copyPT = PT;
interrupts();
FREQ = 1000000.0 / copyPT; // Calculate frequency in Hz
RPM_Reading = FREQ * 60; // Convert frequency to RPM
// not ms but micro seconds
//Serial.print("periodic time in ms: ");
Serial.print("periodic time in µs: ");
Serial.println(copyPT);
Serial.print("frequency: ");
Serial.println(FREQ);
Serial.print("RPM: ");
Serial.println(RPM_Reading);
}
void InterruptSR()
{
static unsigned long lastTime = 0;
unsigned long currentTime = micros();
PT = currentTime - lastTime;
lastTime = currentTime;
}
void toggle() {
static byte state = LOW;
digitalWrite(togglePin, state);
state = !state;
}