User manual

56
6.1.1 How does it work?
Parts of this programme may seem familiar, some elements, however not at all. At this point we will delve
into object-oriented programming. As already known, we will first import libraries. This time, we define only
one variable,
LED, for GPIO port 18, this is initialized as output.
print (“Ctrl+C exits the program") Since this programme also runs with a try ... except
construct and has to be stopped by the user, a certain information will be displayed.
p = GPIO.PWM (LED, 50) The function GPIO.PWM () from the GPIO library is crucial for the output of PWM
signals. This function requires two parameters, the GPIO port and the frequency of the PWM signal. In our
case, the variable
LED will define the GPIO port, the frequency is 50 hertz (oscillations per second).
50 hertz is the ideal frequency for PWM
The human eye does not detect light changes which are faster than 20 Hertz. The frequency of the
oscillations of alternating current in the European electric power grid is 50 hertz. Many flashing lighting
bodies using this frequency are not detected by the eye. If an LED would flash in more than 20 Hertz, but
less than 50 Hertz, it could cause interferences with other sources of light, whereby the dimming light
effect would seem no longer consistent.
GPIO.PWM() generates a so-called object which will be stored in the variable p. Such objects are much more
than just simple variables. Objects can have different properties and can be influenced by so-called methods.
Methods are separated by a period, and are expressed directly after the object name.
p.start(0) The method start() starts the generation of the PWM signal. A duty cycle needs to be specified
too. In our case, the duty cycle is
0, the LED is therefore always off. The infinity loop will start now. It has
two loops embedded directly in succession that will alternate the LED light and dark levels.
for c in range(0, 101, 2): The loop counts in steps from2 to 0 until100. At the end of afor loop, the value
which is not processed, in our case this is
101, is always given.
p.ChangeDutyCycle(c) In each loop run the method ChangeDutyCycle sets the duty cycle of the PWM
object to the value of the loop counter, thus each time increasing by 2% until in the last cycle it stands at
100%, and the LED shines in full brightness.
time.sleep(0.1) Each loop run has a latency of 0.1 seconds, before the next iteration increases the duty
cycle by 2%.
for c in range(100, -1, -2):
p.ChangeDutyCycle(c); time.sleep(0.1)