Table of Contents 1 From installing the operating system to the first Python programme 1.1 What do I need? 1.1.1 Micro USB mobile charger 1.1.2 Memory card 1.1.3 Keyboard 1.1.4 Mouse 1.1.5 Network cable 1.1.6 HDMI cable 1.1.7 Audio cable 1.1.8 Yellow CVBS video cable 1.2 Installing the Raspbian operating system 1.2.1 Preparing the computer’s memory card 1.2.2 The software installer NOOBS 1.2.3 The LEDs on the Raspberry Pi 1.2.4 Starting the Raspberry Pi for the first time 1.
6 Dimming the LED using pulse width modulation 6.1.1 How does it work? 6.1.2 Dimming two LEDs independently of one another 6.1.3 How does it work? 53 56 57 59 7 Indicator with LEDs for free space on the memory card 7.1.1 How does it work? 60 63 8 Graphical dice 8.1.1 How does it work? 65 67 9 Analogue clock on-screen 9.1.1 How does it work? 72 73 10 Graphical dialog fields for program control 10.1.1 How does it work? 10.2 Controlling chaser by a graphical user interface 10.2.
1 From installing the operating system to the first Python programme The Raspberry Pi has hit the headlines in recent months like no other electronic device in this price range. Although it does not look like that at first glance, the Raspberry Pi is a full-fledged computer about the size of a credit card - at a very reasonable price. Not only the hardware is cheap, but also the software: The operating system and all applications required for everyday use can be downloaded free of charge. Fig. 1.
1.1.1 Micro USB mobile charger Any modern cell phone power supply is sufficient for the Raspberry Pi. However, older chargers from the early days of the USB charging technology are too weak. If you intend to connect a power-hungry USB devices such as external hard drives without a separate power supply you will need a stronger power supply. The power supply must provide 5 V and at least 700 mA, while 1000 mA is even better.
1.1.8 Yellow CVBS video cable If no HDMI monitor is available, you can connect the Raspberry Pi to an analogue composite video cable, with the typical yellow plugs and also to a typical a television; however, the image-screen resolution, will be very low. For TV sets without yellow composite input, converters from CVBS to SCART are available The graphical user interface works in analogue TV resolution only with restrictions. 1.
size of 1.2 GB from the official download page www.raspberrypi.org/downloads and using the PC unpack it to the memory card of at least 4 GB. Start the Raspberry Pi now from the memory card. Insert the memory card into the slot on the Raspberry Pi and connect keyboard, mouse, monitor and network cable. Finally it is time for the USB power port. It is used to switch the Raspberry Pi on. A separate power button does not exist.
Fig. 1.2: The status LEDs on the Raspberry Pi. 1.2.4 Starting the Raspberry Pi for the first time The Raspberry Pi will reboot and automatically launch the configuration raspi-config after the installation has completed. You only need to select the option Desktop Log in as user 'pi' under Enable Boot to Desktop. German and the German keyboard layout are automatically selected along with other important basic settings. The graphical LXDE desktop is available after rebooting. 1.
Fig. 1.3: The LXDE desktop environment on the Raspberry Pi is very similar to Windows XP. Raspbian-Linux for the Raspberry Pi uses the interface LXDE (Lightweight X11 Desktop Environment), which on the one hand requires very little system resources and on the other hand its Start Menu and the File Manager are very much like the familiar Windows interface. Linux Application Even the typical Linux user registration happens in the background.
1.3.1 Saving your data on the Raspberry Pi File management on Linux runs a bit different than it does under Windows, but is not difficult at all. Raspbian features a file manager, which looks just like the Windows Explorer. There is an important difference to Windows: Linux does not strictly separate the drives, all files are located in a shared file system. Basically on Linux, you store all your documents under the home directory. It is called here /home/pi according to the username pi.
Fig. 1.5: ... or like that. How much free space is on the memory card? Not only hard drives of personal computers are quickly full - with the memory card of the Raspberry Pi this happens much faster. That is why it is important to always keep an eye on the free and the used space on the memory card. The status bar of the File Manager at the bottom on the right shows the memory card’s free and used space. 1.
Python 2.7.3 is started with the icon IDLE on the desktop. A command window with a command prompt appears on the desktop, which looks simple at a first glance. Fig. 1.6: The input window of the Python shell. In this window you can open existing Python programs, write new ones or you can directly execute Python commands interactively, without having to write a real programme.
Python Flashcards Python is the ideal programming language to introduce you to programming. It takes a bit to get used to the syntax and the layout rules. A brief description of the main syntax elements of the Python programming language in the form of a "cheat sheet” will help you with everyday programming. These are based on the Python Flashcards by David Whale. Find out what this is all about on bit.ly/pythonflashcards.
Fig. 1.8: The correct setting to display umlauts in Python. 4. Start the game using the key [F5] or menu item Run/Run Module. 5. To simplify matters, the game forgoes any graphic interface and explanatory texts and does not query input parameters. The computer generates a random number between 0 and 1,000 in the background. Just enter a guess, and find out whether the number to be guessed is larger or smaller. Take more guesses until you have guessed the right number.
Fig. 1.9: 1.4.1 Guessing numbers with Python 1.4.2 How does it work? Let’s try and see if the game works. Naturally some questions are coming up: What is happening in the background? What are the individual command lines standing for in the programme? import random To generate the random number, an external Python module called random is imported which contains various functions for random generators. number = random.
How are random numbers generated? Generally you would think that in a program nothing happens at random. How then is it possible that a program can generate random numbers? If you divide a large prime number by any value you will get umpteenth decimal digits that are barely predictable. These decimals change without any regularity, if the divisor is increased regularly.
In each instance – not anymore indented – the counter i that counts the attempts is increased by one. The line with the operator += equals i = i + 1. i += 1 print “You guessed the number in ",i,". Guesses” This line is more indented, which means that the while loop ends here.
Caution Under no circumstances do you connect any GPIO pins to one another and wait to see what will happen. Adhere to the following instructions: Some GPIO pins are directly connected to terminals of the processor; a short circuit may totally ruin the Raspberry Pi. A series resistor must always be interposed when connecting two pins with each other using a switch or LED. Pin 1, which supplies + 3.3V and a current draw up to 50 mA, is always used for logic signals.
• 4x resistor 220 Ohm (red-red-brown) • 12x connecting cables (breadboard – Raspberry Pi) • ca. 1 m jumper wire 2.1.1 Breadboards Two breadboards are included in the package so that electronic circuits can be built quickly. Here the electronic components can be plugged directly into a matrix with standard spacing, and without the need to solder. The outer longitudinal rows with contacts (X and Y) are all interconnected on these circuit boards. Fig. 2.
A jumper wire is also included in the learning package. It is used to build short connecting bridges to which the contact rows on the breadboard are connected. Cut the wire with a wire cutter to the appropriate length, as described in the individual experiments. We recommend cutting the wires slightly at an angle, so that they form a wedge-shape, which allows you to insert the wires into the breadboard more easily. Remove the insulation at both ends over a length of roughly half a centimeter. 2.1.
The learning package contains resistors in three different values: Value 1. Ring (Tenth) 2. Ring (Ones) 3. Ring (Multipl.) 4. Ring (Toleranc e) Use 220 Red Red Brown Gold Series resistors for LEDs 1 kOhm Brown Black Red Gold Protective resistors for GPIO inputs 10 kOhm Brown Black Orange Gold Pull-down resistors for GPIO inputs Tab. 2.2: Colour codes of resistors in the learning package Pay attention in particular to the colours of the 1 kOhm and 10 kOhm resistors.
Fig. 2.3: Breadboard assembly to connect a LED.
Fig. 2.4: The first LED on the Raspberry Pi. In this first experiment we will use the Raspberry Pi only as the power supply for the LED. The LED is always on and there is no need for any software. In the next experiment you add a button to the lead of the LED. The LED lights up only when this button is pressed. Here, too, no software is needed.
Fig. 2.5: Breadboard assembly for a LED that is controlled by a button.
Fig. 2.6: LED with button on a Raspberry Pi. 2.3 GPIO and Python In order to be able to use Python programs on the GPIO ports, the Python library for GPIO must be installed. If you are you not sure whether all necessary modules are installed, reinstall the up-to-date versions using the following the console commands: sudo apt-get update sudo apt-get install python-dev sudo apt-get install python-rpi.
2.4 Switching the LED on or off Connect a LED via a 220-ohm series resistor (red-red-brown) to the GPIO port 25 (Pin 22), and not anymore directly to the + 3.3 V connector, and connect the negative terminal of the LED via the ground rail on the breadboard to the ground wire of the Raspberry Pi (Pin 6), as shown in the next image. Components required: 1x breadboard 1x LED red 1x 220-ohm series resistor 2x connecting wire The next program led.py turns the LED on for 5 seconds and then off: import RPi.
Fig. 2.7: An LED at GPIO port 25 2.4.1 How does it work? The example shows the essential basic functions of the RPi.GPIO library. import RPi.GPIO as GPIO The library RPi.GPIO must be imported into every Python program, that you are going to use. By using the prefix GPIO this notation can call all functions of the library. import time The often used Python library time has nothing to do with GPIO programming. It contains functions in terms of time and date calculation, including the time.
Numbering of the GPIO ports The library RPi.GPIO supports two modes to identify the ports. In mode BCM the known GPIO port numbers are used, as they are also used on command line level or in shell scripts. In alternative mode BOARD the notation equal the pin numbers from 1 to 26 on a Raspberry Pi board. GPIO.setup(25, GPIO.OUT) The function GPIO.setup initializes a GPIO port as output or as input.
• Create a copy of the pre-installed desktop icon IDLE. Proceed as follows: • Right-click the icon IDLE on the desktop using your mouse and select Copy in the shortcut menu. Fig. 2.8: Copying the IDLE desktop icon. Then right-click on the desktop with your mouse and select Paste in the shortcut menu. A message appears when you attempt to create a copy that a desktop shortcut with the same name already exists. Rename the copy here from idle.desktop to idle_gpio.desktop.
Fig. 2.9: A message of a desktop shortcut when duplicating. Right-click now the copy of the desktop icon with your mouse and select leafpad from the shortcut menu. In Linux desktop shortcuts are mere text files, which can be edited using a text editor. Fig. 2.10: The desktop shortcut in Leafpad editor. Make the two modifications as illustrated here: • Change the field Name to IDLE GPIO. This is the name shown on the screen. • In the field Exec enter just before the actual command call the word sudo.
3 Traffic light To turn on and off a single LED may be very exciting at first, but you do not really need a computer for this. A traffic light with a typical luminous cycle that is changing from green to yellow and then to red, and then from the light combination red and yellow back to green, can be easily built with three LEDs and hence, shows more programming techniques in Python. Build the pictured circuit on the breadboard.
Fig. 3.2: A simple traffic light. The program ampel01.py controls the light: import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) red = 0; yellow = 1; green = 2 Light=[4,18,23] GPIO.setup(light[red], GPIO.OUT, initial=False) GPIO.setup(light[yellow], GPIO.OUT, initial=False) GPIO.setup(light[green], GPIO.OUT, initial=True) print ("Strg+C exits the program") try: while True: time.sleep(2) GPIO.output(light[green],False); GPIO.output(light[yelllow],True) time.sleep(0.
GPIO.output(light[yellow],False); GPIO.output(light[red],True) time.sleep(2) GPIO.output(lightl[yellow],True) time.sleep(0.6) GPIO.output(light[red],False); GPIO.output(light[yellow],False) GPIO.output(lihtl[green],True) except KeyboardInterrupt: GPIO.cleanup() 3.1.1 How does it work? The first lines are already known, they import RPi.GPIO libraries for controlling the GPIO ports and the time for time delays. Then the numbering of the ports GPIO, as in the previous example, is set to BCM.
If in the meantime a system exception occurs – which can be due to an error or caused by the keyboard shortcut [Ctrl]+[C] – the code will abort and the statement except at the end of the programme is executed. except KeyboardInterrupt: GPIO.cleanup() The key combination will invoke a KeyboardInterrupt and the loop is automatically exited. The last line closes the GPIO ports used and thus switches off the LEDs. After that the program closes.
4 Pedestrian lights In the next experiment we are going to extend the traffic light by adding a pedestrian light which will feature a flashing light for pedestrians during the traffic light’s red phase, as is common practice in some countries. Obviously we could also integrate a pedestrian light into the program with red and green lights, which are commonplace in Central Europe. However, besides the LEDs used for the traffic light the learning package contains only one more LED.
Fig. 4.2: Traffic light with flashing light for pedestrians. The programme ampel02.py controls the traffic light system. Compared to the previous version the program has been slightly expanded. import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) red = 0; yellow = 1; green = 2; blue = 3 Light=[4,18,23,24] GPIO.setup(light[red], GPIO.OUT, initial=False) GPIO.setup(light[yellow], GPIO.OUT, initial=False) GPIO.setup(light[green], GPIO.OUT, initial=True) GPIO.setup(light[blue], GPIO.
time.sleep(2) GPIO.output(light[green],False); GPIO.output(light[yelllow],True) time.sleep(0.6) GPIO.output(light[yellow],False); GPIO.output(light[red],True) time.sleep(0.6) for i in range(10): GPIO.output(light[blue],True); time.sleep(0.05) GPIO.output(light[blue],False); time.sleep(0.05) time.sleep(0.6) GPIO.output(light[yellow],True); time.sleep(0.6) GPIO.output(light[red],False) GPIO.output(light[yellow],False) GPIO.output(lightl[green],True) except KeyboardInterrupt: GPIO.cleanup() 4.1.
here so far. But it gets interesting when the pedestrian light, instead of running automatically, is started by pressing a button as is the case with many pedestrian lights. In the next experiment a button is connected to a GPIO port that will simulate the push button on a real traffic light. 4.2 Button on the GPIO connector GPIO ports not only output data, for example by means of LEDs, but they can also be used to input data. Therefore they must be defined as input in the programme.
Fig. 4.4: Pushbutton with protective resistance and pull-down resistor on a GPIO input. Build a button with its two resistors into the circuit according to the following illustration. Fig. 4.5: Breadboard assembly for the pedestrian lights “on-demand”.
Components required: 1x breadboard 1x LED red 1x LED yellow 1x LED green 1x LED blue 4x 220-ohm series resistor 1x button 1x 1-kOhm resistor 1x 10-kOhm resistor 7x connecting wire 1x short jumper bridge This figure shows the lower contact strip of the button connected via the positive rail of the breadboard to the +3.3 V wire of the Raspberry Pi (Pin 1). To connect the button to the positive rail, we will use a short jumper to keep the drawing clear.
Fig. 4.6: Flashing pedestrian light with button. The programme ampel02.py controls the new traffic light system with button for the flashing pedestrian light. # -*- coding: utf-8 -*import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) red = 0; yellow = 1; green = 2; blue = 3; button = 4 Light=[4,18,23,24,25] GPIO.setup(light[red], GPIO.OUT, initial=False) GPIO.setup(light[yellow], GPIO.OUT, initial=False) GPIO.setup(light[green], GPIO.
GPIO.setup(light[blue], GPIO.OUT, initial=False) GPIO.setup(light[button], GPIO.IN) print (“Press button to turn on pedestrian light, “Ctrl+C exits the program") try: while True: if GPIO.input(light[button])==True: GPIO.output(light[green],False) GPIO.output(lightl[yellow],True) time.sleep(0.6) GPIO.output(light[yellow],False) GPIO.output(light[red],True) time.sleep(0.6) for i in range(10): GPIO.output(light[blue],True); time.sleep(0.05) GPIO.output(light[blue],False); time.sleep(0.05) time.sleep(0.6) GPIO.
Later, when in parallel with the ASCII character the ANSI character set was introduced, which is used by older versions of Windows, the very same mistake happened again. When the German umlauts and other accented characters were allocated other places in the character set than in the standard of ASCII, the linguistic chaos reached perfection.
When starting the programme, a message is displayed that notifies the user to press the button while True: if GPIO.input(light[button])==True: Within the loop, a query is now set up. The following statements are only executed when the GPIO port 25 has the value True, that is, the user presses the button. Until then, the traffic light will be in the green state. The rest of the loop’s process basically corresponds to the previous programme.
Components required: 1.x breadboard 1x LED red 1x LED yellow 1x LED green 1x LED blue 4x 220-ohm series resistor 5x connecting wire Fig. 5.2: Four LEDs with series resistors.
We will explain now more loops and programming methods in Python by using different LED flashing patterns. The next programme offers different LED samples that the user can select by making keyboard entries. The programme ledmuster.py allows the LEDs to use different flashing patterns. # -*- coding: utf-8 -*import RPi.GPIO as GPIO import time import random GPIO.setmode(GPIO.BCM) LED = [4,18,23,24] for i in LED: GPIO.setup(i, GPIO.OUT, initial=0) z = len(LED); w = 5; t = 0.
for j in range(z): GPIO.output(LED[j], False) time.sleep(t) elif e == "5": for i in range(w*z): j = random.randint(0,z-1) GPIO.output(LED[j], True); time.sleep(t) GPIO.output(LED[j], False) else: print (“Invalid entry") except KeyboardInterrupt: GPIO.cleanup() 5.1.1 How does it work? Through previous experiments you are already familiar with the first lines of the program that is, the definition of the UTF-8 encoding and the import of the necessary libraries.
For the programme to be universal and easily alterable, we will ow define three variables: z Number of LEDs The number of LEDs is automatically adopted from the list LED by using the functionlen(). w Repetitions Each pattern is repeated five times by default so that the pattern is better for better recognize it better detected. This number can be changed as desired, and is then applies to all patterns. t Time This variable indicates how long a flashing LED is turned on.
The program waits until the user has typed a character and has pressed the [Enter] key. Depending on the number the user has entered, the LEDs should now perform according to certain pattern. We will query this with the use of the construct if...elif...else. Pattern 1 If the entry was 1, the indented part of the programme that comes after this line is executed. if e == "1": Note that indents in Python are not used as optical effects. As we do with loops, we also start those queries with an indent.
Here too nested loops are used. After the first inner loop, which corresponds to the part of the program described above, that is, after the LED with the number 3 lights up, another loop starts for the chaser light now running in the opposite direction. Elements in the list start always with 0. So the fourth LED has the number 3. For loop to run backwards, we are going to use the extended syntax for...range().
Pattern 4 If the user has entered 4, a different flashing pattern starts, in which all LEDs are flashing simultaneously and are not called up in sequence. elif e == "4": for i in range(w): for j in range(z): GPIO.output(LED[j], True) time.sleep(2*t) for j in range(z): GPIO.output(LED[j], False) time.sleep(t) Not all GPIO ports can be switched on or off at once with a single statement, that is why also here loops are used, however, without a time lag within the loop.
If the user has entered something else, the statement specified in elseis executed. This section of a query is always applied, if no other queries have delivered true results. In our case, the programme displays a message on-screen. As in previous experiments, the programme is terminated via KeyboardInterrupt, that is, the user pressing the key combination [Ctrl]+[C]. The last line closes the GPIO ports used and thus switches off the LEDs.
Fig. 6.2: Breadboard assembly with LED.
Fig. 6.3: An LED at GPIO port 18. The programme leddimmen01.py dims the LED using cycles of light and dark phases and utilizes the PWM function from the GPIO library. The PWM signal is generated as a separate thread. This allows the use of a dimmed LED (almost) like any normally lit LED in a programmr. import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM); LED = 18 GPIO.setup(i, GPIO.OUT, initial=0) print (“Ctrl+C exits the program") p = GPIO.PWM(LED, 50); p.
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.
After the LED has achieved its full brightness, a second loop regulates the intensity in the same way but reverse. This loop counts down from 100 in increments of -2. This cycle iterated until a user stops it with the key combination [Crtl]+[C]. except KeyboardInterrupt: p.stop(); GPIO.cleanup() The KeyboardInterrupt triggers now also the method stop()of the PWM object. This method stops the generation of a PWM signal. Then the GPIO ports are reset as already known from past programmes. 6.1.
Components required: 1x breadboard 1x LED yellow 1x LED red 2x 220-ohm series resistor 3x connecting wire Fig. 6.5: A second LED at GPIO port 25. The programme leddimmen02.py dims one of the LED using cycles of light and dark phases, while the other LED together with the first LED light gets brighter, but in another cycle it does not get darker, instead its brightness intensifies starting from 0 and it is also flickers quickly. import RPi.
GPIO.setmode(GPIO.BCM); LED = [18,25] GPIO.setup(LED[0], GPIO.OUT); GPIO.setup(LED[1], GPIO.OUT) print (“Ctrl+C exits the program") p = GPIO.PWM(LED[0], 50); q = GPIO.PWM(LED[1], 50) p.start(0) p.start(0) try: while True: for c in range(0, 101, 2): p.ChangeDutyCycle(c); q.ChangeDutyCycle(c) time.sleep(0.1) q.ChangeFrequency(10) for c in range(0, 101, 2): p.ChangeDutyCycle(100-c); q.ChangeDutyCycle(c) time.sleep(0.1) q.ChangeFrequency(50) except KeyboardInterrupt: p.stop(); GPIO.cleanup() 6.1.
The second loop is starting now, for reasons of clarity it will count in an ascending order this time. The corresponding values for the duty cycle of each iteration are calculated for the first LED from the PWM object which in this cycle is dimmed step by step. The duty cycle for the second LED is simply incremented again by the PWM object q. The blinking effect is caused by the modified frequency. q.
Fig. 7.2: Breadboard assembly for indicator of the free space on a memory card.
Fig. 7.3: Three LEDs will show the free space on the memory card. The programme speicheranzeige.py provides different LED indications depending on the free space on the memory card: Free space LED display < 1 MB Red 1 MB to 10 MB Red–yellow 10 MB to 100 MB Yellow 100 MB to 500 MB Yellow-green > 500 MB Green Tab. 7.1: This is how the memory status is displayed.
import RPi.GPIO as GPIO import time import os g1 = 1; g2 = 10; g3 = 100; g4 = 500 GPIO.setmode(GPIO.BCM) LED = [4,18,23] for i in range(3): GPIO.setup(LED[i], GPIO.OUT, initial=False) print (“Ctrl+C exits the programme") try: while True: s = os.statvfs('/') f = s.f_bsize * s.f_bavail / 1000000 if f < g1: x = "100" elif f < g2: x = "110" elif f < g3: x = "010" elif f < g4: x = "011" else: x = "001" for i in range(3): GPIO.output(LED[i], int(x[i])) time.sleep(1.0) except KeyboardInterrupt: GPIO.
GPIO.setmode(GPIO.BCM) LED = [4,18,23] for i in range(3): GPIO.setup(LED[i], GPIO.OUT, initial=False) A list defines the GPIO port numbers of the three LEDs. The loop initializes the three GPIO ports as outputs and resets all LEDs to its off-state. Also in this experiment, we use the construct try...exceptand an infinity loop to automatically run the programme over and over until it stopped by the user with[Ctrl]+[C] ].
activate or deactivate GPIO outputs. The function int() calculates a character’s numeric value. The character is read out from a certain position of the pattern string via the loop counter i. time.sleep (1.0) The program waits 1 second until the next iteration. To save performance, you can also prolong the latency until the calculation of free space is repeated. At this point, the while...True loop restarts.
pygame.display.set_caption(“Dicel") BlUE = (0, 0, 255); WHITE = (255, 255, 255) P1 = ((160, 160)); P2 = ((60, 60)); P3 = ((160, 60)); P4 = ((260, 60)) P5 = ((60, 260)); P6 = ((160, 260)); P7 = ((260, 260)) mainloop = True print “Press any key to roll the dice, [Esc] exits the game” while mainloop: for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): mainloop = False if event.type == KEYDOWN: FELD.fill(BUE) NUMBER = random.
8.1.1 How does it work? This programmr displays many new features, especially for graphics output by the PyGame library which of course is not only used for games only for games but also for any other graphics on the screen. import pygame, sys, random from pygame.locals import * pygame.init() These three lines of code stand at the beginning of almost every programme that uses PyGame.
The seven points P1 to P7mark in the graphic the midpoints of the dice. Each dot of a dice has a radius of 40 pixels. At 80 pixels center distance, 20 pixels remain between the dots of the dice and 20 pixels to the window edges. Fig. 8.2: The dots of the dice and their coordinates. At this point, a variable that goes by the name mainloop is set to True along with the other variables which we will need for the main loop of the game at a later stage.
This line tells the user, what to do. Each time you press any key on the keyboard rolls the dice. print always writes into the Python Shell window, not in the new graphical window. while mainloop: Now the main loop of the game starts. In many games an infinite loop is used which is repeated over and over again and constantly queries any user activity. Somewhere in the loop an abort statement must be defined, which ensures that the game can exit.
This is followed by six queries all performed in the same way. If the random number thrown has a certain value, one to six dice spot will be marked accordingly. The function employed is pygame.draw.circle() and requires four to five parameters: • Surface specifies the drawing canvas, which is FIELD in the example. • Colour specifies the colour of the circle, in the example, the previously defined colour WHITE. • Midpopint specifies the centre of the circle.
Fig. 8.3: Six possible dice scores. The loop restarts immediately and waits for the user’s keystroke. If, however, mainloop is set to False during the loop because the user wants to quit the game, the loop will not rerun and the following line is executed: pygame.quit() This line terminates the PyGame module and closes the graphical window and then the whole programme.
9 Analogue clock on-screen The digital display of time on computers, that we are accustomed to today has come into fashion only in the 70's. For centuries time was displayed analogously with pointers on a dial. The boom in digital watches has declined somewhat in recent years. We have come to realize that analogue clocks are better readable and can be seen and read under poor weather conditions or over long distances, such as in railway stations, much faster and clearer.
FIELD = pygame.display.set_mode((400, 400)) FIELD.fill(WHITE) MX = 200; MY = 200; MP = ((MX, MY)) def point(A, W): w1 = radians(W * 6 – 90); x1 = int(MX + A * cos(w1)) y1 = int(MY + A * sin(w1)); return((x1, y1)) for i in range(60): pygame.draw.circle(FIELD, BLACK, point(190, i), 2) for i in range(12): pygame.draw.circle(FIELD,BLACK, point(190, i * 5), 4) mainloop = True; s1 = 0 while mainloop: time = time.localtime() s = time.tm_sec; m = time.tm_min; h = time.tm_hour if h > 12: h = h – 12 hm = (h + m / 60.
Three variables determine the coordinates of the midpoint; all other graphical elements, the dial and the hands are in alignment with the midpoint. The variables MX and MY contain the x- and y-coordinates of the midpoint, the variable MP the midpoint point as dot, as used for graphics functions. Next comes the definition of an important function that calculates dots based on the distance to the centre and angle points in the coordinate system.
succession at an angular distance of five minute units; that is achieved by multiplying the angle data by 5 which is passed on to the function. mainloop = True; s1 = 0 Before the main loop of the program starts, two auxiliary variables are defined, which are needed in the following process. As in the last program sample, mainloop indicates whether the loop should continue running or if the user wants to exit the programme. s1 saves the last second that was displayed. while mainloop: time = time.
If the second has changed in respect to the last one drawn changed, the graphics of the clock is updated by the following statement. If nothing has changed, the graphics is not updated, and the loop restarts with yet another query of the current system time. pygame.draw.circle(FIELD, WHITE, MP, 182) A white circular area is drawn first, which covers the hand completely. The radius with 182 pixels is slightly larger than the longest pointer, to ensure that no remnants remain.
pygame.display.update() So far, all the graphic elements have been drawn only virtually. But this line restructures the graphic display genuinely. It is updated simultaneously. Therefore, you can’t see any flickering when the individual pointers are drawn in sequence. for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYUP and event.
Fig. 10.1: A single LED at GPIO port 4. Connect an LED via a series resistor to the GPIO port 4. The programme ledtk01.py will turn the lights on. import RPi.GPIO as GPIO from Tkinter import * LED = 4; GPIO.setmode(GPIO.BCM); GPIO.setup(LED,GPIO.OUT) def LedOn(): GPIO.output(LED,True) def LedOff(): GPIO.output(LED,True) root = Tk(); root.title("LED") Label(root, text=”Please click a button to turn the LED on or off").pack() Button(root, text=”On", command=LedOn).
Button(root, text=”Off", command=LedOff).pack(side=LEFT) root.mainloop() GPIO.cleanup() Fig. 10.2: The final dialog box will look like this. 10.1.1 How does it work? This programme shows the basic functions of the Tkinter library for the building graphical dialogs.
root.title("LED") Objects in Tkinter make different methods for different purposes available. The method in a widget sets the window caption, and in our case, it writes the word LED into the title bar of the new window. title() Each widget can contain multiple objects that are defined separately. Tkinter knows different types of objects, each of them features different parameters to describe the object's properties. The parameters separated by commas, are embedded in a bracket after the object type.
root.mainloop() The main program has only this single line. It starts the main loop mainloop(), a method of the root widget. This programme loop waits for the user to activate a widget which will thus trigger an action. There is no need in Tkinter to specifically define the x-icon at the top right that closes the window. If the user closes the main window root, the main loop mainloop ()is terminated automatically. GPIO.
Fig. 10.4: Breadboard assembly for experiment 10.
Fig. 10.5: Four LEDs are flashing using different patterns. The programme ledtk02.py is built on the previous programme, but has been expanded to include the radio buttons and the functions of the LED chasing lights and flashing patterns. import RPi.GPIO as GPIO import time from Tkinter import * GPIO.setmode(GPIO.BCM) LED = [4,18,23,24] for i in LED: GPIO.setup(i, GPIO.OUT, initial=0) w = 5; t = 0.
] root = Tk(); root.title("LED"); v = IntVar(); v.set(1) def LedOn(): e = v.get() if e == 1: for i in range(w): for j in range(4): GPIO.output(LED[j], True) time.sleep(t) GPIO.output(LED[j], False) elif e == 2: for i in range(w): for j in range(4): GPIO.output(LED[j], True) time.sleep(t) for j in range(4): GPIO.output(LED[j], False) time.sleep(t) else: for i in range(w): for j in range(4): GPIO.output(LED[3-j], True); time.sleep(t) GPIO.
The texts of the three patterns of choice are defined in a separate list form. Each of the three list elements consists of a pair of values, each consisting of the text displayed and a numeric value, which is returned later when the respective radio button is selected. root = Tk(); root.title("LED") The initialization of the root widget corresponds to the previous program, however, the contents of the dialog box differ. root = Tk(); root.title("LED"); v = IntVar(); v.
GPIO.output(LED[3-j], True); time.sleep(t) GPIO.output(LED[3-j], False) The third case is similar to the first, with the difference that the LEDs are counted down backwards and thus reversing the direction of the chaser’s run. When this function is defined, the elements of the graphical user interface are created. Label(root, text=”Please click a button to start the chaser ").pack() The text in the dialog is again defined as Label object. New is the definition of the three radio buttons.
10.3 Setting the flashing rate In a third step, the dialog box is expanded again. The user can now adjust with a slider, the blinking speed. Fig. 10.6: Three LED patterns to choose from and the customizable flashing rate. Use of the sliders Slide controls provide a very intuitive way to enter numerical values within a defined range.
GPIO.output(LED[j], True); time.sleep(t) GPIO.output(LED[j], False) elif e == 2: for i in range(w): for j in range(4): GPIO.output(LED[j], True) time.sleep(t) for j in range(4): GPIO.output(LED[j], False) time.sleep(t) else: for i in range(w): for j in range(4): GPIO.output(LED[3-j], True); time.sleep(t) GPIO.output(LED[3-j], False) Label(root, text=”Please click a button to start the chaser ").pack() for txt, m in pattern: Radiobutton(root, text = txt, variable = v, value = m).
Converting integers to floating-point values The result of a calculation is automatically saved as floating point number if at least one of the values in the formula is a floating point number. If all values in the formula are integers (Integer), the result will also be reduced to an integer. The definition of the label and the radio buttons in the dialog box are taken from the previous example. Label(root, Label(root, text=”Speed").
Fig. 11.1: The game Simulate of the Python Games Our game PiDance is also based on the principle of this game. LEDs are flashing in random order. The user has to press the buttons in the same order. With each round, another LED lights up, so that it becomes more difficult to remember the order. One mistake, and the game is over. The game is built on two breadboards, so that the buttons are located on the edge and can be operated comfortably without accidentally pulling cables from the boards.
Fig. 11.
Fig. 11.3: PiDance with LEDs and buttons using two breadboards The buttons are built opposite to the associated LEDs. The two middle longitudinal rows of the breadboard on both sides of the joint serve as the circuit’s 0 V and +3.3 V line. The programme pidance01.py contains the game. # -*- coding: utf-8 -*import time, random import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) rnumber = 10; color = [] for i in range(w): color.append(random.randrange(4)) LED = [4,18,23,24] for i in LED: GPIO.setup(LED[i], GPIO.
if(GPIO.input(TAST[2])): return 2 if(GPIO.input(TAST[3])): return 3 ok = True for round in range(1, rnumber +1): print “Round", round for i in TAST: LEDOn(color[i], 1) for i in range(round): button = press() LEDOn(button, 0.2) if(button != color[i]): print “Lost!" print “You have made it to round", round – 1, “success" for j in range(4): GPIO.output(LED[j], True) for j in range(4): time.sleep(0.5) GPIO.output(LED[j], False) ok = False break if(ok == False): break time.sleep(0.
LED = [23,24,25,8] for i in LED: GPIO.setup(i, GPIO.OUT, initial=False) The GPIO ports for LEDs are set up as outputs in a list LED following the familiar procedure and all LEDs are set to off. TAST = [4,17,21,22] for i in TAST: GPIO.setup(i, GPIO.IN) Now following the same principle, the GPIO ports for the four buttons are set up in a list TAST as inputs. We have created the foundation, and will now define two more functions that are needed several times in the programme. def LEDOn(n, z): GPIO.
The actual round is displayed in the Python Shell window for i in range(round): LEDOn(color[i], 1) Now the program performs the pattern that the player has to remember. Depending on the actual number of rounds, LEDs light up one after the other in the random colours according to the list colour which was set up in the program previously. Since the counter round starts with 1, one LED is already lit in the first round.
time.sleep(0.5) If the entry of the sequence was correct, the programme waits for 0.5 second and starts the next round. if(ok == True): The programme reaches this point when either the loop has fully run though, that is, the player has entered the correct sequences, or the previous loop has been discontinued due to a mistake made by the player. If ok is still on True the awarding ceremony takes place. Otherwise this block is skipped, and the game only executes the last command line of the programme.
Impressum © 2014 Franzis Verlag GmbH, Richard-Reitzner-Allee 2, 85540 Haar near Munich www.elo-web.de Author: Christian Immler ISBN 978-3-645-10145-5 All rights reserved, including the rights of photomechanical reproduction and storage on electronic media. Creating and distributing copies on paper, on disk or on the Internet, in particular as PDF, is permitted only with the explicit permission of the publisher and is failing to do will result in criminal proceedings.