Advertisement
silver2row

PWM_Python

Sep 3rd, 2022
1,261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. # from Mark Yoder but changed heavily by me (as you can tell)
  4. # Seth 2022
  5.  
  6. import glob
  7. import pathlib
  8. from time import sleep
  9.  
  10. def set_frequency(freq):
  11.     """ Change the frequency
  12.  
  13.    frequency - frequency in Hz (freq > 0.0) """
  14.     path = "/dev/bone/pwm/1"
  15.     pathpwm = path + "/b"
  16.  
  17.     # compute current duty cycle
  18.     fd = open(pathpwm + "/duty_cycle", 'r')
  19.     duty_cycle_ns = int(fd.read())
  20.     fd.close()
  21.  
  22.     fd = open(pathpwm + "/period", 'r')
  23.     period_ns = int(fd.read())
  24.     fd.close()
  25.  
  26.     duty_cycle = duty_cycle_ns/period_ns          # compute current duty cycle as fraction
  27.     period_ns = 1e9 / freq                  # compute new period
  28.     duty_cycle_ns = period_ns*duty_cycle # compute new duty cycle as fraction of period
  29.  
  30.     # print('duty_cycle: ' + str(duty_cycle))
  31.     # print('period_ns: ' + str(period_ns))
  32.     # print('duty_cycle_ns: ' + str(duty_cycle_ns))
  33.  
  34.     # Duty Cycle - Set to 0
  35.     fd = open(pathpwm + "/duty_cycle", 'w')
  36.     fd.write('0')
  37.     fd.close()
  38.  
  39.     # Period
  40.     fd = open(pathpwm + "/period", 'w')
  41.     fd.write(str(int(period_ns)))
  42.     fd.close()
  43.  
  44.     # Duty Cycle
  45.     fd = open(pathpwm + "/duty_cycle", 'w')
  46.     fd.write(str(int(duty_cycle_ns)))
  47.     fd.close()
  48.  
  49. def set_duty_cycle(duty):
  50.     """ Change the duty cycle.
  51.  
  52.    dutycycle - between 0.0 and 100.0 """
  53.     path = get_pwm_path()
  54.     pathpwm = path + "/b"
  55.  
  56.     fd = open(pathpwm + "/period", 'r')
  57.     period_ns = int(fd.read()[:-1])
  58.     fd.close()
  59.  
  60.     duty_cycle_ns = duty/100 * period_ns
  61.     # Duty Cycle
  62.     fd = open(pathpwm + "/duty_cycle", 'w')
  63.     fd.write(str(int(duty_cycle_ns)))
  64.     fd.close()
  65.  
  66. def stop():
  67.     """ Stop the PWM channel. """
  68.  
  69.     path = pwm_path()
  70.     pathpwm = path + "/b"
  71.  
  72.     # Disable
  73.     fd = open(pathpwm + "/enable", 'w')
  74.     fd.write('0')
  75.     fd.close()
  76.  
  77.     # unexport
  78.     fd = open(path + "/unexport", 'w')
  79.     fd.write(str(path[1]))
  80.     fd.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement