Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- import pathlib
- from time import sleep
- class PWM:
- def start(duty, freq=2000, polarity=0):
- """ Set up and start the PWM channel. """
- path = pathlib.Path("/dev/bone/pwm/1/b")
- if path == None:
- return None
- period_ns = 1e9 / freq
- duty_ns = (period_ns * (duty / 100.0))
- # export
- try:
- fd = open(path + "/export", 'w')
- fd.write(str(path))
- fd.close()
- except:
- pass
- time.sleep(0.05) # Give export a chance
- # Duty Cycle - Set to 0 so period can be changed
- try:
- fd = open(pathpwm + "/duty_cycle", 'w')
- fd.write('0')
- fd.close()
- except:
- pass
- # Period
- fd = open(pathpwm + "/period", 'w')
- fd.write(str(int(period_ns)))
- fd.close()
- # Duty Cycle
- fd = open(pathpwm + "/duty_cycle", 'w')
- fd.write(str(int(duty_ns)))
- fd.close()
- # Enable
- fd = open(pathpwm + "/enable", 'w')
- fd.write('1')
- fd.close()
- return 'Started'
- def set_frequency(freq):
- """ Change the frequency
- frequency - frequency in Hz (freq > 0.0) """
- path = Path("/dev/bone/pwm/1")
- pathpwm = path + "/b"
- # compute current duty cycle
- fd = open(pathpwm + "/duty_cycle", 'r')
- duty_cycle_ns = int(fd.read())
- fd.close()
- fd = open(pathpwm + "/period", 'r')
- period_ns = int(fd.read())
- fd.close()
- duty_cycle = duty_cycle_ns/period_ns # compute current duty cycle as fraction
- period_ns = 1e9 / freq # compute new period
- duty_cycle_ns = period_ns*duty_cycle # compute new duty cycle as fraction of period
- # print('duty_cycle: ' + str(duty_cycle))
- # print('period_ns: ' + str(period_ns))
- # print('duty_cycle_ns: ' + str(duty_cycle_ns))
- # Duty Cycle - Set to 0
- fd = open(pathpwm + "/duty_cycle", 'w')
- fd.write('0')
- fd.close()
- # Period
- fd = open(pathpwm + "/period", 'w')
- fd.write(str(int(period_ns)))
- fd.close()
- # Duty Cycle
- fd = open(pathpwm + "/duty_cycle", 'w')
- fd.write(str(int(duty_cycle_ns)))
- fd.close()
- def set_duty_cycle(duty):
- """ Change the duty cycle.
- dutycycle - between 0.0 and 100.0 """
- path = get_pwm_path()
- pathpwm = path + "/b"
- fd = open(pathpwm + "/period", 'r')
- period_ns = int(fd.read())
- fd.close()
- duty_cycle_ns = duty/100 * period_ns
- # Duty Cycle
- fd = open(pathpwm + "/duty_cycle", 'w')
- fd.write(str(int(duty_cycle_ns)))
- fd.close()
- def stop():
- """ Stop the PWM channel. """
- path = pwm_path()
- pathpwm = path + "/b"
- # Disable
- fd = open(pathpwm + "/enable", 'w')
- fd.write('0')
- fd.close()
- # unexport
- fd = open(path + "/unexport", 'w')
- fd.write(str(path[1]))
- fd.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement