11import os .path
2-
3- #from pinmap import PinMap
4-
5-
6- #pins = PinMap('/sys/devices/virtual/misc/pwmtimer/', 'pwm', 12)
7-
8- #pinMap broken beyond repair for new sysfs-pwm
2+ from os import listdir
93
104MAX_PWM_LEVEL = 255
115
@@ -15,26 +9,30 @@ def analog_write(pin, value):
159 value can be an number between 0 and 255.
1610
1711 """
12+
1813 path = '/sys/class/misc/pwmtimer/'
1914
2015 ending = 'pwm' + str (pin )
2116
22- with open (os .path .join (path , 'max_level' ,ending )) as f :
17+ pins = listdir (os .path .join (path , 'enable' ))
18+ if not ending in pins :
19+ raise ValueError ("Pin not found, PWM only possible on " + " " .join (str (p ) for p in pins ) + "." )
20+
21+ with open (os .path .join (path , 'max_level' ,ending )) as f :
2322 max_value = int (f .read ())
2423
2524 if value < 0 or value > MAX_PWM_LEVEL :
2625 raise ValueError ("value must be between 0 and %s" % MAX_PWM_LEVEL )
2726
2827 map_level = ((max_value - 1 ) * value ) // MAX_PWM_LEVEL
29- #// because python 3 compatibility
30- #-1 because if it puts max_value the duty cycle somehow becomes 0
31-
28+ #-1 because if it puts max_value the duty cycle somehow becomes 0 (overflow)
29+
3230 #disable -> change level -> enable , as requested by documentation
3331 with open (os .path .join (path , 'enable' , ending ), 'w+' ) as f :
34- f .write ("0\n " )
35-
32+ f .write ("0\n " )
33+
3634 with open (os .path .join (path , 'level' , ending ), 'w+' ) as f :
3735 f .write ("%d\n " % map_level )
38-
36+
3937 with open (os .path .join (path , 'enable' , ending ), 'w+' ) as f :
40- f .write ("1\n " )
38+ f .write ("1\n " )
0 commit comments