Measuring fan RPM

Going on from our earlier posts about how to synchronise a strobe light to a three wire fan, I've designed something a bit more practical, to measure the RPM of the fan.

https://github.com/swiftforarduino/community/blob/master/contributed%20examples/Fan%20RPM%20speed.swift4a/main.swift

The important trick is we need to turn one of the timers into a "counter" and count the number of pulses coming in from the fan tachometer.  Then if we monitor the count per unit time, we get the RPM simply by multiplication.

What is a timer really? It is actually really a counter.  In normal timer modes, the timer counts clock cycles. You may have noticed you can run it at different speeds, this is done by dividing the clock cycle. But alternatively, two of the atmega328p timers can alternatively count pulses from external sources.

How easy is it to do? Well on S4A it's pretty easy...

timer0SetAsCounter(edgeType: RISING_EDGE)

Timer 0 will now count the rising edge of pulses on pin 4 (assuming it's set as an input of course).

You can access the pulse count easily like this...
let currentCount = currentTimer0Value()

Timer0 is an 8 bit counter so this will wrap round to 0 after 255. Or you can use timer0CounterReset() to reset it manually.

You can see how you could use this to count light pulses, cars passing over a sensor, etc. and maybe even return this value via I2C...


But in this case, we want to count the number of pulses per unit time. How to do this?

Pretty simple of course. We use the S4A builtin setupTimerIntervalInterruptCallback().

setupTimerIntervalInterruptCallback(tenthsOfAMillisecond: 1000) {
  let currentCount = currentTimer0Value()
  ...
  timer0CounterReset()
}

Then do something useful with currentCount.

Here's the video of it in action...



p.s. If you want a bit more variety on the same theme...

timer0SetAsCounterInterruptCallback(edgeType: RISING_EDGE, tripCount: 200) {
}

...will trigger an interrupt callback every 200 counts!

Comments

Popular posts from this blog

Halloween LED lights on a plastic trick or treat cauldron

All about bootloaders

code signing, entitlements, bundles, sandboxes, hardened runtime, notarisation, app store security