I have a project going on that requires me to measure duty cycle of a 100 Hz square wave signal. The duty cycle changes but the frequency stays constant. The amplitude of the signal is 15 volts and I have used a resistor and zener to get it down to 3 volts so I can use one of the GPIO pins to measure the duty cycle.
For some reason once in a while when the duty cycle changes there is a huge error in the measurement. For example when it changes from 50 % to 55 % raspberry might show that it is 3 % or 87 % or something else. I'm guessing that the problem comes from the fact when the duty cycle changes it sometimes screws up the timing calculations for the next pulse. Since I'm fairly new to raspberry and python I don't know how to solve this.
I tried to do the same with arduino and it works perfectly when I'm using the pulseIn function and the exact same circuit. The signal is generated from my function generator and I have check it with my scope that it is correct. But if I connect arduino to pi and send the data over tx and rx or over usb there is some weird error on the measurement that I don't get with my pc.
Here is the code that I have used with my Pi and the resistor and zener circuit (basic overvoltage circuit).
Code: Select all
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) while True: try: GPIO.wait_for_edge(25, GPIO.RISING) startTime = time.time() GPIO.wait_for_edge(25, GPIO.FALLING) print "%.1f" % ((time.time() - startTime) * 10000) except KeyboardInterrupt: GPIO.cleanup() GPIO.cleanup()
Code: Select all
import time import RPi.GPIO as GPIO dutyPin = 25 GPIO.setmode(GPIO.BCM) GPIO.setup(dutyPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) while True: try: while GPIO.input(dutyPin) pass start = time.time() while not GPIO.input(dutyPin) pass width = time.time() - start print "%.1f" % (width * 10000) except KeyboardInterrupt: GPIO.cleanup() GPIO.cleanup()