Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define NUM_SAMPLES 10
- volatile unsigned long duration = 0;
- volatile unsigned int pulseCount = 0;
- volatile unsigned long previousMicros = 0;
- void setup() {
- Serial.begin(19200);
- attachInterrupt(digitalPinToInterrupt(2), myIntHandler, RISING);
- }
- void loop() {
- unsigned long _duration;
- unsigned long _pulseCount;
- float Freq_Hz;
- float Freq_RPM;
- // bufferize to avoid glitches
- _duration = duration;
- _pulseCount = pulseCount;
- if (_pulseCount == NUM_SAMPLES) {
- // clear counters
- duration = 0;
- pulseCount = 0;
- Freq_Hz = _pulseCount * 1e6 / float(_duration); // frequency in Hz
- Freq_RPM = Freq_Hz * 60; // frequency in RPM
- Serial.print("freq: ");
- Serial.println(Freq_RPM);
- }
- }
- void myIntHandler() {
- unsigned long currentMicros = micros();
- duration += currentMicros - previousMicros;
- previousMicros = currentMicros;
- pulseCount++;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement