1

I have been trying to read the number of pulse inputs from an external device. The pulse generated is from the arduino uno, and the pin I am using has a frequency of 450hz with 5% duty cycle.

Every time the pulse count shows aroung 2300-3000 per second.

I also have check the frequency of the arduino pin using an Oscilloscope

model- raspberry pi zero W

below is my python code for counting pulse using interrupts to count the pulse within a time interval of 1 sec.

import RPi.GPIO as GPIO
import time, sys

pulse_gpio=26

GPIO.setmode(GPIO.BCM)
GPIO.setup(pulse_gpio,GPIO.IN, pull_up_down=GPIO.PUD_UP)

global count
count=0

def counting(channel):
        global count
        if start_counter==1:
                count=count+1

GPIO.add_event_detect(pulse_gpio, GPIO.FALLING, callback=counting)

while True:
        try:
                start_counter=1
                time.sleep(1)
                start_counter=0
                flow=count
                print(flow)
                count=0
                #time.sleep(0.5)
        except keyboardInterrupt:
                print("keyboard")
                GPIO.cleanup()
                sys.exit()
3
  • Does it generate an error when you try?
    – Milliways
    Jan 20 at 8:58
  • It is hard to understand what this unusual code will actually do but I suggest if you make start_counter global it may help.
    – Milliways
    Jan 20 at 9:15
  • @Milliways making it global doesnot change the counting. It still is showing the same reading of around 2000 when it actually should be around 450. And it didnot show any error.
    – John Mist
    Jan 20 at 9:36

1 Answer 1

0

pigpio is likely to be more accurate for this task.

With the pigpio daemon running (sudo pigpiod) run the following Python code.

import time
import pigpio

COUNT_GPIO=20

pi = pigpio.pi()

if not pi.connected:
   exit()

cb = pi.callback(COUNT_GPIO)

while True:

   time.sleep(1)
   print(cb.tally())
   cb.reset_tally()

cb.cancel()
pi.stop()

Ref http://abyz.me.uk/rpi/pigpio/python.html#callback

4
  • I tried this but now its coming around 7000.
    – John Mist
    Jan 20 at 10:41
  • If it says 7000 then there are 7000 pulses. You need to check your Arduino code (and your oscilloscope). Try piscope
    – joan
    Jan 20 at 11:16
  • I tried with a switch to count number of pulses, it is counting perfectly. Thank you!!
    – John Mist
    Jan 20 at 12:48
  • I don't know what you have done wrong. You need to provide details if you want help.
    – joan
    Jan 20 at 12:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.