1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
from pyA20.gpio import gpio as GPIO
import threading
import time
class OrangePwm(threading.Thread):
def __init__(self, frequency, gpioPin, gpioScheme=0):
"""
Init the OrangePwm instance. Expected parameters are :
- frequency : the frequency in Hz for the PWM pattern. A correct value may be 100.
- gpioPin : the gpio.port which will act as PWM ouput
- gpioScheme : saved for compatibility with PiZyPWM code
"""
super().__init__()
self.baseTime = 1.0 / frequency
self.maxCycle = 100.0
self.sliceTime = self.baseTime / self.maxCycle
self.gpioPin = gpioPin
self.terminated = False
self.toTerminate = False
# GPIO.setmode(gpioScheme)
def start(self, dutyCycle):
"""
Start PWM output. Expected parameter is :
- dutyCycle : percentage of a single pattern to set HIGH output on the GPIO pin
Example : with a frequency of 1 Hz, and a duty cycle set to 25, GPIO pin will
stay HIGH for 1*(25/100) seconds on HIGH output, and 1*(75/100) seconds on LOW output.
"""
self.dutyCycle = dutyCycle
GPIO.setcfg(self.gpioPin, GPIO.OUTPUT)
self.thread = threading.Thread(None, self.run, None, (), {})
self.thread.start()
def run(self):
"""
Run the PWM pattern into a background thread. This function should not be called outside of this class.
"""
while self.toTerminate == False:
if self.dutyCycle > 0:
GPIO.output(self.gpioPin, GPIO.HIGH)
time.sleep(self.dutyCycle * self.sliceTime)
if self.dutyCycle < self.maxCycle:
GPIO.output(self.gpioPin, GPIO.LOW)
time.sleep((self.maxCycle - self.dutyCycle) * self.sliceTime)
self.terminated = True
def changeDutyCycle(self, dutyCycle):
"""
Change the duration of HIGH output of the pattern. Expected parameter is :
- dutyCycle : percentage of a single pattern to set HIGH output on the GPIO pin
Example : with a frequency of 1 Hz, and a duty cycle set to 25, GPIO pin will
stay HIGH for 1*(25/100) seconds on HIGH output, and 1*(75/100) seconds on LOW output.
"""
self.dutyCycle = dutyCycle
def changeFrequency(self, frequency):
"""
Change the frequency of the PWM pattern. Expected parameter is :
- frequency : the frequency in Hz for the PWM pattern. A correct value may be 100.
Example : with a frequency of 1 Hz, and a duty cycle set to 25, GPIO pin will
stay HIGH for 1*(25/100) seconds on HIGH output, and 1*(75/100) seconds on LOW output.
"""
self.baseTime = 1.0 / frequency
self.sliceTime = self.baseTime / self.maxCycle
def stop(self):
"""
Stops PWM output.
"""
self.toTerminate = True
while self.terminated == False:
# Just wait
time.sleep(0.01)
GPIO.output(self.gpioPin, GPIO.LOW)
GPIO.setcfg(self.gpioPin, GPIO.INPUT)
|