-->
Page 1 of 1

gpio interrupt - reading tacho problem

PostPosted: Tue Mar 02, 2021 11:38 am
by blue_kk
Hi,
I've connected PC fan tacho to IO pin 2 (with pullup from 3.3v) and wanted to count pulses. Here the code:

Code: Select allwifi.setmode(wifi.NULLMODE, false);
gpio.mode(2, gpio.INT);

tacho_2 = 0

gpio.trig(2, "down", function()
        tacho_2 = tacho_2 + 1
end)

function start()
   print("tacho ".. tacho_2 .. "\n");
   tacho_2 = 0
 end

tmr.create():alarm(1000, tmr.ALARM_AUTO, start)


But the interrupt is triggered too many times... There are about 38 pulses per second, but the interrupt seems to be triggered about 100 times per second.

And yes, I know the tacho pules are no revolutions.

Any suggestions?

Re: gpio interrupt - reading tacho problem

PostPosted: Thu Mar 18, 2021 2:34 pm
by Sean Phelan
Hi - you are probably getting switch bounces which trigger interrupts. If you are comfortable with hardware tweaks you could debounce with another resistor and a capacitor. Or for a software solution, try something like:

Code: Select allwifi.setmode(wifi.NULLMODE, false);
gpio.mode(2, gpio.INT);

tacho_2 = 0
bounces=0
last_t=0
min_t=20000

gpio.trig(2, "down", function(level, when)
   if (when-last_t>min_t) then
      tacho_2 = tacho_2 + 1
      last_t=when
   else
      bounces=bounces+1
   end
end)

function start()
   print("tacho ".. tacho_2 .. "\n");
   tacho_2 = 0
 end

tmr.create():alarm(1000, tmr.ALARM_AUTO, start)


Note the 'min_t' constant, the minimum pulse width (in microseconds). I've suggested 20,000 but you can try highere and lower values.