News    The Project    Technology    RoboSpatium    Contribute    Subject index    Download    Responses    Games    Shopping tips    Contact   




<<< Software Raspberry         Python: Pulse-width modulation >>>

Python: Switching GPIOs

The circuit used in this chapter

Verbraucher mittels Python über GPIOs schalten
Figure 1:
In order to be able to make an LED blink, it must of course be wired to the Raspberry Pi. More about how to connect LEDs to GPIOs is written in the chapter on switching LEDs.
Which pins have which function can be found in the chapter on the hardware of the Raspberry Pi.

What is Python?

Computers process data as binary numbers. Program code must therefore be stored as zeros and ones. Writing such code directly is possible, but veeeery abstract. That is why so-called interpreter software was developed at an early stage in computing history. This turns human readable text into computer-executable, binary code. The Python interpreter does exactly that. The program text to be written, however, cannot be freely formulated, but must conform to the rules of this programming language. For example the text line:
Turn on GPIO number 16
Can't be processed by the Python interpreter. Instead, this must be as follows:
GPIO.output(16, GPIO.HIGH)
The line of text must read exactly like this, matching even upper and lower case letters. The line:
gpio.output(16, GPIO.HIGH)
cannot be processed by the Python interpreter either. Before the line shown here, which represents the command to switch on the GPIO, further commands are necessary to prepare the GPIO. With that we come to the complete ...

Python script to turn a GPIO on and off

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
#!/usr/bin/env python  
 
# Make special commands available to your source code  
# by importing code lines from outside this file  
 
import RPi.GPIO as GPIO # needed to switch GPIOs  
from time import sleep  # needed to make command "sleep" available  
 
 
# Choose BOARD pin numbering  
# On the Raspberry Pi, pin 1 ist the 3.3V pin on top left  
# pin 2 is +5V pin on top right and so on.  
# Only numbers that represent a GPIO pin are valid  
 
GPIO.setmode(GPIO.BOARD)  
 
# Set GPIO number 16 to output mode  
GPIO.setup(16, GPIO.OUT)  
 
# Define a variable and set it to 0  
loopCount = 0  
 
# Check if loopCount is lower than 3 and  
# execute code below the while statement that is intended  
# as long as that statement is true.  
# In this example, the LED blinks as long as loopCount is lower than 3  
# which is true for three loop runs  
 
while (loopCount < 3):         # While statement must end with :  
      
    # All code lines intended are executed  
    # as long as the while condition above is TRUE.  
    # If the condition is FALSE, those lines are skipped.  
      
    GPIO.output(16, GPIO.HIGH) # Turn LED ON  
    sleep(0.1)                 # Do nothing for 0.1 seconds  
    GPIO.output(16, GPIO.LOW)  # Turn LED OFF  
    sleep(1)                   # Do nothing for 1 second  
    loopCount = loopCount + 1  # Increase loopCount by 1  
      
    # Python now goes back to the while statement  
    # and checks the condition again.  
    # If that is FALSE, the program continues with the lines below.  
 
# While loop ends here  
# Blink LED once more, now on for 2 seconds  
 
GPIO.output(16, GPIO.HIGH) # Turn LED ON  
sleep(2)                   # Do nothing for 2 seconds  
GPIO.output(16, GPIO.LOW)  # Turn LED OFF  
 
# Free all GPIOs for use in other programs  
GPIO.cleanup()  
 
# Finally print a message that the script has reached the end  
print ("...all done, end of script reached!")  
    
The Python interpreter ignores all text that comes after the special character "#". This means that comments in plain text can be inserted in the program code. Such comments should be inserted wherever it makes sense to provide additional explanations as to the purpose of a part of the program. In the example above, I have commented on each line as this is intended for beginners in Python programming. Anyone who is just a little practiced will immediately recognize that the line:
GPIO.output(16, GPIO.HIGH)
Turns on pin 16. So there is no need for the comment behind it. How many comments you add is entirely up to you. But remember that you eventually have to modify your script after years because of a bug or you'd like to add functions and thats when comments are priceless! In principle, however, all comments can also be removed from the script. This then runs exactly as with the comments.
A special case is the very first comment:
#!/usr/bin/env python
This must be the first line of the script! It indicates to the operating system that this text file is a Python source code and must therefore be called via the corresponding interpreter.

Executing Python scripts

After storing the text file with the name "blink.py", it can be started in two ways via the command line:
Either by calling the Python interpreter with the file name of the script as a parameter:
python blink.py
or by declaring the file as being executable:
chmod a+x blink.py
and this is then started like all normal programs:
./blink.py
Do not forget "./" in front of the file name! Furthermore, you have to change to the directory in which you the "blink.py" is stored before using the commands. As mentioned above, the second version only works if the first line in the script is:
#!/usr/bin/env python

What to do if errors happen

The Python interpreter outputs messages if something in the program code is not written as expected. These can be warning messages that (sometimes) do not have an impact on the program execution or errors that lead to the execution being terminated. These messages are meant to be read and understood! The most important information is the program line on which the error occurred. If you search the net for descriptions of the error message, you will quickly find help, but NO, as a beginner you shouldn't start a new post in the appropriate forums because of every sh... Keep searching until you find the answer, because beginners mistakes have been made by thousands and thousands of beginners before you! Find the answer before you start wasting other people's time with your little problems! So far I have found a solution to all my questions on the Internet without typing any post in any forum, but sometimes you will have to spend a couple of hours. Yes, coding is nothing you will learn in an afternoon and some problems will keep you busy for days before you will find a solution. That's simply the way it is! You must spend lots of time to outgrow the "Setup.exe clicker" level. The reward you get is that in a world that is more and more ruled by technology, you will gain insights into data processing that is for ever hidden from the "Muggles", the non-coders.
However, don't hesitate to leave a comment, if you find errors on my pages of if there is something you find hard to understand (what, exactly?) or that is missing from your point of view.


<<< Software Raspberry         Python: Pulse-width modulation >>>


News    The Project    Technology    RoboSpatium    Contribute    Subject index    Archives    Download    Responses    Games    Links    Shopping tips    Contact    Imprint   





Twitter YouTube Hackaday Patreon TPO