1

Try to measure frequency with OrangePi Zero by rising edge. I'm using this library for accessing gpio: http://opi-gpio.readthedocs.io/en/latest/index.html

This is my code (Python 3.5):

def meas_freq_cb(receiver):
    self.meas_list.append(time.perf_counter())

GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN)
GPIO.add_event_detect(12, GPIO.RISING, callback=meas_freq_cb)
time.sleep(1)
GPIO.remove_event_detect(12)

i = 0
while i < len(self.meas_list)-1:
    a = self.meas_list[i+1] - self.meas_list[i]
    a = (a - int(a)) * 10000
    # a = round(a)
    print(a)
    i = i + 1
    if i > 200:
        break

GPIO.cleanup()

Frequency: square 100Hz from precision generator.

Result:

0.8033299945964245
0.41291000343335327
1.2274799973965855
1.1154000003443798
0.9166499967250274
1.909970005726791
1.1483199978101766
3.992020001533092
0.5579099979513558
1.763299997037393
0.8991600043373182
23.93046999713988
7.611549999637646
4.15909999901487
13.988540003992966
4.470759995456319
1.9358100053068483
...

Results is very very strange. I don't know what a problem. Frequency very low, system in idle state, very simple question, but it doesn't work.. Please assist.. Thanks!

P.S. Sorry for my bad English

Dennosaur
  • 65
  • 5

1 Answers1

0

in your code the problem is a = (a - int(a)) * 10000. in your meas_list is the time / counter ticks between two rising edges T that is equivalent one period. Frequency f = 1 / T, so a = (a - int(a)) * 10000 is nonsense, it has to be

while i < len(self.meas_list)-1:
    T = self.meas_list[i+1] - self.meas_list[i] # time T between two rising edges
    f = (1 / T) * k # by definition and k is a constant that transforms the counter ticks returned by time.perf_counter() to real-world frequency ( calibration )
    print(f) 
    ...

time.perf_counter returns the absolute value of the counter.

source : Understanding time.perf_counter() and time.process_time()

this it is a translation of RPi code to OrangePi ( How to get the frequency of a square wave in a python script ) code measures the time for 10000 rising edges to occur ( duration ) and calculates frequency = 10000 / duration however time.time() is far too inexact for serious applications :

import time

impulse_count = 0

def meas_freq_cb(receiver):
    global impulse_count
    impuls_count+=1



NUM_CYCLES = 10000
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN)


start = time.time()
for impulse_count in range(NUM_CYCLES):
    GPIO.add_event_detect(12, GPIO.RISING, callback=meas_freq_cb)
duration = time.time() - start      #seconds to run for loop
frequency = NUM_CYCLES / duration   #in Hz

print(frequency)

GPIO.remove_event_detect(12)

( Using global variables in a function )

ralf htp
  • 9,149
  • 4
  • 22
  • 34