Titelei :33 Seite 1. Franzis Raspberry Pi Maker Kit

Size: px
Start display at page:

Download "Titelei :33 Seite 1. Franzis Raspberry Pi Maker Kit"

Transcription

1 Titelei :33 Seite 1 Franzis Raspberry Pi Maker Kit

2 Titelei :33 Seite 2

3 Titelei :33 Seite 3 TURN ON YOUR CREATIVITY RASPBERRY PI

4 Titelei :33 Seite 4 Dear customers! This product was developed in compliance with the applicable European directives and therefore carries the CE mark. Its authorized use is described in the instructions enclosed with it. In the event of non-conforming use or modifi cation of the product, you will be solely responsible for complying with the applicable regulations. You should therefore take care to assemble the circuits as described in the instructions. The product may only be passed on along with the instruction and this note. Waste electrical products should not be disposed of with household waste. Please recycle where facilities exist. Check with your local authority or retailer for recycling advice. All circuits and programs depicted in this book are developed and tested with utmost care. Nonetheless, it is not possible to rule out all errors in the book or in the soft ware. Publisher and author are only liable in case of intent or gross negligence according to legal regulation. Beyond that, publisher and author are only liable according to the law on product liability concerning hazards to life, body, and health and the culpable violation of essential contractual obligations. The damage claim for the violation of essential contractual obligations is limited to the contract-specifi c, predictable damage, unless in cases of mandatory liability according to the law on product liability. All rights reserved, including those of reprinting, reproduction and storage in electronical media. No part may be reproduced and distributed on paper, on storage media, or in the Internet, especially as PDF, without the publisher s prior written permission. Any attempt may be prosecuted. Hardware and soft ware product names, company names, and company logos mentioned in this book are generally registered trademarks and have to be considered as such. For product names, the publisher uses mainly the spelling of the manufacturer. ISBN Author: Christian Immler Translation and DTP: G&U language & Publishing Services GmbH, Flensburg Art & Design Cover: Franzis Verlag GmbH, Richard-Reitzner-Allee 2, Haar

5 Table of contents Before we begin Lighting up the first LED 14 2 Your first Scratch program 28 3 GPIO and Scratch 32 4 Pedestrian light 44 5 Pedestrian light in Scratch 52 6 LED DICE 58 7 Control the Scratch cat with GPIO buttons 66 8 First experiments with the LC display 70 9 Controlling the LC display in Python LC display in 8-bit mode Displaying the IP address of the Raspberry Pi Marquee text on the LC display Extended status display Interactive status display with push-buttons Chaser lights with the port expander Binary clock CPU load gauge with LEDs at the port expander LC display at the port expander LC display for Raspberry media center PiKey PiKey: Controlling games with your fingers 146 You can download all the scripts/source code from

6 Before we begin... Nearly no other electronic device in this price range has got so much attention in the last months as the Raspberry Pi. Although it is not much bigger than a credit card, the Raspberry Pi is a full-fledged computer, and it is very low priced. The software is even cheaper than the hardware, as the operating system and all necessary applications can be downloaded free of charge. The Raspberry Pi, a miniature PC With the specifically adapted Linux, the Raspberry Pi is an energy saving, silent PC replacement. Because of its arbitrarily programmable GPIO interface, the Raspberry Pi is particularly interesting for hardware tinkering and the maker community.

7 What do you need? When you read this text, you probably have already concerned yourself with the Raspberry Pi. Therefore we will just summarize the system requirements for the Maker Kit. Raspberry Pi Of course you need a Raspberry Pi, namely the popular model B. Model A has less memory and no network connection. Micro-USB charger for mobile phones You can use any modern mobile phone charger for the Raspberry Pi. It must provide 5 V and at least 700 ma, although 1000 ma is recommended. Older mains adapters from the early days of USB charging technology are too weak. If you connect power-hungry USB devices like external hard drives without a power source of their own, you need a more powerful mains adapter. When the Raspberry Pi boots, but the mouse cursor does not Effects of move or the system does not react to key inputs, the power supply an insufficient may be too weak. You should also use a more powerful mains adapter mains adapter when you cannot access connected USB sticks or hard drives. Memory card The memory card contains the operating system. Any own data and installed programs are also stored on the card. It should have a capacity of at least 4 GB. According to the manufacturer of the Raspberry Pi, it should support at least the class 4 standard. This standard refers to the speed of the memory card. A modern class 10 card shows a significantly increased performance. The number in the circle refers to the classification of the memory card. Left: 4 GB class 6, right: 16 GB class 10.

8 8 Before we begin... Keyboard Any current keyboard with USB connection will suffice. Wireless keyboards may not always work as they need too much power or special drivers. Mouse The mouse must have a USB connection. Some keyboards have an additional USB port for a mouse, so you have another USB port on the Pi at your disposal that you can use e. g. for a USB stick. Network cable To connect to the router in the local network, you need a network cable. In any case, this is required for the initial setup. After that, you can also use a Wi-Fi connection. Without access to the Internet, many features of the Raspberry Pi are not usable in a reasonable way. HDMI cable You can connect the Raspberry Pi to a monitor or a TV set via an HDMI cable. For the connection to computer monitors with a DVI port, there are special HDMI adapters. HDMI cables are available in electronics shops at prices comparable to that of the Raspberry Pi. Online shops (like e. g. Amazon) sell these cables for a few dollars incl. shipping charges. Apart from the price, there are no differences for the usage with the Raspberry Pi. Raspbian operating system In all projects we assume that the most current version of the Raspbian operating system is installed on the memory card. For installation, it is best to use the software installer NOOBS that you can get at

9 Raspbian operating system 9 In case the Raspberry Pi does not automatically boot with the graphical LXDE desktop that you need for the programming environment Scratch and for the IDLE Python IDE, you have to call the configuration tool: sudo raspi-config Here you have just to choose the option Desktop Log in as user pi at the graphical desktop under Enable Boot to Desktop. Setting up the automatic login at the graphical desktop When you install Raspbian via NOOBS, the English language and the English keyboard layout and other basic settings are already automatically selected. After a reboot, the graphical LXDE desktop is ready to use. When you use an older Raspbian version or when you are not sure if the most current versions of all components are installed, you can perform a complete update with the following commands in the terminal window: sudo apt-get update sudo apt-get dist-upgrade Now all installed Linux packages are updated to the most current version. This can take several minutes.

10 10 Before we begin... Special Raspbian version for Pi_Scratch In order to program the GPIO interface with Scratch, we show a specifically adapted Raspbian version in the project Scratch and GPIO. Furthermore, you get to know a method to setup Pi_Scratch on standard Raspbian. Nearly like Windows: The LXDE graphical interface Many people are terrified by the notion of using Linux because they think they have to enter cryptic commands at the command prompt as it was necessary 30 years ago in DOS. Far from it! As an open-source operating system, Linux allows developers the flexibility to come up with their own graphical interfaces. Although the core of the operating system still revolves around the command prompt, users are therefore not restricted to one interface. The LXDE desktop on the Raspberry Pi looks very like Windows XP. Raspbian Linux for the Raspberry Pi uses the LXDE interface (Lightweight X11 Desktop Environment) that only requires low system resources. With its start menu and the file manager it looks very like the familiar Windows desktops.

11 Your first Python program 11 Even the typical user login of Linux is done in the background. If you should ever need the credentials: The username is pi and the password is raspberry. Linux login The LXDE icon in the bottom left corner opens the start menu, the adjacent icons open the file manager and the web browser. The start menu is organized in multiple layers, just like the start menu in Windows. You can right-click frequently used programs in order to deposit them on the desktop. Several pre-installed programs, the Midori web browser, the Python development environment and the Pi Store are already there. In theory, you can simply pull the plug, and the Raspberry Pi will turn itself off automatically. However, it is better to shut it down cleanly like a PC. To do this, you double-click on the Shutdown icon on the desktop. Turn off the Raspberry Pi Your first Python program To get the started with programming, the programming language Python is pre-installed on the Raspberry Pi. Python boasts a clear structure that allows for a simple introduction to programming. It is also an ideal language for quickly automating something that you would otherwise do manually. As you do not have to bother with variable declarations, types, classes or complex rules, programming is real fun! On the Raspberry Pi, two Python versions are pre-installed. Unfortunately, the new Version 3.x uses a partially different syntax than the proven version 2.x. Therefore, programs written in one version do not run under the other one. In this book, we use Python version If an older Python version with the version number 2.x is installed on your Raspberry Pi, the examples will still run. Python or 3.3.0? You start Python by means of the IDLE icon on the desktop. A simple-looking input window with a command prompt will appear.

12 12 Before we begin... The input window of the Python shell In this window, you can open existing Python programs, write new ones, and even interactively execute Python commands without writing a program. When you enter: >>> at the prompt, the correct solution will immediately appear: This way, you can use Python as a convenient calculator. But this has nothing to do with programming. Normally, programming classes begin with a HelloWorld program, that shows the sentence HelloWorld on the screen. This can be done so easily in Python that it is not worth a headline of its own. Just enter the following simple line into the Python shell window: >>> print Hello World This first program writes Hello World into the next line on the screen: Hello World in Python (above this you can still see the output of the previous calculation)

13 Your first Python program 13 Here you can also see that the Python shell automatically uses different text colors for clarification: Python commands are orange, strings are green and events are blue. Later on, you will discover even more colors. In order to enter a proper program, you choose File/New Window in the menu of the Python shell. This opens a window where you can enter program code. Python is the ideal language for learning to program, albeit the syntax and the layout rules need getting used to it. To help you in your everyday programming work, the most important syntax elements of Python are described in the form of little cheat sheets. They are based on the Python flashcards by David Whale. If you want to know more about that, look at bit.ly/pythonflashcards. These flashcards do not explain the technological background, but use very short examples to describe the syntax and show you how to do something in Python. Python flashcards An excerpt of the Python flashcards

14 1 Lighting up the first LED The 26-pin header in the corner of the Raspberry Pi lets you directly connect hardware, so that you can e. g. give input via push-buttons or programmatically let the LEDs light up. This header is called GPIO, which is the abbreviation of General Purpose Input Output. 17 of the 26 pins can be arbitrarily programmed as input or output and thus can be used for a plethora of hardware extensions. The other pins are reserved for power supply and other purposes. Figure 1.1: Pin configuration of the GPIO header. The gray lines at the bottom and right side depict the edge of the circuit board. The 5 V pin is thus situated at the outer corner of the Raspberry Pi. Caution: Never connect GPIO pins with each other in order to look what will happen. Always observe the following advice:

15 Some GPIO pins are directly connected to the processor. Short- circuiting them can utterly destroy the Raspberry Pi. If you connect two pins via a switch or an LED, you always have to use a series resistor. Always use Pin 1 for logic signals. It supplies +3.3 V and can take loads up to 50 ma. Pin 6 is the ground wire for logic signals. The other pins labeled with Ground or 3V3, i. e. pins 9, 14, 17, 20 and 25, are intended for future extensions. Currently they can be used as labeled, but you should not do this, so that you can still use your projects on future Raspberry Pi versions. Each of the GPIO pins can be designated as output (e. g. for LEDs) or as input (e. g. for push-buttons). GPIO outputs supply a voltage of +3.3 V in the logic state 1 and a voltage of 0 V in the logic state 0. GPIO inputs supply the logic signal 0 at voltages up to +1.7 V and the logic signal 1 at voltages between +1.7 V and V. Pin 2 provides +5 V as a power supply for external hardware, e. g. an LC display. Here you can take as much current as the mains adapter of the Raspberry Pi can give. This Pin must not be connected to a GPIO input! 1.1 Components in the kit This kit contains several electronic components that you can use to set up the described experiments (and of course, your own experiments, too). Here only a short description of the components is given. The actual experiments will provide you with the practical experience necessary to use them.

16 16 1 Lighting up the first LED 3 x bread board 1 x LC display 1 x header connector (16 pins) 1 x port expander MCP x LED 4 x push-button 4 x 10 kw resistor (brown-black-orange) 4 x 1 kw resistor (brown-black-red) 10 x 220 W resistor (red-red-brown) 1 x 560 W resistor (green-blue-brown) 6 x 22 MW resistor (red-red-blue) 1 x 15 kw potentiometer 12 x connection cables (breadboard/raspberry Pi) Jumper wire 2 x cable with alligator clips Breadboards For the quick setup of electronic circuits (without the need to solder), the kit contains three breadboards. Electronic components can be inserted directly into a grid of holes with standard distances. In these breadboards, the other longitudinal lines with contacts (X and Y) are connected to each other. Figure 1.2: The breadboard in the kit; some connections are indicated by way of example.

17 1.1 Components in the kit 17 These contact lines are often used as positive or negative terminals for the power supply of the circuits. In the other contact lines, five contacts at a time (A to E and F to J) are connected crossways, with a gap in the middle of the breadboard. Thus you can insert bigger components like the port expander in the middle and connect it at the external sides Connection cablesl The colored connection cables have a thin wire connector at one side that can be inserted into the breadboard. The other side has a female connector that fits onto a GPIO pin of the Raspberry Pi. Additionally the kit contains some jumper wire. With this you create small wire bridges to connect the contact lines on the breadboard. Use a wire cutter to cut the wire as required for the experiment at hand. It is recommended to cut the wire diagonally so that the end becomes wedge-shaped. This way, you can insert the wire more easily into the breadboard. Remove the insulation at both ends for about half a centimeter Color-coding of resistors In digital electronics, resistors are mostly used to limit the current at the ports of a microcontroller and as series resistors for LEDs. The measuring unit for resistance is called Ohm (W) Ohm equal 1 kiloohm (kw), and 1000 kw equal one megaohm (MW). Resistors are usually labeled by colored rings that indicate the resistance value. Most resistors have four of these rings. The first two give numbers, the third one is a multiplier, and the fourth specifies the tolerance. In most cases, this tolerance ring is silver or golden. These colors are not used in the first rings, so that the direction of reading is clear. In digital electronics, the tolerance values virtually bear no significance.

18 18 1 Lighting up the first LED Color Ring 1 (tens digit) Resistance value in Ohm Ring 2 (units digits) Ring 3 (multiplier) Ring 4 (tolerance) Silver 10 2 = 0,01 ±10 % Gold 10 1 = 0,1 ±5 % Black = 1 Brown = 10 ±1 % Red = 100 ±2 % Orange = Yellow = Green = ±0,5 % Blue = ±0,25 % Purple = ±0,1 % Gray = ±0,05 % White = Figure 1.3: Meaning of the colored rings on resistors Resistance value Ring 1 (tens digit) The kit contains resistors with five different resistance values. Ring 2 (units digits) Ring 3 (multiplier) Ring 4 (tolerance) Usage 220 W Red Red Brown Gold Series resistor for LEDs 560 W Green Blue Brown Gold 1 kw Brown Black Red Gold 10 kw Brown Black Orange Gold Series resistor for the power supply of the LC display Protective resistor for GPIO inputs Pull-down resistor for GPIO inputs 22 MW Red Red Blue Gold Resistor for Pikey Pikey Figure 1.4: Color codes of the resistors in the kit

19 1.1 Components in the kit 19 Observe the colors carfully, in particular for the 1 kw and 10 kw resistors and the 220 W and 22 MW resistors, respectively. Otherwise, they can be confused easily LEDs In order to create light signals or light effects, you can connect LEDs (Light Emitting Diodes) to the GPIO pins. In doing so you have to insert a 220 W series resistor (red-red-brown) between the GPIO pin and the anode of the LED in order to limit the electrical current und thus avoid blowing the LED. Additionally, the series resistor also protects the GPIO output of the Raspberry Pi, as the LED provides nearly no resistance in flow direction and the GPIO port can thus easily be overloaded when connected to ground. Connect the cathode of the LED with the ground wire at pin 6 of the Raspberry Pi. The two connecting leads of the LED are of different length. The longer lead is the positive pole or anode, the shorter one is the cathode. You can remember this easily when you imagine that the plus sign has one more stroke than the minus sign, and likewise the lead is a little longer. Furthermore, most LEDs are flattened at the negative side, resembling the shape of a minus sign. In which direction do you have to connect the LED? LC-Display The kit contains a two-line LC display. Like most displays of this type, it is compatible to the de facto standard HD This is the denomination of a display controller that can show up to four lines of text without requiring the user to control the individual pixels.

20 20 1 Lighting up the first LED Figure 1.5: Two-line LC display on a breadboard, connected to a Raspberry Pi The display features a 16-pin connection header. Solder in the shorter pins of the included header connector so that the longer pins are freely accessible on the bottom side. With these pins the display is later connected to the breadboard. Figure 1.6: Display with soldered header connector Simple soldering done correctly When you tinker with hardware for the Raspberry Pi, you have to solder components once in a while. This is no problem for the seasoned user, and not really a problem for beginners, too, as long as they consider a few important tips. On mightyohm.com/soldercomic you can find the entertaining comic strips Soldering is Easy that provides basic knowledge on soldering.

21 1.2 GPIO and Python GPIO and Python In order to use the GPIO ports in Python, you have to install the Python GPIO library. In the current Raspbian versions it is pre-installed by default. As is usual for devices in Linux, the GPIO ports are embedded in the directory structure like files. Root privileges are required to access these files. Launch the Python shell with root privileges via an LXTerminal: sudo idle Launch Python with GPIO support without Terminal When you use Python and the GPIO pins a lot, you do not want to call LXTerminal in order to launch IDLE. There is a simpler way: Place an icon on your desktop that launches the Python IDE with superuser rights. Copy the pre-installed IDLE desktop icon like this: Right-click the IDLE icon on the desktop, and in the context menu, choose Copy. Figure 1.7: Copy the IDLE desktop icon

22 22 1 Lighting up the first LED Right-click the desktop and in the context menu choose Paste. As there is already a desktop shortcut with the same name, the following message is displayed: Figure 1.8: The message that appears when duplicating a desktop shortcut Change the name of the copy from idle.desktop to idle_gpio. desktop. However, the icon on the desktops remains the same and shows still the name IDLE. Right-click the copied desktop icon and in the context menu, choose Leafpad. In Linux, desktop shortcuts are simple text files that can be edited in a text editor. Figure 1.9: The desktop shortcut in the Leadpad editor

23 1.3 Turning LEDs on and off with Python 23 Make the changes shown in the images: Change the field Name to IDLE GPIO. This is the name that is shown on screen. In the field Exec, prepend the actual command with sudo. Close the editor and save the file. By double-clicking the new desktop icon, you execute the IDLE Python IDE with superuser rights. Now you can use the GPIO functions without having to call Python from LXTerminal. 1.3 Turning LEDs on and off with Python As shown in the image, connect an LED via a 220 W resistor (redred-brown) to GPIO port 25 (pin 22), and connect the negative pole of the LED via a ground line of the breadboard with the ground wire of the Raspberry Pi (pin 6). Required components: 1 x breadboard, 1 x LED, 1 x 220 W resistor (red-red-brown), 2 x connection cable

24 24 1 Lighting up the first LED Figure 1.10: An LED at GPIO port 25 The program led.py makes the LED flash ten times: #!/usr/bin/python import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.OUT) for i in range(10): GPIO.output(25, 1) time.sleep(0.2) GPIO.output(25, 0) time.sleep(0.2) GPIO.cleanup()

25 1.3 Turning LEDs on and off with Python How it works The example demonstrates the basic functions of the library RPi.GPIO. #!/usr/bin/python This line can be found at the beginning of nearly every Python script. Its purpose is to identify the file as such a script. In this case it is not absolutely necessary, but you should get into the habit to use it always as the first line in a Python script. import RPi.GPIO as GPIO The library RPi.GPIO has to be imported in every Python program in which she is used. The notation used here makes it possible to access every function in the library by the prefix GPIO. import time The Python library time is not related to GPIO programming, but contains functions for date and time calculations. Among these is the function time.sleep() that lets you implement waiting times in an easy way. GPIO.setmode(GPIO.BCM) At the beginning of a program you have to define the labeling of the GPIO ports. Usually you use the standard numbering system BCM. The library RPi.GPIO supports two different methods for labeling the ports. In the BCM mode, the known GPIO port numbers are applied that are also used at the command line or in shell scripts. In the alternative BOARD mode, the pin numbers 1 to 26 as depicted on the Raspberry Pi board are used as labels. Numbering the GPIO ports GPIO.setup(25, GPIO.OUT) The function GPIO.setup() initializes a GPIO port as output or input. The first parameter specifies the port according to the BCM or board mode by its GPIO or pin number. The second parameter can be GPIO.OUT for an output or GPIO.IN for an input.

26 26 1 Lighting up the first LED for i in range(10): This starts a loop that will be executed ten times. for loops like this are known in many programming languages. The counter i iterates through the integer numbers from 0 upwards. The loop is terminated when the value given by range is reached. In each pass of the loop, the indented program code is repeated. GPIO.output(25, 1) At port 25, the value 1 is output. The LED connected to this port lights up. Instead of 1, you can also output the pre-defined values True or GPIO.HIGH. Indentations are important in Python In most programming languages loops or decisions are indented in order to enhance the readability of the code. In Python, these indentations are not only used for clarification, but are required by the program logic. You do not need special symbols in order to terminate loops or decisions. time.sleep(0.2) This function originates from the time library that was imported at the beginning of the program. It effects a waiting time of 0.2 s. After that, the program continues. GPIO.output(25, 0) To turn off the LED, you output the value 0 or False or GPIO.LOW at the GPIO port. time.sleep(0.2) With the LED turned off, the program again waits for 0.2 s. After that the loop ends, because this is the last indented line. Now the loop begins again, and the LED is turned on for a short time. GPIO.cleanup()

27 1.3 Turning LEDs on and off with Python 27 At the end of the program, all GPIO ports have to be reset. This is done by this line for all initialized GPIO ports at once. Ports that were initialized by other programs remain unaffected. In this way the execution of other programs that may run in parallel is not impaired. Python programs do not need any special instruction to terminate. They simply end after the last command or after a loop that is not longer executed and not followed by further commands. Warnings appear, when you want to use a GPIO port that is not reset, but maybe still open because of a program running in parallel or an aborted program. These warnings do not interrupt the program flow. They are very useful to find errors, but in the final program, they may confuse the user. The GPIO library provides the function GPIO. setwarnings(false) to suppress these warnings. Catching GPIO warnings

28 2 Your first Scratch program Scratch is an intuitive programming environment that allows children and beginners to quickly implement their ideas without bothering with programming theory up front. Scratch is a project of the Lifelong Kindergarten Group at the MIT Media Lab. It is pre-installed on the Raspberry Pi. As it is apt for the main target audience of children and adolescents, Scratch is particularly suitable for interactive animations and games. The graphical interface provides elements, so that you do not have to be concerned about the user interface of your own program. Scratch scripts are not written as text, but put together from pre-fabricated elements by drag & drop. Launch Scratch via the pre-installed desktop icon on the Raspbian desktop. Scratch always launches with a four-part program window.

29 Figure 2.1: Launching Scratch 1. In the left pane, you see the block palette with all elements that can be combined to a Scratch script. As only pre-defined blocks can be used, it is not possible to make any syntax errors. These types of errors are very frustrating for beginners in other programming languages. 2. In the beginning, the middle pane is empty. Here you will later build the script. 3. In the top right corner you see the so called stage. This is the interface where the script will run. The cat that is shown there represents an object that can be animated by Scratch. 4. The sprite window in the bottom right corner shows the objects ( sprites ) that are used in the script. Here you can design your own objects later on.

30 30 2 Your first Scratch program In a first and very simple script we want to make the cat move once in a circle and simultaneously change its color. 1. Click the cat in the bottom right sprite window. It is now highlighted and represented as Sprite1 above the script window. All commands in the script window now refer to this object. 2. At the top of the block palette, click the yellow Control category. This shows the blocks that can be used to control the program flow. 3. Drag the block shown here from the block palette into the script window. In the top right corner of the Scratch stage, you can see a green flag symbol. It is usually used to start a program. The element shown here causes the execution of the following script elements when the user clicks the green flag. 4. The circular movement is composed of single forward movements and turns. This is repeated until the cat has covered a complete circle. Drag the Repeat block shown above into the script window and attach it underneath the existing element. 5. After each forward movement, the cat shall turn for 15. This way, it turns complete around in 24 iterations. Click the white number field of the Repeat block and change the default value to To execute a circular movement, the cat has to move a fixed number of steps forward, turn for 15, move another number of steps etc. Click the blue Motion icon at the top of the block palette and drag the block shown here into the script window. Attach it inside the loop and change the step count to Drag the block for a counterclockwise turn into the script window. Place it above the existing blocks so that it clicks into place behind the movement block inside the loop.

31 1.3 Turning LEDs on and off with Python Now the script should look like the picture shown on the right. Test to see if works as expected. Click on the green flag above the stage. The cat should now walk in a circle. 9. Now we only have to add the color change. At the top of the block palette, click on the purple Looks icon. Now the palette shows blocks to change the look of the active sprite. Drag the block shown above into the script window and place it inside the loop after the Turn block. 10. Run the script again. Now the cat cycles through the different colors while it walks in a circle. After 24 repetition, the cat is back again at the initial position and with the original color. Figure 2.2: Walking, turning and changing color

32 3 GPIO and Scratch Scratch seems not to have GPIO support out of the box. To use the GPIO interface, you have to include external function libraries and to adjust some settings. For the following experiments we use the Pi_Scratch library ( that offers extensive support for different hardware components at the GPIO port. 3.1 Using a Pi_Scratch image The developers of Pi_Scratch provide a Raspbian image that has Pi_Scratch pre-installed. This is the easiest way that allows the immediate utilization. The manual installation of Pi_Scratch on an existing Raspbian is a much more complex task. 1. The Raspberry Pi MakerKit contains a DVD with a ready-made operating system image that includes Pi_Scratch The programs used in the MakerKit are also preinstalled in this operating system. Therefore it is not necessary for you to download Pi_Scratch. 2. Ideally you use a brand-new memory card with a capacity of at least 4 GB, because it is optimally pre-formatted by the manufacturer. Memory cards that have been used in other devices should be reformatted before you use them in the Raspberry Pi. In theory you could do this with the formatting features of Windows, but the SDFormatter software by SD Association ( downloads/formatter_4) is significantly better as it formats the memory cards for optimum performance. If the memory card

33 contains partitions from a previous operating system installation for the Raspberry Pi, Windows will not show the full size. In this case you have to turn on the formatting option Format Size Adjustment that repartitions the memory card. Figure 3.1: The SDFormatter tool in Windows in action 3. Use the USB Image Tool included on the DVD to transfer the i_scratch_v276b_en_makerkit.img image file to a memory P card. When you insert the DVD, the appropriate image is loaded directly into the USB Image Tool. 4. Now you boot the Raspberry Pi with the memory card. After launching the LXDE desktop, Scratch is started automatically, and a Terminal windows with messages about the Pi_Scratch library appears.

34 34 3 GPIO and Scratch Figure 3.2: Scratch with GPIO and network sensor support 5. The Raspberry Pi has no internal clock, but receives its time settings from a time server in the Internet. Thus you have to specify your time zone. Open a new LXTerminal window and launch the configuration tool. In this version, you are automatically logged in as root, so that you do not specify sudo. raspi-config Use the cursor keys to choose the menu item Internationalisation Options and then Change Timezone. Choose the correct time zone for the Raspberry Pi to use. 6. Exit the configuration tool and restart the Raspberry PI.

35 3.2 Installing Pi_Scratch in Raspbian Installing Pi_Scratch in Raspbian Instead of using a complete new Raspbian image and a new memory card, you can install Pi_Scratch in an existing Raspbian installation. Prior to that you have to activate the so called mesh mode in Scratch. 1. Launch Scratch as root in an LXTerminal. sudo scratch 2. Press and hold (Shift) and click the upper part of the letter R in the Scratch logo in the top left corner. Now a menu appears that is normally hidden from the user. Deselect the menu item turn fill screen off. Figure 3.3: Turn fill screen off 3. A white border appears at the right side and below the Scratch window. When you click on it, a menu is shown. Figure 3.4: The World menu in Scratch

36 36 3 GPIO and Scratch 4. Choose open in this menu and then browser in the next menu. With the system browser, you get into the depth of the Scratch configuration. 5. In the left column, click Scratch-UI-Panes. Now a new list appears in the next column. Choose ScratchFrameMorph, then menu/ button actions and in the last column, addservercommandto. Figure 3.5: The Scratch system browser 6. Click the lower pane and change the word true in the second line to false. Click with the mouse wheel to open a context menu. Choose accept. Figure 3.6: At t2, change True to false

37 3.2 Installing Pi_Scratch in Raspbian Before your changes are finally accepted, a window appears where you have to enter your initials or some other characters. Then the changes are saved. 8. Close the system browser by clicking on the X in the top left corner of the green windows. 9. Press and hold (Shift) and click again the upper part of the letter R in the Scratch logo. Choose turn fill screen on. The white border around the Scratch windows is hidden. 10. Call the same menu again and choose save image for end-user in order to save the settings for the mesh mode. Otherwise you would have to setup this mode again each time you start Scratch. Exit Scratch. 11. Next you have to activate I2C in the operating system. Open /etc/modprobe.d/raspi-blacklist.conf in the Nano editor: sudo nano /etc/modprobe.d/raspi-blacklist.conf 12. Place a commentary character in front of the two blacklist lines as shown in the figure. This removes the respective drivers from the blacklist so that they can be loaded normally. Figure 3.7: Editing raspi-blacklist.conf

38 38 3 GPIO and Scratch 13. Edit /etc/modules and enter the required kernel modules as shown in the figure. sudo nano /etc/modules Figure 3.8: Editing /etc/modules 14. Reboot the Raspberry Pi so that the modules are loaded automatically. 15. Download the Pi_Scratch library in an LXTerminal und unzip the archive. sudo wget tar xf Pi_Scratch_v268.tar cd Pi_Scratch_v268/Installer 16. Start the actual installation script. It downloads several further components. This can take some minutes. sudo python Install.py

39 3.2 Installing Pi_Scratch in Raspbian During installation you see several questions. In each case answer (Y). At the end of the installation you are requested to press (Enter) in order to reboot the Raspberry Pi. 18. Sometimes the reboot does not work, and the Raspberry Pi hangs with a black screen. In this case just cut the power supply and reboot the Raspberry Pi in this way. 19. Launch Scratch, but not via the desktop icon, but in an LXTerminal with root privileges. sudo scratch 20. Press and hold (Shift) and click the Share menu. Choose the menu item Host Mesh. The IP address is shown. If the menu item is not shown, choose Stop Hosting Mesh. Then call the menu again while you hold down (Shift). Figure 3.9: The IP address shows that Host Mesh is activated 21. Launch Pi_Scratch again in another LXterminal. cd ~/Pi_Scratch_v268 sudo python Pi_Scratch_v268.py --debug

40 40 3 GPIO and Scratch Figure 3.10: Pi_Scratch shows the loaded modules 22. Now you can use Pi_Scratch. As you do not want to go to the effort of manually restarting Pi Scratch every time you reboot Raspbian, you now have to start the script for automatic configuration, login and start. This script automatically starts Scratch when the Raspberry Pi boots. cd ~/Pi_Scratch_v268/Installer sudo python Install-With-Scratch.py 3.3 Flashing LEDs in Scratch Pi_Scratch comes with a simple example script that shows the basic GPIO control in Scratch by alternatively lighting up two LEDs. Instead of tinkering with the script yourself, you simply load the g17-g27demo script in the provided examples. Build the circuit shown on a breadboard as shown in the figure. To control the LEDs we use two GPIO ports and a common ground wire. Required components: 1 x breadboard, 1 x red LED, 1 x yellow LED, 2 x 220 W resistor (red-red-brown), 3 x connection cable

41 3.3 Flashing LEDs in Scratch 41 Figure 3.11: Lighting up two LEDs with Scratch Start the script by clicking on the green flag. The LEDs light up alternatively How it works For most of the GPIO functions, Pi_Scratch uses the Broadcast control block. After starting the script by clicking on the green flag, the GPIO ports 17 and 27 are defined as outputs.

42 42 3 GPIO and Scratch This block contains a field where you can enter your own text. When you click on it, a list of the last entries is shown. Click New to open the input field for new text. Text that had been used before can easily be chosen from the list. After that, the script waits for one second, because the initialization of the GPIO ports can take a moment. Then the infinite loop begins. Loops like this are never terminated by the script. They are automatically ended when the user clicks on the red Stop sign in the top right corner. In Scratch it is not required to close the used GPIO ports explicitly. First thing in the loop is to turn on GPIO port 17 and to turn off GPIO port 27.

43 3.3 Flashing LEDs in Scratch 43 After that, the script waits for two seconds. Then it turns off GPIO port 17 and turns on GPIO port 27. After a waiting period of another two seconds, the loop begins again. In this way the two LEDs flash alternatively. The Terminal window of Pi_Scratch continually shows the GPIO outputs. The GPIO port 27 that is used in this example included with Pi_Scratch is called 21 on older Raspberry Pi boards. In order to avoid problems we do not use this port in our own examples. Here it is used by the developer of the Pi_Scratch library. If one of LEDs does not light up, change g27 in the three Broadcast blocks of the script to g21. GPIO port 27

44 4 Pedestrian light At first it may be exciting to light up single LEDs, but you do not really need a computer for that. However, a traffic light with its typical light cycle from green to yellow to red and then via a combination of red and yellow back to green can show further programming techniques in Python. The next experiment simulates a simple traffic light circuit with pedestrian light on a breadboard with five LEDs. During the red phase of the traffic light, the pedestrian light is green. Figure 4.1: The traffic light on the breadboard connected to the Raspberry Pi Build the following experiment with five LEDs, series resistors and a push-button on the breadboard as shown. Required components: 1 x breadboard, 2 x red LED, 1 x yellow LED, 2 x green LED, 5 x 220 W resistor (red-red-brown), 1 x pushbutton, 1 x 1 kw resistor (brown-black-red), 1 x 10 kw resistor (brown-black-orange), 8 x connection cable, 1 x short wire bridge

45 Figure 4.2: Traffic light with pedestrian light 4.1 Push-button at the GPIO port GPIO can not only output data, e. g. via LEDs, but also be used for data input. To this end they have to be defined in the program as inputs. As input device we use a push-button that is directly attached to the breadboard. The button has four connection leads. The opposite leads (separated by the bigger distance) are connected to each other. As long as the button is pressed, all four leads are connected with each other. Unlike a normal button, a push-button does not stay in the pressed state. When you release it, the connections are immediately separated. A +3.3 V signal at a GPIO port defined as input is evaluated l ogically as True or 1. In theory you could connect a GPIO port via a push-button with the +3.3 V connection of the Raspberry Pi. But you must never do this, as this would overload the GPIO port! Always

46 46 4 Pedestrian light place a 1 kw series resistor between the GPIO input and the +3.3 V port. In this way you avoid that excessive current reaches the GPIO port and thus the processor. Figure 4.3: Push-button with protective resistor at a GPIO input This simple circuit may work in most cases, but the GPIO port would not have a defined state when the button is opened. When a program queries this port, the result may be a random value. In order to avoid this, you connect a very large resistor usually 10 kw to ground. This so called pull-down resistor pulls the state of the GPIO port down to 0 V when the button is opened. Due to the high resistance value, there is no risk of short-circuiting while the button is pressed. In this state, the +3.3 V port and the ground wire are directly connected by this resistor. Figure 4.4: Push-button with protective resistor and pull-down resistor at a GPIO port The lower contact bar of the push-button as seen in the image of the completed circuit is connected with the +3.3 V wire of the Raspberry Pi (pin 1) via the positive bar of the breadboard. For clarity, we use a short wire bridge to connect the push-button with the positive bar. Alternatively you could also use a connection cable to directly connect the lower contact leads of the push-button with pin 1 of the Raspberry Pi.

47 4.2 Pedestrian light with Python 47 The upper contact bar of the push-button is connected to GPIO port 7 via a 1 kw protective resistor and to 0 V ground via a 10 kw pull-down resistor. 4.2 Pedestrian light with Python In idle state, the traffic light should be green and the pedestrian light red. When you press the push-button, the traffic light switches to yellow and then to red. Not before this the pedestrian light switches to green. After a green phase of two seconds the pedestrian light switches back to red. Now the traffic light cycle to red-yellow and then to green begins. After that the program remains in this state until the user presses the button again. The program ampel.py controls the traffic light system. #!/usr/bin/python import RPi.GPIO as GPIO import time rot = 0 gelb = 1 gruen = 2 f_rot = 3 f_gru = 4 taste = 5 Ampel=[18,23,24,25,8,7] GPIO.setmode(GPIO.BCM) GPIO.setup(Ampel[rot], GPIO.OUT, initial=0) GPIO.setup(Ampel[gelb], GPIO.OUT, initial=0) GPIO.setup(Ampel[gruen], GPIO.OUT, initial=1) GPIO.setup(Ampel[f_rot], GPIO.OUT, initial=1) GPIO.setup(Ampel[f_gru], GPIO.OUT, initial=0) GPIO.setup(Ampel[taste], GPIO.IN) print ( Press the button to turn on the pedestrian light. Ctrl+C terminates the program. ) try: while True: if GPIO.input(Ampel[taste])==1: GPIO.output(Ampel[gruen],0) GPIO.output(Ampel[gelb],1) time.sleep(0.6) GPIO.output(Ampel[gelb],0)

48 48 4 Pedestrian light GPIO.output(Ampel[rot],1) time.sleep(0.6) GPIO.output(Ampel[f_rot],0) GPIO.output(Ampel[f_gru],1) time.sleep(2) GPIO.output(Ampel[f_gru],0) GPIO.output(Ampel[f_rot],1) time.sleep(0.6) GPIO.output(Ampel[gelb],1) time.sleep(0.6) GPIO.output(Ampel[rot],0) GPIO.output(Ampel[gelb],0) GPIO.output(Ampel[gruen],1) time.sleep(2) except KeyboardInterrupt: GPIO.cleanup() How it works You are already familiar with the first lines that define the file as a Python script and import the libraries RPi.GPIO and time to control the GPIO ports and to insert waiting periods, respectively. rot = 0 gelb = 1 gruen = 2 f_rot = 3 f_gru = 4 taste = 5 In these lines the variables rot, gelb and gruen for the three traffic light LEDs, f_rot and f_gru for the pedestrian light LEDs and taste for the push-button are defined. This way you do not have to remember numbers for the GPIO ports in the program, but can refer to the LEDs simply by their color. Ampel=[18,23,24,25,8,7] To control the LEDs we set up a list that contains all GPIO numbers in the order in which they were defined. The GPIO ports are only mentioned in this location of the program. Thus you can easily change the program when you want to use other GPIO ports. Subsequently the numbering of the GPIO ports is set to BCM.

49 4.2 Pedestrian light with Python 49 GPIO.setmode(GPIO.BCM) GPIO.setup(Ampel[rot], GPIO.OUT, initial=0) GPIO.setup(Ampel[gelb], GPIO.OUT, initial=0) GPIO.setup(Ampel[gruen], GPIO.OUT, initial=1) GPIO.setup(Ampel[f_rot], GPIO.OUT, initial=1) GPIO.setup(Ampel[f_gru], GPIO.OUT, initial=0) GPIO.setup(Ampel[taste], GPIO.IN) The used GPIO ports are defined as outputs one by one. For this we do not use the GPIO port numbers, but the list defined previously. In such a list the individual entries are indexed by numbers, beginning with 0. The variables rot, gelb and gruen take the list indexes 0, 1 and 2. In this way we can address the used GPIO ports by color: Ampel[rot] refers to GPIO port 18 with the red LED. Ampel[gelb] refers to GPIO port 23 with the yellow LED. Ampel[gruen] refers to GPIO port 24 with the green LED. Ampel[f_rot] refers to GPIO port 25 with the red pedestrian light LED. Ampel[f_gru] refers to GPIO port 8 with the green pedestrian light LED. Ampel[taste] refers to GPIO port 7 with the push-button. The GPIO port of the push-button is defined as input. This definition is also done with GPIO.setup, but this time we use the parameter GPIO.IN. The GPIO.setup statement can contain the optional parameter initial, that assigns a logical state to the GPIO port while initializing. With this instruction we turn on the green traffic light LED and the red pedestrian light LED right from the start. The other LEDs are turned off at the beginning of the program. print ( Press the button to turn on the pedestrian light. Ctrl+C terminates the program. ) This line shows a short operating instruction on the screen. It says that the user has to press the push-button. The program runs automatically. To quit it, the user has to press (Ctrl) + (C).

50 50 4 Pedestrian light To determine whether the user has stopped the program with (Ctrl) + (C), we use a try...except query. At first, the program code under try is executed normally. If a system exception occurs this may be an error or the keyboard shortcut (Ctrl) + (C), the execution will be aborted and the except statement at the end will be run. except KeyboardInterrupt: GPIO.cleanup() By pressing this keyboard shortcut, a KeyboardInterrupt is triggered and the loop is automatically aborted. The last line closes the used GPIO ports and thus turns off all LEDs. After that the program quits. Due to the controlled closing of the GPIO ports, no system warnings or abort messages are shown that would only confuse the user. The actual traffic light cycle runs in an infinite loop: while true : Infinite loops like this always require an abort criterion, because otherwise, the program would never quit. if GPIO.input(Ampel[taste])==1: This loop contains a query. The following statements are only executed when the GPIO port with the push-button has the state true, i. e. when the user presses the button. Until then the traffic light remains in its green phase. GPIO.output(Ampel[gruen],0) GPIO.output(Ampel[gelb],1) time.sleep(0.6) Now the green LED is turned off and the yellow one is turned on solely for 0.6 s.

51 4.2 Pedestrian light with Python 51 GPIO.output(Ampel[gelb],0) GPIO.output(Ampel[rot],1) time.sleep(0.6) Now the yellow LED is turned off and the red one is turned on. Again, the program waits for 0.6 s. GPIO.output(Ampel[f_rot],0) GPIO.output(Ampel[f_gru],1) time.sleep(2) Only now the pedestrian light switches from red to green. The green light lasts for two seconds. Then the pedestrian light switches back to red, and the traffic light switches to red-yellow and then to green, each time with a delay of 0.6 s. At the end of the loop, the traffic light is again green, while the pedestrian light shows the red light. After a waiting period of 2 s, the loop begins again with the green phase of the traffic light. This delay at the end of the loop is necessary to prevent a drop out of the green phase when the user presses the push-button immediately after the yellow phase. Of course you can adjust all the time periods at your discretion. In real life, the traffic light cycles depend on the dimensions of the crossing and the volume of traffic. The yellow phase and the red-yellow phase usually last for 2 s.

52 5 Pedestrian light in Scratch You can program the same pedestrian light in Scratch. Due to the simpler initialization in Pi_Scratch, the script is easier to understand. In order to make room for the script, you can enlarge the script pane and reduce the stage by means of the icons in the top right corner of the Scratch window. Figure 5.1: The Scratch script for the pedestrian light in a larger script window

53 5.1 How it works The first thing that happens when the user clicks the green flag is that the six used GPIO pins are initialized. Just as in the Python version of the pedestrian light we use the ports 18, 23, 24, 25 und 8 as outputs for the LEDs and port 7 as input for the push-button. The script pauses for a second so that the GPIO ports can be initialized. After that, the green traffic light LED and the red pedestrian light LED are turned on. The other three LEDs are turned off. Actually it is not required to turn off any lights at the beginning. This is done here in order to start the script with a defined state. Similarly to the Python script, we now start the infinite loop that waits for the user to press the push-button and then triggers the traffic light cycle. In this place we query the state of the push-button. For this we use the If block that works like an if statement in Python.

54 54 5 Pedestrian light in Scratch In this block we insert blocks that will be executed when the condition is true. Inside the If block there is an oblong field with pointed ends where you enter the condition. Here you have to insert a block from the green Operators category. Choose the block with the equal sign and drag it to the placeholder field on the If block. This operator evaluates to true, when the values on both sides of the equal sign are equal. In this case the value of GPIO pin 7 shall equal 1. As in Python, a depressed button provides the value 1. For querying the GPIO inputs we use the Sensor Value block in the blue Sensing category. Drag the block to the left placeholder field in the green Equals block. In the dropdown field of the blue block, choose sensor GPIO-7. In addition to some predefined sensors, all GPIO pins that are defined as inputs are available. Enter 1 in the right field of the green Equals block. The GPIO input does not appear Should the GPIO input not appear in the dropdown list after a few seconds, drag a Broadcast block into the script window, but do not attach it to the existing script. Enter the text update and click the block to execute it manually. After that, the GPIO input will appear in the list of the Sensor Value block. Now the condition in the If block looks like this. When the condition is true, i. e. when the user has pressed the push-button, the traffic light cycle commences. In the first step the green LED of the traffic light is turned off and the yellow LED is turned on. After that, the script waits for 0.6 s.

55 5.1 How it works 55 In order to switch the GPIO ports we use again a Broadcast block. After the yellow phase, the traffic light switches to red. To this end we turn off the yellow LED and turn on the red one. This phase also lasts for 0.6 s. In the next step, the pedestrian light is switched to green, while the traffic light still shows the red light. The green LED of the pedestrian light is turned on, the red one is turned off. The green phase of the pedestrian light lasts for 2 s. After the green phase of the pedestrian light, its red LED is turned on again, while the green one is turned off. This takes 0.6 s. At this stage the red LED of the traffic light is already lit. For the subsequent red-yellow phase we have just to turn on the yellow LED. After the red-yellow phase, the red and the yellow LEDs of the traffic light have to be turned off, while the green one has to be turned on. After the beginning of the green phase, we wait for 2 s, before the command sequence inside the If statement is finished. By this we prevent a shortage of the green phase when the user presses the push-button immediately after the yellow phase. After that we send an update command to query all sensors again. In this way the script determines the state of the push-button. Thereafter the infinite loop begins again and calls the traffic light cycle depending on the detected sensor value. As long as the push-button is not depressed, the infinite loop sends one update statement after the other in order to determine if the user presses the button. Like all other GPIO messages, these update statements are shown in the text window of Pi_Scratch.

56 56 5 Pedestrian light in Scratch 5.2 The cat walks according to the pedestrian lights In this extension the Scratch mascot, the cat, will walk in accordance with the pedestrian lights. This demonstrates that you can freely combine classic Scratch functions and Pi_Scratch in a single script. To this end the script ampel_katze contains some additional blocks. The control system of the pedestrian light works as in the previous version of the script. However, during the green phase of the pedestrian light there are some new blocks that move the cat. When the pedestrian light switches to green, the cat shall walk to the opposite side of the street. There it should turn for 180, so that it can walk back during the next green phase. Instead of walking (or rather, jumping) for 200 steps at once, the motion is split into ten phases of 20 steps each, after which the cats waits for 0.1 s at a time. This provides for a more fluid motion.

57 5.2 The cat walks according to the pedestrian lights 57 After ten repetitions, the cat has to turn for 180. Above the script pane, activate the double-arrow icon next to the cat in order to avoid that the cat ends up on its head after turning. Figure 5.2: This icon freezes the vertical orientation of the cat instead of rotating it in every direction. When you start the script and press the push-button, it walks to the right during the first green phase of the pedestrian light and turns around. When you press the button again, it walks back to the initial position on the left. We only use relative motion in this script, so that we do not have to differentiate between walking to the right and walking to the left.

58 6 LED DICE We all know the typical dice that show one to six dots. Much cooler, however, are electronically controlled dice where a random number of LEDs light up when you press a button. It gets even better when the six LED do not light up in a straight line, but in the typical dice pattern. In order to emulate this rectangular grid, we have to use seven LEDs. Figure 6.1: A die made of seven LEDs connected to the Raspberry Pi For the following experiment, insert seven LEDs with series resistors and a push-button in the breadboard as shown in the figure. To control the LEDs we only need four GPIO pins instead of seven, because the LEDs are used in pairs to represent even numbers of dots.

59 Required components: 1 x breadboard, 2 x red LED, 2 x yellow LED, 2 x blue LED, 1 x green LED, 7 x 220 W resistor (red-red-brown), 1 x push-button, 1 x 1 kw resistor (brown-black-red), 1 x 10 kw resistor (brown-black-orange), 7 x connection cables, 5 x wire bridges (different lengths) Figure 6.2: LED die with push-button on the breadboard

60 60 6 LED DICE 6.1 Rolling the dice in Scratch The Scratch script ledwuerfel is similar to the pedestrian light script in that pressing the push-button lights up several LEDs. In order to create, save and query a random number we use new types of blocks. Figure 6.3: The Scratch script for the LED die How it works The first thing that happens when the user clicks the green flag is that the five GPIO ports are initialized. Here we use the ports 18, 23, 24 and 25 as LED outputs and port 7 as push-button input. The script waits for a second to let the initialization of the GPIO ports happen.

61 6.1 Rolling the dice in Scratch 61 Subsequently the infinite loop begins and waits for the user to press the push-button. As in the pedestrian light program, this is done by querying GPIO port 7. When this port has the value 1, we know that the push-button is depressed. In this case the statements inside the If block are executed. At first the four GPIO ports for the LEDs are turned off. At the beginning, all LEDs are turned off. The later result of rolling the dice, however, is shown until the user presses the button again. After that, a random number between 1 and 6 is created and saved in the variable w. In Scratch, variables have to be created first. Click the orange Variables icon on top of the block palette and then New Variable. Name the variable (in this case w). The block palette shows several blocks for working with variables. When you activate the switch on the left-hand side of the variable w, it is automatically shown on the stage in a small orange field. Thus you can always see the thrown number and can check if the LEDs work. Drag the Set... To block into the script. As long as only one variable is defined, it is automatically selected in the block. When you have several variables, you have to choose the right one in the dropdown list. Drag the Pick Random... To block from the Operators category into the number field of the orange Set... To block. Enter 1 and 6, respectively, in the number fields. This is the range for the random number.

62 62 6 LED DICE After rolling the dice, we have six If blocks for the possible values. Each of these blocks turns on the respective LEDs when a special number is thrown. Drag a green Equals block into the condition field of the If block. Then drag the block for the variable w from the Variables category of the block palette into the first field of the Equals operator. Enter 1 in the second field. Now the block inside the bracket is executed when the result of rolling the dice was 1. Inside the If block you place a Broadcast block where you specify the GPIO ports for the LEDs that have to light up for this result. You can duplicate the If block by right-clicking it. In this way you only have to change the result and the respective LEDs. Independent of the result, the program always waits for half a second after the push-button has been pressed. Otherwise key-bouncing might undesirably trigger two subsequent processes of rolling the dice. After that all sensors are queried again by an update command. In this way the script determines the state of the push-button. Then the infinite loop begins again and calls the rolling action depending on the detected sensor value. As long as the push-button is not depressed, the infinite loop sends one update statement after the other in order to determine if the user presses the button. Like all other GPIO messages, these update statements are shown in the text window of Pi_Scratch.

63 6.2 Rolling the dice in Python Rolling the dice in Python The Python program ledwuerfel.py represents the same die in Python. The circuit and the used GPIO ports are identical to those used in the Scratch script How it works The program contains many known elements. Here we only show the new ones. #!/usr/bin/python import RPi.GPIO as GPIO import time, random During initialization, we also import the module random that allows for generating random numbers. You might think that nothing in a program runs randomly. But how can a program generate random numbers? When you divide a number by an arbitrary value, the nth decimal place will contain numbers that are nearly unpredictable. When you increase the divisor in a regular way, these numbers change irregularly. The result seems to be random. However, it can be reproduced by an identical program or the repeated execution of the same program. But if you combine these numbers to another number and divide that number by the current seconds reading of the clock or an arbitrary memory location in the computer, you get a result that is not reproducible and thus a random number. How are random numbers generated? GPIO.setmode(GPIO.BCM) LED = [18,25,24,23] TASTE = 7 As in the previous examples, the numbering of the GPIO ports is set to BCM. The numbers for the middle LED and the three LED pairs are defined in the array LED. The GPIO port of the push-button is defined in the constant TASTE.

64 64 6 LED DICE for x in range(4): GPIO.setup(LED[x], GPIO.OUT) GPIO.setup(TASTE, GPIO.IN) print ( Press the button to throw the dice. Ctrl+C quits the program. ) The GPIO ports for the LEDs are defined as outputs, the GPIO port for the push-button is defined as input. Then a short information about the program is shown on the screen. try: while True : if GPIO.input(TASTE)==1: Now the infinite loop begins and waits for the user to press the push-button. for x in range(4): GPIO.output(LED[x], 0) time.sleep(0.5) When the push-button is depressed, all LEDs are turned off, and the program waits for 0.5 s. w = random.randrange(1,7) print Result: + str(w) Then a random number between 1 and 6 is generated and shown on the screen. The display of this information can be omitted. if w == 1: GPIO.output(LED[0], 1) if w == 2: GPIO.output(LED[1], 1)... if w == 3: GPIO.output(LED[0], 1) GPIO.output(LED[2], 1)

65 6.2 Rolling the dice in Python 65 Depending on the result, the respective LEDs are turned on. print ( Press the button to throw the dice. Ctrl+C quits the program. ) Independent of the result, the user is again asked to press the button. Then the program jumps back to the beginning of the loop. The LEDs remain turned on until the user presses the button again.

66 7 Control the Scratch cat with GPIO buttons The Scratch mascot, the cat, can walk on the stage and leave track marks. It represents the different objects ( sprites ) that can be animated in Scratch. The Scratch script tasten demonstrates how to control Scratch animations with GPIO buttons. Figure 7.1: Four push-buttons with resistors on the breadboard For the following experiment, arrange four push-buttons with pull-up and pull-down resistors as directional buttons for moving an object to the left, to the top, to the right and to the bottom.

67 Required components: 1 x breadboard, 4 x push-button, 4 x 1 kw resistor (brown-black-red), 4 x 10 kw resistor (brown-black-orange), 6 x connection cables, 6 x wire bridges (different lengths) Figure 7.2: Four push-buttons with resistors on the breadboard The four push-buttons shall move the cat in the four directions for ten steps each. The motion shall be shown as lines so that you can track the movement of the cat or draw little graphics.

68 68 7 Control the Scratch cat with GPIO buttons Figure 7.3: The moves in accordance to the GPIO buttons 7.1 How it works The script queries the four push-buttons in an infinite loop. When the user presses a button, the cat turns into the respective direction and walks ten steps. The first thing that happens when the user clicks the green flag is that the four GPIO ports are initialized. Here we use the ports 18, 25, 10 and 14 as push-button inputs. The scripts warts for a second to let the initialization of the GPIO ports happen. Now the pen is lowered. This means that from now on, every motion leaves a track mark on the stage. Click the dark green Pen category in the block palette and drag the Pen Down block into the script. Then the infinite loop begins and waits for the user to press the push-button. Each push-button is queried separately by an If block. When the push-button at GPIO port 8 (left) is depressed, the cat turns for -90. In Scratch coordinates, this means to the left. Here we use

69 7.1 How it works 69 absolute directions, because the orientation of the cat before pressing the button is not saved. After turning the cat walks for ten steps. The other three buttons are queried in the same way. The cat turns and moves accordingly. Now the program always waits for half a second. Otherwise key-bouncing might undesirably trigger two subsequent actions. After that all sensors are queried again by an update command. In this way the script determines the state of the four push-button. Then the infinite loop begins again and moves the cat according to the detected sensor value. Eventually the screen is filled with lines, and maybe the cat tries to vanish beyond the edge of the stage. For this case you create a second script block that is neither connected to the first one nor executed when you click on the green flag. This second script is not started by the green flag, but by clicking the cat Sprite1. It resets the program. First, it turns the cat to the standard direction (to the right) and places it at coordinates x:0, y:0 center stage. Finally, all drawn tracks are erased. This script can be triggered at any time by clicking the cat. You do not have to quit the main script; it is still executed. Immediately after resetting you can thus press one of the push-buttons to move the cat again.

70 8 First experiments with the LC display The next experiments demonstrate how to use Scratch and ython to write text on the LC display. First you have to solder the P included header connection to the display as described on page 20. Figure 8.1: The 16 connection pins of the LC display

71 8.1 Pin assignment of a HD44780 compatible display Pin Function Description 1 VSS Power supply, 0 V ground wire 2 VDD Power supply, + 5V 3 V0 Contrast setting, 0 V... 5 V 4 RS Register select 5 RW Read/write; connected to 0 V, when nothing is read from the display 6 E Enable (switching signal) 7 D0 Data bit 0 (not required in 4-bit mode) 8 D1 Data bit 1 (not required in 4-bit mode) 9 D2 Data bit 2 (not required in 4-bit mode) 10 D3 Data bit 3 (not required in 4-bit mode) 11 D4 Data bit 4 12 D5 Data bit 5 13 D6 Data bit 6 14 D7 Data bit 7 15 A Background lighting, 560 W series resistor required 16 K Background lighting, ground wire Required components: 1 x breadboard, 1 x LC display, 1 x 560 W resistor (green-blue-brown), 1 x potentiometer, 8 x connection cables, 6 x wire bridges (different lengths)

72 72 8 First experiments with the LC display Figure 8.2: Yellow: control wires; purple: data wires; red: +5 V; blue: ground Unfortunately Pi_Scratch demands particular GPIO ports for controlling the LC display. This makes the representation of the cable connections in the diagram a little bit messy. For the subsequent Python programming examples we will use the same GPIO ports so that we can reuse the existing circuit, although in Python, you could choose the ports freely.

73 8.1 Pin assignment of a HD44780 compatible display 73 Display pin Signal Raspberry Pi GPIO 1 VSS 0 V 2 VDD +5V 3 V0 Potentiometer 4 RS GPIO 25 5 RW 0 V 6 E GPIO 24 7 D0 Not required in 4-bit mode 8 D1 Not required in 4-bit mode 9 D2 Not required in 4-bit mode 10 D3 Not required in 4-bit mode 11 D4 GPIO D5 GPIO D6 GPIO D7 GPIO A 560 W series resistor 16 K 0 V In addition to the connection cables to the Raspberry Pi you need wire bridges of different lengths in order to merge several pins to provide a common power supply and ground wire. Cut these bridges from the included jumper wire und remove the insulation at both ends for approx. 5 mm. Place a 560 W resistor as protection against overloading in front of the background lighting LED at pin 15. As a means to set the contrast, you insert a 15 kw potentiometer so that it supplies pin 3 with voltages between +5V and 0 V.

74 74 8 First experiments with the LC display Double-check the circuit Before you supply the Raspberry Pi and the circuit with electrical power, you have to check all connection leads. An incorrectly attached +5 V line can damage the display. The maximum voltage at the contrast pin must be less than +5 V. Thus you must never fully open the potentiometer! The display supports two data transfer modes. In the 8-bit mode, you can transfer a complete character in one go. However, in most cases the 4-bit mode is used, because you can save four ports at the sending device. Here the data of one character are send in two consecutive blocks. Pi_Scratch generally uses the 4-bit mode. 8.2 Digital clock with Scratch on the LC display Pi_Scratch provides a very good support for LC displays. You do not have to bother with the technology of the display, but can directly output text. Figure 8.3: Digital clock with Pi_Scratch

75 8.2 Digital clock with Scratch on the LC display 75 The first Scratch script will display the digital clock shown above How it works When using Pi_Scratch for the LC display, it is not necessary to register the individual GPIO ports as outputs. Pi_Scratch contains an initialization routine that initializes the display and the GPIO ports. The Broadcast block initializes the GPIO ports and the display with the text LCD1602g init. This Code must be present at the beginning of every program that uses the LC display. The initialization is internally handled by a long command sequence. After that, the script has to wait for 0.2 s until the display is operational. You should provide a waiting period like this after every command that writes to the display. Otherwise the next display command may not be processed correctly. All of the following display commands consist of the word LCD1602 (without the trailing g), a space and the respective command or the text to be displayed.

76 76 8 First experiments with the LC display In order to enter these display commands, drag the Join block from the green Operators category into the text field of the Broadcast block. With this block, you can combine output strings. The green block contains two text fields that can be edited freely. Entering text here is thus significantly more convenient than entering it directly in the Broadcast block. This is particularly true when you duplicate the completed block by right-clicking it so that you can reuse it for a similar command. Make sure there is a space at the end of the first field after LCD1602. The command cls in the second field clears the display. Always use this command at the beginning of a program in order to erase any remaining data from the memory of the display. After that, the script waits for another 0.2 s. Now the current time is written in the first line. At the beginning of any text output you have to specify the coordinates of the first character. This first number in these coordinates represents the number of the character on the line, the second one gives the line number. The top line of the display is number 0, the bottom line is number 1. The characters on the line are numbered from left to right, beginning with 0. The time is represented by eight characters. In order to center them on the display, we skip the first four and the last four columns of the display. The text begins at the fifth column, i.e. column number 4. Thus the coordinates are 4,0. The keyword time retrieves the current time in the 24 hour format. After each text output, you should wait for 0.2 s before you issue the next display command.

77 8.2 Digital clock with Scratch on the LC display 77 With the same command sequence we write to the bottom line of the display. (Of course you can choose another text of your liking.) The coordinates 1,1 specify that the text begins in the second column of the bottom line. The 14 character sample text is thus centered on the display. Click on the green flag. Shortly after that, you can see the text on the display. The display shows the current time of the program execution, but does not update to keep the time. So it does not really do what a clock is supposed to do. This does not come as a surprise, as the script runs just once and writes the then current time to the display. The clock does not keep the time The solution is to use an infinite loop that regularly writes the current time to the display. When you click on a block in a Scratch script, you can detach it with all the following blocks from the preceding blocks and move around in the Script window. Use this method to detach the blocks that write the lines of text with their subsequent Wait blocks from the script. Reattach the block that writes the static bottom line to the remaining script. This text does not need to be written to the display several times. Now attach a Forever block underneath the script and drag the blocks with the time display and the respective Wait blocks into this loop. These statements will be repeated continuously. When you now click the green flag, you have a digital clock with a working time display!

78 9 Controlling the LC display in Python In Python the display is controlled on a very low level, i. e. directly via high and low signals on the GPIO ports. This may seem rather uncomfortable in the beginning, but in doing this you get more familiar with the operating mode of an LC display. Figure 9.1: Simple text output on an LC display In this project, the display is also operated in the 4-bit mode. Use the same circuit as in the display experiment with Scratch. The table only shows the data wires of the display and the GPIO ports that we use. Display pin Signal Raspberry Pi GPIO 4 RS GPIO 25 6 E GPIO D4 GPIO 23

79 Display pin Signal Raspberry Pi GPIO 12 D5 GPIO D6 GPIO D7 GPIO 22 The first simple Python example display01.py writes two static character strings to the display. The basic program shown here is used as a framework for the following LC display programming examples. #!/usr/bin/python import RPi.GPIO as GPIO import time LCD_RS LCD_E LCD_D4 LCD_D5 LCD_D6 LCD_D7 = = = = = = GPIO.setmode(GPIO.BCM) GPIO.setup(LCD_E, GPIO.OUT) GPIO.setup(LCD_RS, GPIO.OUT) GPIO.setup(LCD_D4, GPIO.OUT) GPIO.setup(LCD_D5, GPIO.OUT) GPIO.setup(LCD_D6, GPIO.OUT) GPIO.setup(LCD_D7, GPIO.OUT) LCD_WIDTH = 16 LCD_LINE_1 = 0x80 LCD_LINE_2 = 0xC0 LCD_CHR = True LCD_CMD = False E_PULSE = E_DELAY = def lcd_enable(): time.sleep(e_delay) GPIO.output(LCD_E, True) time.sleep(e_pulse) GPIO.output(LCD_E, False) time.sleep(e_delay)

80 80 9 Controlling the LC display in Python def lcd_byte(bits, mode): GPIO.output(LCD_RS, mode) GPIO.output(LCD_D4, bits&0x10==0x10) GPIO.output(LCD_D5, bits&0x20==0x20) GPIO.output(LCD_D6, bits&0x40==0x40) GPIO.output(LCD_D7, bits&0x80==0x80) lcd_enable() GPIO.output(LCD_D4, bits&0x01==0x01) GPIO.output(LCD_D5, bits&0x02==0x02) GPIO.output(LCD_D6, bits&0x04==0x04) GPIO.output(LCD_D7, bits&0x08==0x08) lcd_enable() def lcd_string(message): message = message.ljust(lcd_width, ") for i in range(lcd_width): lcd_byte(ord(message[i]),lcd_chr) def lcd_anzeige(z1, z2): lcd_byte(lcd_line_1, LCD_CMD) lcd_string(z1) lcd_byte(lcd_line_2, LCD_CMD) lcd_string(z2) LCD_INIT = [0x33, 0x32, 0x28, 0x0C, 0x06, 0x01] for i in LCD_INIT: lcd_byte(i, LCD_CMD) lcd_anzeige(" abcdefghijklmnopqrstuvwxyz, " www. franzis.de ) GPIO.cleanup() 9.1 How it works You can easily demonstrate that the script works. But what happens under the hood? What do the individual program lines mean? In the beginning we import the known libraries so that we can use the GPIO interface. LCD_RS = 7 LCD_E = 8 LCD_D4 = 25 LCD_D5 = 24 LCD_D6 = 23 LCD_D7 = 18

81 9.1 How it works 81 These lines define the constants that save the numbers of the GPIO ports for the control wires and data wires of the display. GPIO.setmode(GPIO.BCM) After that, the numbering of the GPIO pins is set to the BCM standard. GPIO.setup(LCD_E, GPIO.OUT) GPIO.setup(LCD_RS, GPIO.OUT) GPIO.setup(LCD_D4, GPIO.OUT) GPIO.setup(LCD_D5, GPIO.OUT) GPIO.setup(LCD_D6, GPIO.OUT) GPIO.setup(LCD_D7, GPIO.OUT) The ports used for the display are defined as outputs. The port numbers are specified by the previously defined variables. This method has the advantage that the actually used GPIO ports are only mentioned in one place of the program. Thus you can change the program in an easy way when you want to use other ports. LCD_WIDTH = 16 LCD_LINE_1 = 0x80 LCD_LINE_2 = 0xC0 LCD_CHR = True LCD_CMD = False E_PULSE = E_DELAY = These lines define further constants that are used in the program. Constant LCD_WIDTH LCD_LINE_1 LCD_LINE_2 LCD_CHR LCD_CMD E_PULSE E_DELAY Description Width of the display given as the number of characters Memory address of the first line Memory address of the second line Switches the display at pin RS to character mode Switches the display at pin RS to control mode Duration of a control pulse at pin E Waiting time between two control pulses at pin E

82 82 9 Controlling the LC display in Python def lcd_enable(): Here we define a function that is later called in the program. It sends a short control pulse to pin E (enable). In this way the display reads the data at the GPIO port in order to write them. In the 4-bit mode the same pulse is used to switch between the upper und the lower bits of a byte to display. time.sleep(e_delay) Here we wait for a short time period that is specified in E_DELAY (0.05). The display exhibits a certain inertness. After one character has been written, you cannot immediately switch to the next half byte. GPIO.output(LCD_E, True) Now the logic signal True is output at pin E. time.sleep(e_pulse) GPIO.output(LCD_E, False) The signal is present at pin E during the time specified in E_PULSE. After that, the pin is reset to False. time.sleep(e_delay) Again, the program waits for the time specified in E_DELAY before completing the function. In this way, it is possible to send data to the display immediately after that. def lcd_byte(bits, mode): This function sends a byte to the display. This byte can be a character or a control command. The parameter bits contains the byte to send, the parameter mode specifies whether it is a character or a control command. mode can take one of two values that are defined in LCD_CHR (character) and LCD_CMD (control command), respectively. GPIO.output(LCD_RS, mode)

83 9.1 How it works 83 The mode to use is output at pin RS (Register Select) to switch the display to character mode or control mode. GPIO.output(LCD_D4, bits&0x10==0x10) GPIO.output(LCD_D5, bits&0x20==0x20) GPIO.output(LCD_D6, bits&0x40==0x40) GPIO.output(LCD_D7, bits&0x80==0x80) The program utilizes the 4-bit mode of the display. At first, the upper 4 bits of the byte to send are written to the date wires by using the Python operator & (bitwise AND). The four bits are tested one by one to see if they are 1 or 0. The result of this test is either True or False. This value is then written to the respective data wire. Bit numbering 4 high 3 high 2 high 1 high 4 low 3 low 2 low 1 low Pin D7 D6 D5 D4 D7 D6 D5 D4 Binary Decimal Hex 0x80 0x40 0x20 0x10 0x08 0x04 0x02 0x01 lcd_enable() This previously defined function reads data at the GPIO ports and switches the display to the lower half byte. GPIO.output(LCD_D4, bits&0x01==0x01) GPIO.output(LCD_D5, bits&0x02==0x02) GPIO.output(LCD_D6, bits&0x04==0x04) GPIO.output(LCD_D7, bits&0x08==0x08) According to the same pattern, the lower 4 bits of the byte to send are written to the data wires. lcd_enable()

84 84 9 Controlling the LC display in Python Then the display is switched back to the upper half byte. def lcd_string(message): This function writes the character string to the display. The calling program passes the string to the function in the parameter message. message = message.ljust(lcd_width, ) At the right hand side, the string is padded with spaces up to the width of the display. The width of the display is given in the constant LCD_WIDTH. In our case, it is 16 characters wide. The method.ljust can be used for any character string. The second parameter specifies the characters that are used to pad shorter strings. Strings that are too long are automatically truncated to the right length. for i in range(lcd_width): lcd_byte(ord(message[i]),lcd_chr) This loop is repeated for the number of characters in the display. In each iteration, the Python function ord() converts one character of the message string to the respective numerical ASCII value, and the previously defined lcd_byte() function writes this value in the LCD_CHR character mode to the display. def lcd_anzeige(z1, z2): This function is passed two character strings by the calling program and causes these lines to be written to the display. lcd_byte(lcd_line_1, LCD_CMD) lcd_string(z1) First, the address of the upper line of the display is written to the display in the LCD_CMD control mode. In this way we specify that the following character mode outputs appear on the upper line. Then the lcd_string() function writes the first character string to the display. lcd_byte(lcd_line_2, LCD_CMD) lcd_string(z2)

85 9.1 How it works 85 In the same way the second character string is written to the lower line of the display. After defining the four functions lcd_enable(), lcd_byte(), lcd_string() and lcd_anzeige(), the actual program begins. LCD_INIT = [0x33, 0x32, 0x28, 0x0C, 0x06, 0x01] Before you can use the display, you have to initialize it. A sequence of initialization commands sets up the display in a definite state and switches it to 4-bit mode. for i in LCD_INIT: lcd_byte(i, LCD_CMD) This loop writes the initialization commands contained in the list LCD_INIT to the display (using the LCD_CMD control mode). To transfer the data, we use the previously defined lcd_byte() function. After everything is defined and initialized, we can actually start. lcd_anzeige(" abcdefghijklmnopqrstuvwxyz, " ) This line specifies the character strings that have to be displayed. The length is of no importance, because the previously defined lcd_ string() function automatically pads or truncates them to a length of 16 characters. GPIO.cleanup() And this is already the end of the program. As in every other Python programs, we have to close the GPIO interface in order to avoid warnings at the next start of a program. After completing the program, the output still remains on the display. The display is not constantly querying the GPIO ports, but reads data only when the Enable signal is switched. After that, the display remains unchanged, independent of the presence of data at the date wires.

86 10 LC display in 8-bit mode The next project shows how to use the LC display in 8-bit mode. Use four additional connection cables to connect the data wires D0 to D3 of the display with the GPIO ports 7 to 10 as shown. Figure 10.1: LC display in 8-bit mode. The additional cables are represented by green lines.

87 Required components: 1 x breadboard, 1 x LC display, 1 x 560 W resistor (green-blue-brown), 1 x potentiometer, 12 x connection cables, 6 x wire bridges (different lengths) The following table shows an overview of the data wires of the display and the GPIO ports used for this experiment. The wires D4 to D7 are connected as in the previous project. Display pin Signal Raspberry Pi GPIO 4 RS GPIO 25 6 E GPIO 24 7 D0 GPIO 7 8 D1 GPIO 8 9 D2 GPIO 9 10 D3 GPIO D4 GPIO D5 GPIO D6 GPIO D7 GPIO 22

88 88 10 LC display in 8-bit mode 10.1 How it works The program display01_8.py is based on the previous program. Here we only show the changes that were made to use the 8-bit mode. LCD_RS = 25 LCD_E = 24 LCD_D0 = 7 LCD_D1 = 8 LCD_D2 = 9 LCD_D3 = 10 LCD_D4 = 23 LCD_D5 = 17 LCD_D6 = 27 LCD_D7 = 22 In the definitions of the GPIO port numbers, we declare four additional variables for the four new data wires. GPIO.setmode(GPIO.BCM) GPIO.setup(LCD_E, GPIO.OUT) GPIO.setup(LCD_RS, GPIO.OUT) GPIO.setup(LCD_D0, GPIO.OUT) GPIO.setup(LCD_D1, GPIO.OUT) GPIO.setup(LCD_D2, GPIO.OUT) GPIO.setup(LCD_D3, GPIO.OUT) GPIO.setup(LCD_D4, GPIO.OUT) GPIO.setup(LCD_D5, GPIO.OUT) GPIO.setup(LCD_D6, GPIO.OUT) GPIO.setup(LCD_D7, GPIO.OUT) These four GPIO ports are also initialized as outputs. The other variable declarations and the lcd_enable() function remain unchanged. def lcd_byte(bits, mode): GPIO.output(LCD_RS, mode) GPIO.output(LCD_D0, bits&0x01==0x01) GPIO.output(LCD_D1, bits&0x02==0x02) GPIO.output(LCD_D2, bits&0x04==0x04) GPIO.output(LCD_D3, bits&0x08==0x08) GPIO.output(LCD_D4, bits&0x10==0x10)

89 10.1 How it works 89 GPIO.output(LCD_D5, bits&0x20==0x20) GPIO.output(LCD_D6, bits&0x40==0x40) GPIO.output(LCD_D7, bits&0x80==0x80) lcd_enable() As in the previous program, the lcd_byte() function calculates the 8 bits of a character. However, this time it writes these bits at once to the eight data wires instead of passing them in two blocks. The functions lcd_string() and lcd_anzeige() remain unchanged, because they are only concerned with the representation of the character strings and not with controlling the display hardware. LCD_INIT = [0x33, 0x32, 0x38, 0x0C, 0x06, 0x01] The third character in the initialization string must change so that we can use the 8-bit mode of the display: Third character of the initialization string 0x28 0x38 4-bit mode 8-bit mode All other program instructions are identical to those in the program version for the 4-bit mode. When you look at the required effort for connecting the components and for programming, the 4-bit mode is to be preferred to the 8-bit mode. In 4-bit mode, you only need six GPIO ports as opposed to ten, and the program is a few lines shorter (at least when you use Python). Because of this reason we will again use the 4-bit mode in the following examples. Pi_Scratch does not support the 8-bit mode. 4-bit mode versus 8-bit mode what is the better choice? Of course you will now ask why there is still such a thing as the 8-bit mode, as the 4-bit mode has so many advantages. The manufacturers of LC displays could even save four ports! However, in the experiment LC display at the port expander you will see that the 8-bit mode has its advantages in special use cases.

90 11 Displaying the IP address of the Raspberry Pi It is not easy to determine the IP address of a Raspberry Pi when you use it without a monitor. However, you need to know this address in order to set up an SSH connection for server administration. With an LC display and a Python script you can get this information in a smart way. Figure 11.1: y means of a Python script, the LC display shows the current server time and the IP address

91 11.1 How it works The program status.py uses the 4-bit mode display control functions of the previously described program display 01.py. The circuit and the used GPIO ports are also identical. In the following you will only see the new program elements. #!/usr/bin/python import RPi.GPIO as GPIO import time, subprocess In the very beginning, the addition library subprocess is imported. It allows to call and evaluate Linux commands in Python programs. pause = 2 In the variable declarations, we introduce the additional variable pause that saves the update interval for the time display. The value 2 means that the time is only updated every two seconds. As we only need precision in the minute range, this is a good trade-off between accuracy and system load. The functions to access the display and the initialization sequence remain unchanged. Instead of a simple static text output we now use a loop, that continuously updates the time and the IP address. try: while True: This loop is repeated until the abort condition occurs that is defined further down in the program with except. zeile1 = time.asctime()

92 92 11 Displaying the IP address of the Raspberry Pi In order to display date and time we use the function time.asctime() in the time module. It provides date and time as a character string, e. g. Fri May 16 13:14: The first 16 characters of this string show the day of the week, the month, the day, the hours and the minutes on the 16-column display. The output of this function is saved in the new variable zeile1. zeile2 = IP: + subprocess.check_ output([ hostname, -I ])[:-2] The variable zeile2 saves the IP address. To this end we use the function check_output() in the subprocess module that supplies us with the output of any shell command as a character string. The last two characters of this string are not used: The line feed character \n of the output and one space at the end are truncated. Long IP addresses If you need more than 13 characters for the IP addresses in your local network (e. g ), you omit the string IP: at the beginning, as the display has only 16 columns. lcd_anzeige(zeile1, zeile2) The contents of these variables are written to the display by means of the lcd_anzeige() function that is defined in the basic program. time.sleep(pause) After that, the program waits for the time that is defined as pause (this defaults to 2 s). Then the loop begins again and shows the new time. except KeyboardInterrupt: GPIO.cleanup() When the user presses (Ctrl) + (C), a KeyboardInterrupt is triggered, and the loop exits automatically. The last line closes the used GPIO ports. Subsequently the program quits. The text remains visible on the display, but the clock is not updated any more. It is the controller inside the display that continues to show the last output. The controlled closing of the GPIO ports prevents disconcerting system warnings or abort messages from popping up at the next start of a program that uses the GPIO interface.

93 11.2 Launching programs automatically Launching programs automatically This program is particularly useful when there is no monitor connected to the Raspberry Pi. In such a case you can automatically launch the program when the Pi is booted. Create a text file named autostart in the directory /home/pi/. config/lxsession/lxde. This file must contain the command to start the program: sudo python status.py This causes the current IP address to be written to the LC display after the Raspberry Pi is booted and the user pi is logged in. When you use Raspbian and Pi_Scratch and are automatically logged in as root, append the following additional line at the end of the file python /home/pi/status.py This file is always processed, no matter which user is logged in.

94 12 Marquee text on the LC display LC displays and similar character-based display elements are often used for marquee text. In this way, even longer texts can be shown on the relatively short lines of the display. This experiment writes an arbitrary text as marquee to the lower line of the display. The upper line shows the clock from the previous experiment. Figure 12.1: Clock and marquee text on the LC display

95 12.1 How it works The program laufschrift.py is based on status.py. We only need to apply a few changes to display marquee text. pause = 0.3 The pause is shortened to 0.3 s. This is now the time period in which the marquee advanced for one character. Extending the pause makes the marquee text run slower. meintext = * LCD_WIDTH + raw_input( Bitte Text eingeben: ) This line uses the raw_input() function to ask for user input. Figure 12.2: The Python shell waits for user input The entered text is saved in the variable meintext and prepended by as many spaces as there are columns in the display, in this case 16. In Python you can simply multiply a string by a number in order to repeat it. By using the constant LCD_WIDTH instead of a number this program can also be used on wider displays. try: while True: for j in range(len(meintext)):

96 96 12 Marquee text on the LC display In the main loop of the program we now have another loop that iterates over the length of the text. lcd_anzeige(time.asctime(), meintext[j:(j + LCD_WIDTH)]) In each iteration the current time is written to the upper line of the display, while the lower line shows a 16 character wide clipping of meintext. The clipping begins each time one character nearer to the end. As there are 16 spaces at the beginning of meintext, the display is at first empty. The text then moves into the display from the righthand side one character after the other. At the end of the text, no additional spaces are required, as they are automatically appended as needed by the known lcd_string() function. time.sleep(pause) After a text clipping has been displayed, the program waits for 0.3 s. Then the next text clipping appears, advanced by one character. The inner loop ends after the last character of meintext has vanished beyond the left edge of the display. Then it starts again. The outer loop is executed until the user aborts the program with (Ctrl) + (C).

97

98 13 Extended status display The next program extends the status display by showing the r emaining storage space on the SD card and on up to three attached USB sticks. The power consumption of USB sticks is so low that you can connect several of them to the Raspberry Pi via a hub without a power supply of its own. Figure 13.1: Three USB sticks connected to the Raspberry Pi via a USB hub The circuit is identical to the one used in the previous experiments. File systems on USB sticks USB sticks are usually formatted with the vfat file system. Linux can read and write this file system. Only the rights management is missing in vfat. When you leave the vfat file system on the USB stick in place, you can easily transfer data from any PC to your server by just replugging the stick. However, Windows cannot do anything with a Linux formatted USB stick.

99 In order to mount (= register) an attached USB stick in Linux, you first have to determine under which name the stick has automatically been entered in the Linux directory structure. sudo fdisk -1 In most cases a USB stick is labeled like a physical USB hard drive as /dev/sa. The first partition on this device is then called /dev/sda1. Other USB sticks are then identified as /dev/sdd or /dev/sde. Every USB stick has a unique device ID. In order to avoid confusion when several USB sticks are attached, you have to make sure that only one particular USB Stick is mounted in the given directory. To this end you first read the UUID of the stick. blkid /dev/sda1 If the USB stick has a different physical name than /dev/sda1, you use that one instead. The following command shows the UUID of the USB stick and the type of file system: /dev/sda1: UUID= 8CA8-C35A TYPE= vfat Determine the UUIDs of all attached USB sticks with this method and enter them in the file /etc/fstab. sudo nano /etc/fstab In the following example, replace the UUIDs by the UUIDs for your respective USB sticks. Also note the other displayed parameters. They are necessary for the user pi to mount the USB stick and get full access. proc /dev/mmcblk0p1 /dev/mmcblk0p2 UUID=8CA8-C35A UUID=7FDA-61CD UUID=B4AE-44EF /proc /boot / /media/usb1 /media/usb2 /media/usb3 proc vfat ext4 vfat vfat vfat defaults 0 defaults 0 defaults,noatime 0 defaults,umask=000,users defaults,umask=000,users defaults,umask=000,users

100 Extended status display Restart the Raspberry Pi. The USB sticks are mounted automatically, so that user pi can copy data to them. When you plug in another USB stick at the Raspberry Pi, it will not be mounted automatically How it works The program status_sdusb.py is based on the program status. py. In addition to time and IP address, it alternately shows the free storage space on the SD card and on three attached USB sticks after an interval of 5 s. To this end it contains the following additional code lines: import time, subprocess, os At the beginning, the additional module os is imported. It allows access to the Linux file system, so that we can determine the free storage space. HD_1 = /media/usb1 HD_2 = /media/usb2 HD_3 = /media/usb3 In the part with the definitions, we specify the names of the attached USB sticks as constants. pause = 5 The waiting time for updating the display is extended to 5 s, as it is nearly impossible to read all the information on the display in a 5 s interval. The most important changes occur in the main loop of the program. It now consists of three blocks, that display different pieces of information one by one.

101 13.1 How it works 101 try: while True: zeile1 = time.asctime() zeile2 = "IP: + subprocess.check_output(["hostname, -I ])[:-2] lcd_anzeige(zeile1, zeile2) time.sleep(pause) s = os.statvfs( / ) hd1 = os.statvfs(hd_1) zeile1 = "SD: + str(s.f_bsize * s.f_bavail / ) + " MB zeile2 = USB1: + str(hd1.f_bsize * hd1.f_bavail / ) + MB lcd_anzeige(zeile1, zeile2) time.sleep(pause) hd2 = os.statvfs(hd_2) hd3 = os.statvfs(hd_3) zeile1 = "USB2: + str(hd2.f_bsize * hd2.f_bavail / ) + " MB zeile2 = USB3: + str(hd3.f_bsize * hd3.f_bavail / ) + MB lcd_anzeige(zeile1, zeile2) time.sleep(pause) Similar to status.py, this program displays time and IP address at first. Then it waits for the pause that was defined as a 5 s interval at the beginning. s = os.statvfs( / ) The statistics module os.statvfs() in the os library provides miscellaneous information about the file system. In each loop iteration, information about the main directory is written as an object to the variable s anew. However, the storage space of the mounted external volumes is not determined in this step. hd1 = os.statvfs(hd_1) In the same way, the data for the first USB stick are determined and written to the variable hd1. The mounting point of the first USB stick is taken from the constant HD_1 that was defined at the beginning.

102 Extended status display The new first line zeile1 shows the free storage space on the SD card. The s.f_bsize method uses the file system data stored in the variable s to provide the size of a storage block measured in bytes. s.f_bavail provides the number of free blocks. The product of these values results in the number of free bytes. This value is then divided by 1,048,576 in order to give the amount in megabyte. The line is a concatenation of the three strings SD:, the calculated value and MB. zeile2 = USB1: + str(hd1.f_bsize * hd1.f_bavail / ) + MB In the same way the free storage space on the first USB stick is calculated and displayed in line 2. The familiar lcd_anzeige() function writes the data to the display. Again, the display remains unchanged for 5 s. Then the data of the second and third USB stick are determined and displayed. When you attach less than three USB sticks, simply remove the respective code lines. Run the program and transfer huge amounts of data to the SD card or the USB sticks. You can observe the megabyte values change with each display cycle.

103

104 14 Interactive status display with push-buttons Until now, the status display changes automatically between three pages with two display lines each. With two additional pushbuttons you can make the display controllable by the user. One of the push-buttons scrolls one page up, the other one down. In this way we always see two lines that are automatically updated. Figure 14.1: Interactive status display with two push-buttons for scrolling Attach two push-buttons with pull-down resistors to a second breadboard as shown in the picture. Arrange the buttons in such a way that you can access them conveniently despite the broad cable harness that runs to the Raspberry Pi. Required components: 2 x breadboard, 1 x LC display, 1 x 560 W resistor (green-blue-brown), 1 x potentiometer, 2 x push-button, 2 x 1 kw resistor (brown-black-red), 2 x 10 kw resistor (brown-blackorange), 11 x connection cable, 9 x wire bridge (different lengths)

105 Figure 14.2: LC display with two push-buttons The circuit is nearly identical to that of the previous LC display e xperiments. We still use the same GPIO ports. The two light blue wires connect the push-buttons with the GPIO ports 14 and 15.

106 Interactive status display with push-buttons Two different power supplies In particular pay attention to the correct connection of the power supply, as this circuit uses both power supply lines of the Raspberry Pi: +3.3 V for the GPIO ports of the push-buttons and +5 V for the display How it works The program status_sdusb_taste.py is based on status_ sdusb.py, but adds the push-button control. T1 = 14 T2 = 15 In the definition part at the beginning, we define two additional GPIO ports for the push-buttons. GPIO.setup(T1, GPIO.IN) GPIO.setup(T2, GPIO.IN) Later on, they are initialized as inputs. pause = 0.1 As the pause now specifies the query interval of the push-buttons, it is reduced to 0.1 s. If the pause were too long, the user would have to press the push-buttons for a very long time so that the program detects the process. z1 = 0 zeile = [,,,,, ] Now we define another variable and an array with six empty strings that later on will be used to chose and display the six individual lines. The most important differences to the previous program versions can be found in the main loop. try: while True: s = os.statvfs( / ) hd1 = os.statvfs(hd_1) hd2 = os.statvfs(hd_2) hd3 = os.statvfs(hd_3)

107 14.1 How it works 107 zeile[0] = time.asctime() zeile[1] = IP: + subprocess.check_output([ hostname, -I ])[:-2] zeile[2] = SD: + str(s.f_bsize * s.f_bavail / ) + MB zeile[3] = USB1: + str(hd1.f_bsize * hd1.f_bavail / ) + MB zeile[4] = USB2: + str(hd2.f_bsize * hd2.f_bavail / ) + MB zeile[5] = USB3: + str(hd3.f_bsize * hd3.f_bavail / ) + MB The texts for the six different display lines are combined from the respective values and stored in the six fields of the zeile[] array. The variable z1 specifies which lines shall be displayed. At the beginning this variable is set to 0. Thus zeile[0] and zeile[1] are written to the display. if GPIO.input(T1)==1: z1 += 1 if z1 > 4: z1 = 4 When the user presses push-button 1, z1 is incremented by 1, so that the display scrolls one line down and now shows zeile[1] and zeile[2]. When you press the button several times, so that z1 reaches the value 4, zeile[4] and zeile[5] are displayed. Higher values are not possible, because no other lines are defined. Thus z1 is automatically set to 4 when the user presses push-button 1 another time. if GPIO.input(T2)==1: z1 -= 1 if z1 < 0: z1 = 0 According to the same principle, the other button scrolls upwards by decrementing the value of z1 with each depression of the button. If this leads to a value less than 0, z1 is automatically set to 0. In this case, zeile[0] and zeile[1] are displayed. lcd_anzeige(zeile[z1], zeile[z1 + 1]) time.sleep(pause) At the end of each loop iteration, the line defined by z1 and the following line are written to the display. After a short waiting period the loop begins again, updates the display and tests if the user has pressed a button.

108 15 Chaser lights with the port expander Chaser lights are a popular effect to attract interest, be it at a rivate party or in professional advertising. With the Raspberry Pi and p a few LEDs, you can easily implement this effect. The only problem is that you quickly run out of GPIO ports The MCP23017 port expander The kit contains an integrated circuit named MCP This is a port expander that is controlled by two control wires of the Raspberry Pi, but provides 16 programmable GPIO ports. The MCP23017 chip features 14 ports at each side, eight of which (on each side) are GPIO ports. The remaining ports are used as control wires and for power supply. Figure 15.1: Pin assignment of the MCP23017

109 For the data sheet for this chip, see raspberry-pi. Like all integrated circuits of this design, the MCP23017 sports a Mind the notch! notch at one of the narrow sides. It specifies the orientation, so that you place the chip in the right way. When setting up the circuits for the experiment, always look at the circuit diagrams in the book and orient the chip as shown. The ports GPA0 to GPA7 and GPB0 to GPB7 form the two 8-bit GPIO interfaces GPIOA and GPIOB that can be controlled binary. This means you do not control the individual ports, but write a number with the length of 8 bits as a whole to the interface GPIOA or GPIOB. The ports VDD and VSS are used as power supply for the port expander. VDD has to be connected to +3.3 V, VSS to +5 V. The RESET port is set to True in normal operation, i. e. it must be connected to +3.3 V. The ports A0, A1 and A2 define the address of the port expander. Three wires can represent a binary number from 0 to 7. A wire that is connected to 0 V has a value of 0, a connection to +3.3 V provides a value of 1. The value 0x20 is added to the result, so that you can use the I2C addresses 0x20 to 0x The I2C protocol I2C (inter-chip communication) is a standards-based serial communication protocol that allows electronic chips to exchange data via a two-wire connection. Every device on this very simple data bus needs a unique address so that the data can be assigned to the respective devices. The Raspberry Pi supports the I2C protocol, but you have to activate it first.

110 Chaser lights with the port expander I2C in Pi_ Scratch When you have installed the Pi_Scratch library as described in the experiment Scratch and GPIO, then I2C is already activated on the Raspberry Pi, and you can skip the next steps. When Pi_Scratch is not installed, you have to edit the files / etc/modprobe.d/raspi-blacklist.conf and /etc/modules as described on page 39. Afterwards install the following two packets for the I2C access in Python: sudo apt-get update sudo apt-get install python-smbus sudo apt-get install i2c-tools Restart the Raspberry Pi to initialize I2C. Enter the following command in the LXTerminal window to test the I2C support: sudo i2cdetect -y 1 On an old Raspberry Pi Rev. 1 you use the following command instead: sudo i2cdetect -y 0 With active I2C support, a table of the I2C devices on the bus is shown. As long as no device is attached, it is empty a b c d e f 00: : : : : : : : When you see an error message, the I2C protocol is not correctly activated on the Raspberry Pi.

111 15.3 LEDs at the port expander LEDs at the port expander The first experiment with I2C and the port expander lights up eight LEDs one by one light a chaser light. Set up the circuit as shown in the figure. Required components: 2 x breadboard, 1 x MCP23017 port expander, 2 x red LED, 2 x orange LED, 2 x yellow LED, 2 x green LED, 8 x 220 W resistor (red-red-brown), 4 x connection cables, 15 x wire bridges (different lengths) Figure 15.2: Chaser lights with the MCP23017 port expander

112 Chaser lights with the port expander Take care to orient the notch of the MCP23017 as shown. The wire bridges connect the LEDs of the same color with eight ports of the GPIOA interface. The dark blue wires are connected to 0 V, the red ones to +3.3 V. In addition to the power supply, this also applies to the RESET pin. The three short blue wires connect the three address wires with 0 V and thus provide the port expander with the I2C address 0x20. Run i2cdetect again when you have connected the circuit to the Raspberry Pi. sudo i2cdetect -y 1 Now the new device is shown in the I2C device list with the address 0x a b c d e f 00: : : : : : : : The program i2c_01.py lights up the LEDs like a chaser light. #!/usr/bin/python import time, smbus DEVICE = 0x20 IODIRA = 0x00 GPIOA = 0x12 bus = smbus.smbus(1) bus.write_byte_data(device,iodira,0x00) bus.write_byte_data(device,gpioa,0x00) while True: j = 1 for i in range(8): bus.write_byte_data(device,gpioa,j) j *= 2 time.sleep(0.1)

113 15.3 LEDs at the port expander How it works Programs that only use I2C do not have to initialize the GPIO interface. It is not even required to import the RPi.GPIO library. import time, smbus For I2C you have to import the smbus library. The time library is used to calculate the flash duration. After these imports, the three hardware addresses are defined as constants. DEVICE = 0x20 IODIRA = 0x00 GPIOA = 0x12 I2C device address of the port expander 8-bit register to specify the direction (output/input) of the GPIOA port 8-bit data register of the GPIOA port bus = smbus.smbus(1) This line defines an object named bus of type smbus.smbus(). This object is used to access the I2C bus with all attached devices. The method bus.write_byte_data() write one byte to the I2C bus. You always have to control all 8 bits of one of the two GPIOA ports. The I2C bus always processes whole bytes composed of 8 bits. Any byte can be given as binary, decimal or hexadecimal. bus.write_byte_data(device,iodira,0x00) This line writes a value of 0 to all bits of the IODIRA register of the device defined in the DEVICE constant (in this case the only existing I2C device). In this way every eight GPIOA ports are defined as outputs. A bit value of 1 would define the respective port as input. bus.write_byte_data(device,gpioa,0x00) This line writes a value of 0 to all bits of the GPIOA data register of the sam device. In this way every eight GPIOA ports are set to 0 and the attached LEDs are thus turned off.

114 Chaser lights with the port expander To implement the chaser lights, we now turn on the eight LEDs one by one. In order to do this the GPIOA data register has to consecutively take numerical values where one of the bits is set to 1. LED that lights up Binary Decimal Hex x x x x x x x x80 In this table you can easily see that in order to get the correct number, the decimal value has to be doubled with each step, beginning with 1. while True: The chaser light effect is repeated in a loop, until the user quits the program with (Ctrl) + (C). J = 1 At the beginning of the loop the value for the data register is set to 1, so that only the first LED lights up. for i in range(8): Inside the loop another loop is executed eight times. In each iteration, one LED is turned on.

115 15.3 LEDs at the port expander 115 bus.write_byte_data(device,gpioa,j) To do this, the current value of j is written in the GPIOA data register. In the first iteration the first bit is 1, while the other seven bits are 0. j *= 2 Subsequently the value of j is doubled in order to set the next bit to 1. time.sleep(0.1) This state remains for 0.1 s. Then the next loop iteration begins and the next LED lights up for 0.1 s. After eight iteration of the inner loop the next iteration of the outer loop begins. The value of j is reset to 1, and the first LED in the row lights up.

116 16 Binary clock Binary clocks show the time in a binary format. This looks cool, although or because reading the time takes getting used to. The clock manufacturer 01 the one ( offers binary wrist watches. The time display follows a simple principle. Every LED represents one bit of a binary number. You need four LEDs (8, 4, 2, 1) for the maximum of twelve hours and six LEDs (32, 16, 8, 4, 2, 1) for 59 minutes. Now you only have to add the values of the lighting LEDs to get the number of hours and minutes. As on an analog watch, the time is displayed in the 12 hour format. Figure 16.1: Circuit for a binary clock with ten LEDs

117 In this experiment we construct such a clock with ten LEDs that are controlled by the port expander. Figure 16.2: The time shown by this clock is 10:28 h. All resistors have the same value. The four series resistors of the hour LEDs are colored differently in this picture so that they can be seen more clearly. Required components: 2 x breadboard, 1 x MCP23017 port expander, 2 x red LED; 2 x orange LED, 2 x green LED, 2 x blue LED, 10 x 220 W resistor, 4 x connection calbe, 18 x wire bridges (different lengths)

118 Binary clock Figure 16.3: Binary clock with MCP23017 port expander This time, the LED connection leads do not run in parallel from the series resistors to the expander ports, but crosswise. This has the advantage that the rightmost LED with the lowest bit value is connected to the port with the lowest bit value. The other LEDs are arranged in the order of increasing bit value. This makes programming significantly easier. The table shows where to connect the individual LEDs.

119 16 Binary clock 119 LED Hour 8 Hour 4 Hour 2 Hour 1 Minute 32 Minute 16 Minute 8 Minute 4 Minute 2 Minute 1 Port at the port expander GPIOB3 GPIOB2 GPIOB1 GPIOB0 GPIOA5 GPIOA4 GPIOA3 GPIOA2 GPIOA1 GPIOA0 The connections for the address wires and the MCP23017 are identical to the previous experiment. The program binaeruhr.py is very simple because the port expander itself processes binary data. #!/usr/bin/python import time, smbus DEVICE = 0x20 IODIRA = 0x00 IODIRB = 0x01 GPIOA = 0x12 GPIOB = 0x13 bus = smbus.smbus(1) bus.write_byte_data(device,iodira,0x00) bus.write_byte_data(device,iodirb,0x00) bus.write_byte_data(device,gpioa,0x00) bus.write_byte_data(device,gpiob,0x00)

120 Binary clock m1 = 60 while True: zeit = time.localtime() m = zeit.tm_min h = zeit.tm_hour if h > 12: h = h 12 if m1 <> m: bus.write_byte_data(device,gpiob,h) bus.write_byte_data(device,gpioa,m) m1 = m time.sleep(1) 16.1 How it works The initialization of the I2C bus is very similar to the previous experiments. This time, however, both GPIO interfaces of the port expander are used. DEVICE = 0x20 IODIRA = 0x00 IODIRB = 0x01 GPIOA = 0x12 GPIOB = 0x13 I2C device address of the port expander 8-bit register to specify the direction (output/input) of the GPIOA port 8-bit register to specify the direction (output/input) of the GPIOB port 8-bit data register of the GPIOA port 8-bit data register of the GPIOB port The program is executed in an infinite loop that regularly reads the current time of the Raspberry Pi. If the new minute value is different from the minute value currently represented by the LEDs, then other LEDs will be turned on.

121 16.1 How it works 121 while True: zeit = time.localtime() In each iteration, the current time is written to the zeit object by the function time.localtime() of the time library. The result is a data structure consisting of several individual values. m = zeit.tm_min h = zeit.tm_hour The two relevant values for the digital clock, minutes and hours, are taken from the structure and written to the variables m and h. if h > 12: h = h 12 If the hour value is greater 12, we subtract 12 so that we can save the time in the 12 hour format in the variable h. if m1 <> m: bus.write_byte_data(device,gpiob,h) bus.write_byte_data(device,gpioa,m) m1 = m When the current minute m is different from the previously shown minute m1, the hour and the minute are written to the GPIOB port and the GPIOA port, respectively. We can directly use the numerical values, as the port expander converts them automatically to the binary numbers that are written to the ports. Now m1 is set to the currently shown minute. Before the loop is run for the first time, m1 is set to the value 60 that can never be reached in operation. This ensures that already in the first iteration, a new time is determined and represented by the LEDs. time.sleep(1) At the end of the loop, the program waits for one second in order to prevent that the loop is called every fragment of a second, as that would strain the processor so much that you could not use the Raspberry Pi for anything else but this program.

122 Binary clock 16.2 Binary clock and LCD clock The binary clock only requires the Raspberry Pi GPIO ports 2 and 3 to control the port expander via the I2C bus. The other GPIO ports are not used. This also comprises the ports that we used to control the LC display in previous experiments. Therefore we can combine both circuits and merge the programs so that the current time is shown simultaneously on the binary clock and on the LC display. For this circuit you need nearly all the components in the kit. Two different power supplies In particular pay attention to the correct connection of the power supply, as this circuit uses both power supply lines of the Raspberry Pi: +3.3 V for the port expander and +5 V for the LC display. Figure 16.4: Binary clock with additional LC display Required components: 3 x breadboard, 1 x MCP23017 port expander, 1 x LC display, 1 x 560 W resistor (green-blue-brown), 1 x potentiometer, 2 x red LED, 2 x orange LED, 2 x yellow LED, 2 x green LED, 2 x blue LED, 10 x 220 W resistor (red-red-brown), 11 x connection cable, 25 wire bridges (different lengths)

123 16.2 Binary clock and LCD clock Figure 16.5: Binary clock with MCP23017 port expander and LC clock in a combined circuit How it works The program binaer-lcd-uhr.py combines the binary clock and the LCD clock programs. #!/usr/bin/python import RPi.GPIO as GPIO import time, subprocess, smbus 123

124 Binary clock LCD_RS = 25 LCD_E = 24 LCD_D4 = 23 LCD_D5 = 17 LCD_D6 = 27 LCD_D7 = 22 GPIO.setmode(GPIO.BCM) GPIO.setup(LCD_E, GPIO.OUT) GPIO.setup(LCD_RS, GPIO.OUT) GPIO.setup(LCD_D4, GPIO.OUT) GPIO.setup(LCD_D5, GPIO.OUT) GPIO.setup(LCD_D6, GPIO.OUT) GPIO.setup(LCD_D7, GPIO.OUT) LCD_WIDTH = 16 LCD_LINE_1 = 0x80 LCD_LINE_2 = 0xC0 LCD_CHR = True LCD_CMD = False E_PULSE = E_DELAY = pause = 2 def lcd_enable(): time.sleep(e_delay) GPIO.output(LCD_E, True) time.sleep(e_pulse) GPIO.output(LCD_E, False) time.sleep(e_delay) def lcd_byte(bits, mode): GPIO.output(LCD_RS, mode) GPIO.output(LCD_D4, bits&0x10==0x10) GPIO.output(LCD_D5, bits&0x20==0x20) GPIO.output(LCD_D6, bits&0x40==0x40) GPIO.output(LCD_D7, bits&0x80==0x80) lcd_enable() GPIO.output(LCD_D4, bits&0x01==0x01) GPIO.output(LCD_D5, bits&0x02==0x02) GPIO.output(LCD_D6, bits&0x04==0x04) GPIO.output(LCD_D7, bits&0x08==0x08) lcd_enable() def lcd_string(message): message = message.ljust(lcd_width, ") for i in range(lcd_width): lcd_byte(ord(message[i]),lcd_chr)

125 16.2 Binary clock and LCD clock 125 def lcd_anzeige(z1, z2): lcd_byte(lcd_line_1, LCD_CMD) lcd_string(z1) lcd_byte(lcd_line_2, LCD_CMD) lcd_string(z2) LCD_INIT = [0x33, 0x32, 0x28, 0x0C, 0x06, 0x01] for i in LCD_INIT: lcd_byte(i,lcd_cmd) DEVICE = 0x20 IODIRA = 0x00 IODIRB = 0x01 GPIOA = 0x12 GPIOB = 0x13 bus = smbus.smbus(1) bus.write_byte_data(device,iodira,0x00) bus.write_byte_data(device,iodirb,0x00) bus.write_byte_data(device,gpioa,0x00) bus.write_byte_data(device,gpiob,0x00) m1 = 60 try: while True: zeit = time.localtime() m = zeit.tm_min h = zeit.tm_hour if h > 12: h = h 12 if m1 <> m: bus.write_byte_data(device,gpiob,h) bus.write_byte_data(device,gpioa,m) m1 = m zeile1 = time.asctime() zeile2 = "IP: + subprocess.check_output(["hostname, -I ])[:-2] lcd_anzeige(zeile1, zeile2) time.sleep(pause) except KeyboardInterrupt: GPIO.cleanup() This program does not contain any new features. After initialization of the display, it initializes the I2C bus. The main loop contains the familiar routines for the time representation of the binary clock and of the LC display clock.

126 17 CPU load gauge with LEDs at the port expander The next experiment turns eight LEDs into a CPU load gauge. Figure 17.1: CPU load gauge Set up the circuit as shown in the picture. It is similar to the circuit of the first port expander experiment as you also connect eight LEDs to the eight pins of the GPIOA interface. Required components: 2 x breadboard, 1 x MCP23017 port expander, 2 x red LED, 2 x yellow LED, 2 x green LED, 2 x blue LED, 8 x 220 W resistor (red-red-brown), 4 x connection cable, 15 x wire bridges (different lengths)

127 Figure 17.2: CPU load gauge with MCP23017 port expander According to the CPU load, one to eight LEDs light up. The program is based on the chaser lights program, but additionally contains some interesting function to calculate the CPU load. cpu.py #!/usr/bin/python import time, os, smbus DEVICE = 0x20 IODIRA = 0x00 GPIOA = 0x12 bus = smbus.smbus(1) bus.write_byte_data(device,iodira,0x00) bus.write_byte_data(device,gpioa,0x00) while True: cpu1 = os.popen("vmstat 1 3 ).readlines() cpu2 = 2 ** int((100 int(cpu1[4].split()[14])) * 0.08) 1 bus.write_byte_data(device,gpioa,cpu2)

128 CPU load gauge with LEDs at the port expander 17.1 How it works You are already familiar with the first code lines that initialize the I2C bus. Additionally, we import the os module to access the system function. while True: cpu1 = os.popen( vmstat 1 3 ).readlines() The program runs in an infinite loop. In every iteration, this loop calls the Linux command vmstat 1 3 in order to read system status information. The parameter 3 means that the status data are read three times. The first reading may be biased as the call of the vmstat command itself uses up some of the system performance. The os.popen() function writes the result of a Linux command line by line to an array of strings, in this case to the variable cpu1. Figure 17.3: Output of the vmstat 1 3 command in a Terminal window The next line uses an interesting formula to determine the value to be displayed by the LEDs, and saves it in the variable cpu2. cpu2 = 2 ** int((100 int(cpu1[4].split()[14])) * 0.08) 1 The third status query is placed behind the two table headings in the fifth line und thus in the fifth element of the array. As counting begins with 0, this element is labeled as number 4. cpu1[4].split() The split() method splits the string at the spaces and turns it into individual shorter strings. Note element no. [14] that comprises the content of the id column and thus indicates the percentage of idle CPU time.

129 17.1 How it works int(cpu1[4].split()[14]) Subtracting this value from 100 gives the percentage of the used CPU time, i. e. the CPU load. Before we can do this calculation we have to use the int() function to convert the string into an integer. (100 int(cpu1[4].split()[14])) * 0.08) Multiplication by 0.08 results in a number from 0 to 8 instead of 0 to100 so that we can represent the value by eight LEDs. For the representation via the port expander we need 8-bit numbers. In the case of a gauge, the LEDs have to light up in form of a continuous row. The following table shows the numbers from 0 to 8 and their binary representation as a continuous series of 1s. Binary Decimal Calculation formula ** ** ** ** ** ** ** ** ** 8 1 With the formula in the right column of the table we determine the binary values for controlling the respective LEDs. In Python, the sign ** represents the exponential function. bus.write_byte_data(device,gpioa,cpu2) The result that is saved in the variable cpu2 is written to the GPIOA port of the port expander and displayed by the LEDs. After that, the infinite loop restarts and again determines the current CPU load.

130 18 LC display at the port expander Depending on the mode, the LC display uses four or eight data wires to receive binary data. The port expander features two times eight data wires to send binary data. This lends itself to connecting the LC display to the port expander. Apart from the power supply, you then only need two wires for the I2C bus instead of six or ten GPIO ports to attach the LC display to the Raspberry Pi. Figure 18.1: LC display connected to the Raspberry Pi via the port expander For the connection to the port expander the 8-bit mode of the LC display is recommended. In this mode, the characters are written to the display byte by byte and not as two blocks. This significantly simplifies programming. The eight data wires of the GPIOA port of the port expander are connected in a straight line to the data wires of the LC display. Two of the wires at the GPIOB port are used for the RS and E control signals.

131 Required components: 2 x breadboard, 1 x MCP23017 port expander, 1 x LC display, 1 x 560 W resistor (green-blue-brown), 1 x potentiometer, 5 x connection cable, 23 x wire bridges (different lengths) Figure 18.2: LC display at the port expander In particular pay attention to the correct connection of the power supply, as this circuit uses both power supply lines of the Rasp berry Pi: +3.3 V for the port expander and +5 V for the LC display. Two different power supplies

132 LC display at the port expander The program i2c_display.py uses the basic structure of the status.py status display program, but some of the port expander control functions have been adapted. Additionally, it contains the familiar initialization routines for the I2C bus, but the initialization of the GPIO interface is omitted. #!/usr/bin/python import time, smbus, subprocess DEVICE = 0x20 IODIRA = 0x00 IODIRB = 0x01 GPIOA = 0x12 GPIOB = 0x13 LCD_WIDTH = 16 LCD_LINE_1 = 0x80 LCD_LINE_2 = 0xC0 LCD_CHR = 1 LCD_CMD = 0 LCD_RS = 0x02 LCD_E = 0x01 E_PULSE = E_DELAY = pause = 2 def lcd_byte(bits, mode): bus.write_byte_data(device,gpiob,lcd_rs*mode) bus.write_byte_data(device,gpioa,bits) time.sleep(e_delay) bus.write_byte_data(device,gpiob,lcd_e+lcd_rs*mode) time.sleep(e_pulse) bus.write_byte_data(device,gpiob,lcd_rs*mode) time.sleep(e_delay) def lcd_string(message): message = message.ljust(lcd_width, ") for i in range(lcd_width): lcd_byte(ord(message[i]),lcd_chr) def lcd_anzeige(z1, z2): lcd_byte(lcd_line_1, LCD_CMD) lcd_string(z1) lcd_byte(lcd_line_2, LCD_CMD) lcd_string(z2)

133 18.1 How it works 133 bus = smbus.smbus(1) bus.write_byte_data(device,iodira,0x00) bus.write_byte_data(device,iodirb,0x00) bus.write_byte_data(device,gpioa,0x00) bus.write_byte_data(device,gpiob,0x00) LCD_INIT = [0x33, 0x32, 0x38, 0x0C, 0x06, 0x01] for i in LCD_INIT: lcd_byte(i,lcd_cmd) while True: zeile1 = time.asctime() zeile2 = "IP: + subprocess.check_output(["hostname, -I ])[:-2] lcd_anzeige(zeile1, zeile2) time.sleep(pause) 18.1 How it works First we import the following modules: smbus for the I2C bus, time and subprocess, that is required for the status display. The GPIO library is not required. You are already familiar with the constants for the port expander. The constants for the LC display remain mostly unchanged, in order to limit the required changes of the program code to a bare minimum. LCD_RS = 0x02 LCD_E = 0x01 The signals LCD_RS (Register Select) and LCE_E (Enable) are now no longer GPIO pins, but bit codes that are sent to the respective control wires of the LC display via the GPIOB port. The former constant for the four or eight data wires and the initialization of the GPIO ports are omitted. The most significant changes take place in the lcd_byte() function, that has been merged with the former lcd_enable() function for convenience.

134 LC display at the port expander def lcd_byte(bits, mode): The function call remains compatible to the original program so that we do not have to change the main program. The lcd_byte() function is still passed two parameters. In the parameter bits, the function receives the byte to send, while the parameter mode indicates if this byte is a character or a control command. The two possible values for mode are defined in the constants LCD_CHR (character) and LCD_CMD (control command). bus.write_byte_data(device,gpiob,lcd_rs*mode) First, the display is set to command mode or character mode. To this end the bit pattern for the second GPIOB port bit (0x02) in LCD_ RS is multiplied by the parameter mode, which can be 0 or 1. Thus the command mode bit is turned off and the character mode bit is turned on. bus.write_byte_data(device,gpioa,bits) This line writes to the GPIOA port the byte that has to be sent to the display. When using the port expander we do not have to convert the characters to bit code. time.sleep(e_delay) bus.write_byte_data(device,gpiob,lcd_e+lcd_rs*mode) Now the display needs the Enable signal, i. e. a change from 0 to 1 on the E line, in order to read and write data on the data wires. After a short delay to overcome the inertness of the display the first bit of the GPIOB port (that is defined in the LCD_E constant) is set to 1. On the port expander, we issue one complete byte after the other. This means that the previously set mode must not be altered. Therefore, this mode is added to the LCD_E value and sent again. time.sleep(e_pulse) bus.write_byte_data(device,gpiob,lcd_rs*mode) After a short delay, the LCD_E bit is reset to 0. In order to do this the function simply sends the current mode 0x02 or 0x00 to the display. In these values, the LCD_E bit is automatically set to 0.

135 18.1 How it works 135 time.sleep(e_delay) Similar to the original program we now have a short delay so that no new data can get to the display until the current data are properly displayed. The lcd_string() and lcd_anzeige() functions do not directly access the hardware of the LC display and can thus remain unchanged. bus = smbus.smbus(1) bus.write_byte_data(device,iodira,0x00) bus.write_byte_data(device,iodirb,0x00) bus.write_byte_data(device,gpioa,0x00) bus.write_byte_data(device,gpiob,0x00) After defining the functions, the actual program begins with the familiar initialization of the I2C bus and the two port expander interfaces GPIOA and GPIOAB. LCD_INIT = [0x33, 0x32, 0x38, 0x0C, 0x06, 0x01] This time the initialization string for the display contains the 0x38 code for the 8-bit mode. The loop to initialize the display and the main loop of the program remain unchanged as they do not directly access the LC display hardware but only via functions.

136 19 LC display for Raspberry media center Figure 19.1: Main menu of the xbmc media center The performance of the Raspberry Pi is sufficient to play videos in HD quality. The Raspbmc software ( turns your Rapsberry Pi into a convenient media center for your living room. The program is based von xbmc, a well-known PC media center. Raspbmc is based on Raspbian, but uses its own graphical i nterface that is optimized for the display on a TV set and can be controlled by mouse and keyboard as well as with a wireless remote. Raspbmc does not run on the normal LXDE Raspbian desktop, but needs a bootable memory card of its own. The media data can be

137 provided on the same card, a USB stick, an attached external hard disk, a network drive or a cloud service. In addition to the graphical interface, an additional Raspbmc module provides the possibility to show the running tracks and other information on an LC display. Raspbmc is one of the available options in the NOOBS operating system installer. After completing the installation, the Raspberry Pi shows the xbmc interface. In a first step, you have to select the language. Do not be surprised when the operation seems to be a bit jerky. After the initial launch Raspbmc automatically downloads and installs updates which puts a high load on the CPU. Just wait a minute until you select the language. When you have done that, the main menu of xbmc appears. On the right-hand side, click System, and under Settings > Appearance > International select your region and time zone so that the clock runs correctly. The language has already been set in the first step. Figure 19.2: Language and region settings

138 LC display for Raspberry media center Back to the main screen As the operation of xbmc is mostly self-explanatory we will not go into the details. You cannot get lost in the nested dialogs. Each of the screens shows two icons in the bottom right corner: The arrow takes you back one level, while the house icon calls the main menu. When you go back, all changes are saved automatically. Xbmc adjusts most of the settings automatically in accordance to the attached hardware. However, it may be necessary to manually change the audio settings when you use a computer monitor with a DVI connection and you do not hear a sound when playing videos or music. When there is a monitor connected to the HDMI port, the Raspberry Pi always tries to play the audio signal via this port, although this is not possible with a DVI monitor. For a monitor of this kind you need external speakers attached via 3.5 mm stereo connectors. Figure 19.3: Audio settings in xbmc To change the audio settings, click System > Settings in the main menu. At the bottom of the Settings dialog select System, and in the next window select Audio Output. Set the audio output to Analog, when you have connected external loudspeakers or headphones to the Raspberry Pi.

139 19.1 Connecting the display Connecting the display The LC display is connected directly to the Raspberry Pi in 4-bit mode and without a port expander. We use the same GPIO ports as in the Python and Scratch experiments. Figure 19.4: Yellow: control wires; purple: data wires; red: +5 V; blue: ground

140 LC display for Raspberry media center Required parts: 1 x breadboard, 1 x LC display, 1 x 560 W resistor (green-blue-brown) 1 x potentiometer, 8 x connection cable, 6 x wire bridge (different lengths) 19.2 Configuring the drivers Exit the xbmc media center by clicking the house symbol in the bottom right corner and then click the On/Off button in the bottom left corner of the main menu. On the next screen, click Exit. Now you see a blue text mode screen. Press (Esc) to view the classic Linux login screen. Log in with the user name pi and the password raspberry. At first login a configuration script is automatically launched. Like raspi-config it queries the language and time zone to be used in the command line mode. At the command line, download and install the LCD add-on for xbmc and LCDproc driver software: sudo wget archive/master.zip --no-check-certificate sudo wget sudo bash lcd-install Now you have to adjust the LCDd.conf configuration file to the display and the GPIO ports. This file is very long and the lines to change are not easy to find. In order to help you finding them, the following illustrations show the whole Terminal window and the cursor position (highlighted by pressing (Ctrl) + (C). It is of course possible that the file looks different from the screenshots due to updates or additionally imported modules. The import elements are the parameters and the section names in brackets. sudo nano /etc/lcdd.conf

141 19.2 Configuring the drivers 141 In the [server] section you can find all of the supported drivers. Enter the parameter hd44780 into the line Driver=. This is the short name of the LC display included in the kit. Figure 19.5: The entry for the display type Press (Ctrl) + (W) to search for the section [hd44780]. Here the parameter rpi has to be present in the line ConnectionType.

142 LC display for Raspberry media center Figure 19.6: The section for the HD44780 driver A few lines further down the display size (here 16x2) and the used GPIO ports are entered. The following table shows how to connect the signal wires of the LC display to the Raspberry Pi so that you can use the circuit in the same way as in the Python and Scratch experiments. The file contains a different default pin assignment. Display pin Signal Raspberry Pi GPIO 4 RS GPIO 25 6 EN GPIO D4 GPIO D5 GPIO D6 GPIO D7 GPIO 22

143 19.3 Configuration in xbmc 143 Figure 19.7: Enter the actually used GPIO ports in these lines Exit the editor by pressing (Ctrl) + (X) and save the changes. Restart the Raspberry Pi: sudo reboot 19.3 Configuration in xbmc After restarting xbmc, click System > Settings > Add-ons. Under Get Add-ons/Services, select and install the XBMC LCDproc add-on.

144 LC display for Raspberry media center Figure 19.8: The XBMC LCDproc add-on in the add-on catalog of xbmc The installation of the LCDproc add-on is fully automated. After its completion the display immediately shows current text messages. When you play a song, you see the names of the track and the artist on the LC display Figure 19.9: xbmc track display on the LCD screen

145 19.3 Configuration in xbmc 145 Select System > Settings > Add-ons > Enabled Add-ons > Services to open the configuration dialog for the LDCproc add-on. Here you can adjust several display parameters like the marquee speed or the display duration of the navigation view. Figure 19.10: The info and configuration screen of the LCDproc add-on

146 20 PiKey PiKey Controlling games with your fingers Wouldn t it be great to control a game simply by touching homemade sensor buttons? With our last project PiKey PiKey this becomes possible! Figure 20.1: Home-made sensor buttons for controlling a game Sensor buttons work according to a simple principle: The GPIO ports are connected to +3.3 V via resistors with an extremely high resistance value (22 MW) so that a weak but definite GPIO.High signal is present. A human being (if not levitating in mid-air) is always grounded and provides a GPIO.Low signal via the electrically conductive skin.

147 When this human being touches a sensor contact, the weak GPIO. High signal is superimposed by the significantly stronger GPIO.Low signal of the finger tip and sets the respective GPIO pin to GPIO.Low. Figure 20.2: Circuit diagram of the PiKey PiKey contact sensors Setup the circuit as shown on two breadboards. In addition to the insulated jumper wire you also need bare wire, shown gray in the figure. Completely remove the insulation of a piece of jumper wire with a sharp knife, or simply use a piece of copper or silver wire that can be found in every tinkerer s home. Bend the bare wire into the shape of the contact sensors for four arrow keys and two rectangular buttons. The long wire at the bottom is connected to ground (0 V). Touch this wire before you use the contact sensors in order to ground yourself. This is to avoid that excess voltages by static electricity reach the GPIO pins. For the same reason you should not unnecessarily touch the GPIO pins when the Raspberry Pi is turned on. Required components: 2 x breadboard, 1 x red LED, 1 x 220 W resistor (red-red-brown), 6 x 22 MW resistor (red-red-blue), 9 x connection cable, 7 x wire bridge (different lengths), 7 x bare wire (different lengths)

148 PiKey PiKey: Controlling games with your fingers Figure 20.3: PiKey PiKey with contact sensors (gray)

149 20 PiKey PiKey: Controlling games with your fingers 149 First you have to install a few modules that are not included in the Raspbian standard distribution. Just call the following Linux commands in LXTerminal: sudo apt-get update sudo apt-get install python-setuptools python-xlib sudo git clone cd PyUserInput sudo python setup.py install Now you can call the program PiKeyPiKey_led.py. It runs in the background, and at the first glance does not seem to do anything at all. By means of the Python module PyKeyboard it simulates keyboard inputs at the GPIO ports so that you can control games and other programs. #!/bin/python import RPi.GPIO as GPIO from pykeyboard import PyKeyboard import time GPIO.setmode(GPIO.BCM) K1 = 7 K2 = 8 K3 = 9 K4 = 10 K5 = 11 K6 = 25 L1 = 24 gpio_in = {K1, K2, K3, K4, K5, K6} gpio_old = {K1:0, K2:0, K3:0, K4:0, K5:0, K6:0} k = PyKeyboard() pause = 0.01 for gpio in gpio_in: GPIO.setup(gpio, GPIO.IN) GPIO.setup(L1, GPIO.OUT) while True: time.sleep(pause)

150 PiKey PiKey: Controlling games with your fingers if GPIO.input(K1) == 0 and gpio_old[k1] == 1: k.press_key(k.enter_key) gpio_old[k1] = 0 elif GPIO.input(K1) == 1 and gpio_old[k1] == 0: k.release_key(k.enter_key) gpio_old[k1] = 1 if GPIO.input(K2) == 0 and gpio_old[k2] == 1: k.press_key( ) gpio_old[k2] = 0 elif GPIO.input(K2) == 1 and gpio_old[k2] == 0: k.release_key( ) gpio_old[k2] = 1 if GPIO.input(K3) == 0 and gpio_old[k3] == 1: k.press_key(k.down_key) gpio_old[k3] = 0 elif GPIO.input(K3) == 1 and gpio_old[k3] == 0: k.release_key(k.down_key) gpio_old[k3] = 1 if GPIO.input(K4) == 0 and gpio_old[k4] == 1: k.press_key(k.right_key) gpio_old[k4] = 0 elif GPIO.input(K4) == 1 and gpio_old[k4] == 0: k.release_key(k.right_key) gpio_old[k4] = 1 if GPIO.input(K5) == 0 and gpio_old[k5] == 1: k.press_key(k.left_key) gpio_old[k5] = 0 elif GPIO.input(K5) == 1 and gpio_old[k5] == 0: k.release_key(k.left_key) gpio_old[k5] = 1 if GPIO.input(K6) == 0 and gpio_old[k6] == 1: k.press_key(k.up_key) gpio_old[k6] = 0 elif GPIO.input(K6) == 1 and gpio_old[k6] == 0: k.release_key(k.up_key) gpio_old[k6] = 1 LED = 0 for gpio in gpio_in: LED = LED or (not GPIO.input(gpio)) GPIO.output(L1, LED)

151 20.1 How it works 151 Supertux (supertux.lethargik.org) is a popular platform game for Linux that can be controlled by the cursor keys and the space bar. The PiKeyPiKey_led.py program uses the input from the contact sensors to emulate these keys. Figure 20.4: The platform game Supertux Install the game: sudo apt-get install supertux Start the PiKeyPiKey_led.py Python program with root privileges for the GPIO access and then launch the game. Instead of using the keyboard and the mouse you can control the game now with the PiKey PiKey contact sensors How it works This program is similar to the previous GPIO experiments, but it contains some significant alterations, in particular due to the PyKeyboard module.

152 PiKey PiKey: Controlling games with your fingers #!/bin/python import RPi.GPIO as GPIO from pykeyboard import PyKeyboard import time This module is imported together with the modules RPi.GPIO for the GPIO interface and time for controlling waiting times. GPIO.setmode(GPIO.BCM) K1 = 7 K2 = 8 K3 = 9 K4 = 10 K5 = 11 K6 = 25 L1 = 24 The GPIO addressing is set to BCM mode as usual. Then the six GPIO port numbers used for the sensor buttons are defined in the constants K1 to K6. The GPIO port for the LED is specified in the constant L1. gpio_in = [K1, K2, K3, K4, K5, K6] The gpio_in[] array contains the previously defined GPIO port numbers of the six inputs for use with loops where arrays are much easier to use than individual variables. gpio_old = {K1:0, K2:0, K3:0, K4:0, K5:0, K6:0} In order to save the previous values of the GPIO inputs we define the variable gpio_old{}. This is a dictionary, a special type of list. The individual elements in a dictionary are not accessed by an index number, but by a so called key which can be any word. In this case the key is the constant that contains the GPIO port number. In contrast to a basic list, a dictionary is written in braces. It can contain any number of key/value pairs. At the beginning of the program, all values are set to 0. k = PyKeyboard() The variable k is assigned a data structure that contains all inputs of the simulated keyboard PyKeyboard(). The individual elements of this structure represent the buttons that will be pressed later.

153 20.1 How it works 153 pause = 0.01 In order to avoid misreadings due to keybounce, a delay of 0.1 s is defined. for gpio in gpio_in: GPIO.setup(gpio, GPIO.IN) All the ports in the gpio_in[] array are defined as input. GPIO.setup(L1, GPIO.OUT) The GPIO port for the LED is defined as output. while True: time.sleep(pause) Now an infinite loop starts. Every iteration begins with a short delay to suppress keybounce. if GPIO.input(K1) == 0 and gpio_old[k1] == 1: k.press_key(k.enter_key) gpio_old[k1] = 0 In every iteration the six contact sensors are queried one by one. The signal 0 at the GPIO input K1 means that the user is touching the contact. If the respective field in gpio_old{} contains the value 1, the user has just touched the contact. This state is evaluated by the k.press_key() method of the data structure as a key press, and the respective key value, in this case k.enter_key for the (Enter) key, is passed to the operating system or the running program. Subsequently the gpio_old[] value for this contact sensor is set to 0 as the sensor has been touched. As long as the sensor is being touched, this query does no longer react. No further key presses are passed. elif GPIO.input(K1) == 1 and gpio_old[k1] == 0: k.release_key(k.enter_key) gpio_old[k1] = 1 When a GPIO input was previously touched, the respective field of gpio_old{} has the value 0. If it is now no longer touched and thus has the value 1, then this state will be interpreted as releasing the

154 PiKey PiKey: Controlling games with your fingers button. In this case the k.release_key() method tells the operating system that the (Enter) key has been released. The same query is executed for the remaining five contact sensors. PyKeyboard can directly process alphanumerical keys as strings, e. g. the (Spacebar) for GPIO port K2. Control characters are represented by key words. The following table shows the keys used in the program. Program variable Key Code K1 (Enter) enter_key K2 (Spacebar) K3 [¼] down_key K4 [Æ] right_key K5 [æ] left_key K6 [½] up_key After querying all of the six contact sensors, the LED has to light up when a contact is touched. LED = 0 for gpio in gpio_in: LED = LED or (not GPIO.input(gpio)) GPIO.output(L1, LED) At first the LED variable is set to 0. The LED should only light up when one of the contacts gets touched. The GPIO ports are queried in a loop. If one of the ports does not supply the value 1, the LED variable is set to 1. The OR conjunction prevents that the LED is immediately set back to 0, when the next queried port has the value 1, i. e. when the respective sensor is not being touched and thus supplies a GPIO. High signal via the resistor connected to +3.3 V. At the end of the loop, the GPIO output defined as L1 is set to the value of the LED variable. With the value 1, the LED lights up. Subsequently the main loop starts again. This loop is executed very fast, and at its end, the LED is set back to 0. Therefore, the lighting up of the LED can only be perceived as a short flashing.

155 20.2 Tea spoons as ground and boss key Tea spoons as ground and boss key The ground connection via the floor is not always sufficient to use PiKey PiKey. Carpets and synthetics floors or even some types of shoe soles insulate so well that your fingers do not supply a sufficient GPIO. Low signal without touching the ground wire. If you sit on a stone floor with your bare feet, there will be no problems. With alligator clips and tea spoons or other conductive household items you can add a solid grounding and a boss key. This key can be used to quickly exit the game when the boss arrives. Ground yourself by grabbing one of the tea spoons. With the other hand, you play as usual. When the boss enters, touch the other tea spoon a few times consecutively until the game ends. Figure 20.5: Two tea spoons as grounding and boss key Attach one of the alligator clips to the ground wire at the bottom and the other one to the pin that is connected with the up-arrow key. Then clamp each of the alligator clips to a tea spoon. In the Supertux game, you can use the menu item Options > Keyboard Setup to define which keys are used for controlling the game. It is not necessary to change this assignment.

156 PiKey PiKey: Controlling games with your fingers Figure 20.6: Key assignment in Supertux Here you can clearly see that you need only five keys for playing the game. The up arrow is only used in the game menu and is thus expendable. When you press the down-arrow key often enough, the menu cycles back to the top. In this way you can reach every menu item even without an up-arrow key. However, the (Esc) key to quit the game cannot be redefined. In order to transfer this function to the up arrow and the attached tea spoon, you have to change the Python program. The last query in the infinite loop is in charge of the up-arrow key. Replace the k.up_key twice by k.escape_key. if GPIO.input(K6) == 0 and gpio_old[k6] == 1: k.press_key(k.escape_key) gpio_old[k6] = 0 elif GPIO.input(K6) == 1 and gpio_old[k6] == 0: k.release_key(k.escape_key) gpio_old[k6] = 1 This small change turns the arrow key into a boss key.

Gooligum Electronics 2015

Gooligum Electronics 2015 The Wombat Prototyping Board for Raspberry Pi Operation and Software Guide This prototyping board is intended to make it easy to experiment and try out ideas for building electronic devices that connect

More information

Raspberry Pi Activity 2: My Binary Addiction...Reloaded

Raspberry Pi Activity 2: My Binary Addiction...Reloaded The Science of Computing II Living with Cyber Raspberry Pi Activity 2: My Binary Addiction...Reloaded In this activity, you will re-implement the one-bit binary adder that was the subject of Raspberry

More information

Basic Electronics and Raspberry Pi IO Programming

Basic Electronics and Raspberry Pi IO Programming Basic Electronics and Raspberry Pi IO Programming Guoping Wang Indiana University Purdue University Fort Wayne IEEE Fort Wayne Section wang@ipfw.edu February 18, 2016 Table of Contents 1 Safety Guideline

More information

9 Output Devices: Buzzers

9 Output Devices: Buzzers 9 Output Devices: Buzzers Project In this project, you will learn how to connect and control LEDs (Light Emitting Diode) and a buzzer with the Raspberry Pi. Components In addition to your Raspberry Pi,

More information

Arduino 05: Digital I/O. Jeffrey A. Meunier University of Connecticut

Arduino 05: Digital I/O. Jeffrey A. Meunier University of Connecticut Arduino 05: Digital I/O Jeffrey A. Meunier jeffm@engr.uconn.edu University of Connecticut About: How to use this document I designed this tutorial to be tall and narrow so that you can read it on one side

More information

Raspberry Pi NTP Clock Setup Guide

Raspberry Pi NTP Clock Setup Guide Raspberry Pi NTP Clock Setup Guide Several steps are involved in getting your Raspberry Pi to operate as a NTP Clock. To begin with, you must obtain a LCD Plate (www.adafruit.com) and build it. You must

More information

CamJam EduKit Sensors Worksheet Five. Equipment Required. The Parts. The Passive Infrared Sensor

CamJam EduKit Sensors Worksheet Five. Equipment Required. The Parts. The Passive Infrared Sensor CamJam EduKit Sensors Worksheet Five Project Description Passive Infrared Sensor In this project, you will learn how to wire and program a passive infrared sensor that detects movement near it. Equipment

More information

TWO PLAYER REACTION GAME

TWO PLAYER REACTION GAME LESSON 18 TWO PLAYER REACTION GAME OBJECTIVE For your final project for this level for the course, create a game in Python that will test your reaction time versus another player. MATERIALS This lesson

More information

BCS Raspberry Pi Launch Events Getting started with Raspberry Pi

BCS Raspberry Pi Launch Events Getting started with Raspberry Pi BCS Raspberry Pi Launch Events Getting started with Raspberry Pi Department of Computer Science 16 th & 17 th April 2013 Who are you? How many of you.. are teachers in STEM subjects in non STEM subjects

More information

SF Innovations Ltd. User Instructions (5th January 2016) Contents. Introduction

SF Innovations Ltd. User Instructions (5th January 2016) Contents. Introduction SF Innovations Ltd Custard Pi 1 - Breakout Board with protection for the Raspberry Pi GPIO Custard Pi 1A - Breakout Board for the Raspberry Pi GPIO User Instructions (5th January 2016) Contents Introduction

More information

A Beginners Guide to Raspberry Pi

A Beginners Guide to Raspberry Pi A Beginners Guide to Raspberry Pi WHAT IS THE RASPBERRY PI? Features It is a low-cost, credit-card sized computer developed in the UK by the Raspberry Pi Foundation. It has been designed with education

More information

Experimental Procedure. Frequently Asked Questions (FAQ) Kit General Questions. Setting Up and Using Your Raspberry Pi Projects Kit

Experimental Procedure. Frequently Asked Questions (FAQ) Kit General Questions. Setting Up and Using Your Raspberry Pi Projects Kit 1 of 11 9/13/2018, 2:31 PM https://www.sciencebuddies.org/science-fair-projects/project-ideas/compsci_p059/computer-science/design-your-own-video-game (http://www.sciencebuddies.org/science-fairprojects/project-ideas/compsci_p059/computer-science/design-your-own-video-game)

More information

A Slice of Raspberry Pi

A Slice of Raspberry Pi A Slice of Raspberry Pi Roadmap Introduction to the Raspberry Pi device What can you use a Raspberry Pi for? Talking to the Hardware A Raspberry Pi Arcade table Q & A Raspberry Pi Introduction What is

More information

Ding Dong, You've Got Mail! A Lab Activity for Teaching the Internet of Things

Ding Dong, You've Got Mail! A Lab Activity for Teaching the Internet of Things Teaching Case Ding Dong, You've Got Mail! A Lab Activity for Teaching the Internet of Things Mark Frydenburg mfrydenberg@bentley.edu Computer Information Systems Department Bentley University Waltham,

More information

Manual of ET-LCD SW HAT

Manual of ET-LCD SW HAT ET- LCD SW HAT ET-LCD SW HAT is Board I/O that is specifically designed for connection with Board Raspberry Pi through Connector 40-PIN; this board includes LCD 16x2, SW, Buzzer, RTC DS3231 with Connector

More information

Custard Pi 5 - Breakout board with protection for 8 digital I/O and stacking connector for the Raspberry Pi GPIO

Custard Pi 5 - Breakout board with protection for 8 digital I/O and stacking connector for the Raspberry Pi GPIO SF Innovations Ltd Custard Pi 5 - Breakout board with protection for 8 digital I/O and stacking connector for the Raspberry Pi GPIO User Instructions (11th November 2016) Contents Introduction CE Compliance

More information

ENGR 210 Lab1. Ohm's Law

ENGR 210 Lab1. Ohm's Law ENGR 210 Lab1 Ohm's Law Background In the class lectures we have discussed the fundamental electrical quantities of voltage, current and resistance. Since these quantities are so important there are specialized

More information

SEAS Computing Facility Raspberry Pi Workshop 2: I/O Camera & Motion Sensor. October 21, 2017

SEAS Computing Facility Raspberry Pi Workshop 2: I/O Camera & Motion Sensor. October 21, 2017 SEAS Computing Facility Raspberry Pi Workshop 2: I/O Camera & Motion Sensor October 21, 2017 Overview for Today Learn about new components Program a push-button ON/OFF input system for LED Connect and

More information

Raspberry Pi GPIO Zero Reaction Timer

Raspberry Pi GPIO Zero Reaction Timer Raspberry Pi GPIO Zero Reaction Timer Tutorial by Andrew Oakley Public Domain 1 Feb 2016 www.cotswoldjam.org Introduction This Python programming tutorial, shows you how simple it is to use an LED light

More information

Experiments 1 How to set up Raspberry Pi B+ The little computer you can cook into DIY tech projects

Experiments 1 How to set up Raspberry Pi B+ The little computer you can cook into DIY tech projects Experiments 1 How to set up Raspberry Pi B+ The little computer you can cook into DIY tech projects The Raspberry Pi is a computer about the size of a credit card. The darling of the do-it-yourself electronics

More information

Windows XP. A Quick Tour of Windows XP Features

Windows XP. A Quick Tour of Windows XP Features Windows XP A Quick Tour of Windows XP Features Windows XP Windows XP is an operating system, which comes in several versions: Home, Media, Professional. The Windows XP computer uses a graphics-based operating

More information

Getting Started Guide XC9010 Raspberry Pi Starter Kit

Getting Started Guide XC9010 Raspberry Pi Starter Kit Getting Started Guide XC9010 Raspberry Pi Starter Kit The Raspberry Pi has been designed as a computer that anyone can use. If you want to get started with a Raspberry Pi, but don t know where to start,

More information

F28HS Hardware-Software Interface: Systems Programming

F28HS Hardware-Software Interface: Systems Programming F28HS Hardware-Software Interface: Systems Programming Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 2 2016/17 0 No proprietary software has

More information

Quick Reference Tables

Quick Reference Tables Quick Reference Tables Chapter 1 Raspberry Pi Startup Command Quick Reference Table Command startx sudo sudo shutdown -h now sudo shutdown -r now Launches the Raspbian desktop environment (GUI). Gives

More information

Connecting LEDs to the ADB I/O

Connecting LEDs to the ADB I/O Application Note AN-2 By Magnus Pettersson September 26 1996 Connecting LEDs to the I/O Introduction The following notes are for those of you who are a bit inexperienced with hardware components. This

More information

Theo. Miles. Olivia. Joseph. Nina. Kishan. The Richard Pate School, Cheltenham

Theo. Miles. Olivia. Joseph. Nina. Kishan. The Richard Pate School, Cheltenham Theo Miles Olivia Joseph Nina Kishan Summary We have developed a system to help old/disabled people answer the door, especially people who have difficulty walking or walk slowly. The system uses the Raspberry

More information

XLink Kai Raspberry Pi Beginners Tutorial

XLink Kai Raspberry Pi Beginners Tutorial XLink-Kai-Raspberry-Pi-Beginners-Tutorial.md XLink Kai Raspberry Pi Beginners Tutorial Hi! This tutorial will guide you through setting up XLink Kai on a Raspberry Pi to play multiplayer system link Xbox

More information

Adafruit's Raspberry Pi Lesson 1. Preparing an SD Card for your Raspberry Pi

Adafruit's Raspberry Pi Lesson 1. Preparing an SD Card for your Raspberry Pi Adafruit's Raspberry Pi Lesson 1. Preparing an SD Card for your Raspberry Pi Created by Simon Monk Last updated on 2013-07-08 12:15:38 PM EDT Guide Contents Guide Contents Overview You Will Need Downloading

More information

Raspberry Pi Setup Tutorial

Raspberry Pi Setup Tutorial Raspberry Pi Setup Tutorial The Raspberry Pi is basically a miniature linux- based computer. It has an ARM processor on it, specifically the ARM1176JZF- S 700 MHz processor. This is the main reason why

More information

Power over Ethernet (PoE) Adaptor

Power over Ethernet (PoE) Adaptor Power over Ethernet (PoE) Adaptor For the Raspberry Pi model B+, Pi2 and Pi3 User Manual www.circuitsurgery.com Page 1 of 6 Description N.B.: In this manual the term "Raspberry Pi" will refer to the Raspberry

More information

Setup: Scratch GPIO. What is Scratch? Introducing Scratch GPIO. How to install Scratch GPIO. Obtain Scratch GPIO

Setup: Scratch GPIO. What is Scratch? Introducing Scratch GPIO. How to install Scratch GPIO. Obtain Scratch GPIO Setup: Scratch GPIO What is Scratch? Scratch is a beginner friendly way to program the Raspberry Pi, designed for those who have not programmed before and are put off by the random keyboard mashing type

More information

Adafruit's Raspberry Pi Lesson 1. Preparing an SD Card for your Raspberry Pi

Adafruit's Raspberry Pi Lesson 1. Preparing an SD Card for your Raspberry Pi Adafruit's Raspberry Pi Lesson 1. Preparing an SD Card for your Raspberry Pi Created by Simon Monk Last updated on 2016-12-03 03:20:15 AM UTC Guide Contents Guide Contents Overview You Will Need Downloading

More information

E-Limitator (Kit) on to your game board or a suitable PC interface. General Advice for building a circuit

E-Limitator (Kit) on to your game board or a suitable PC interface. General Advice for building a circuit E-Limitator (Kit) Digital joysticks are divided by the number of directions that can be controlled with them. The most common are 2-, 4- and 8-way. It's uncommon that a developer has already built in a

More information

& Technical Specifications

& Technical Specifications User Manual & Technical Specifications User manual Contents Pidion BM-170 Technical specifications... 2 Micro Rolltalk basic package... 3 Micro Rolltalk functions and buttons... 3 Preparing Micro Rolltalk...

More information

RaspiDigiHamClock. Raspberry Pi Amateur Radio Digital Clock. v WA4EFH R.Grokett

RaspiDigiHamClock. Raspberry Pi Amateur Radio Digital Clock. v WA4EFH R.Grokett RaspiDigiHamClock Raspberry Pi Amateur Radio Digital Clock v2018-07-08 WA4EFH R.Grokett Overview Amateur Radio Operators (aka HAM Radio) use 24 hour UTC (Universal Coordinated Time) for much of their operation.

More information

Wireless USB 600AC USER MANUAL. Dual Band USB Adapter. HNW600ACU Rev

Wireless USB 600AC USER MANUAL. Dual Band USB Adapter. HNW600ACU Rev Wireless USB 600AC Dual Band USB Adapter USER MANUAL HNW600ACU Rev. 2.0 www.hamletcom.com Table of Contents 1. Introduction... 4 1.1 Product Features... 4 1.2 Package contents... 4 2. Wireless USB Adapter

More information

Wi-Fi 300N USER MANUAL. Nano USB Adapter HNWU300NN.

Wi-Fi 300N USER MANUAL. Nano USB Adapter HNWU300NN. Wi-Fi 300N Nano USB Adapter USER MANUAL HNWU300NN www.hamletcom.com Table of Contents 1. Introduction... 4! 1.1 Product Features... 4! 1.2 Package contents... 4! 2. Wireless USB Adapter Installation...

More information

Point of View SmartTV-500 Center - Android 4.2. General notices for use...2 Disclaimer...2 Box Contents...2

Point of View SmartTV-500 Center - Android 4.2. General notices for use...2 Disclaimer...2 Box Contents...2 Point of View SmartTV-500 Center - Android 4.2 English Table of Contents General notices for use...2 Disclaimer...2 Box Contents...2 1.0 Product basics...3 1.1 Buttons and connections... 3 1.2 Connecting

More information

StenBOT Robot Kit. Stensat Group LLC, Copyright 2018

StenBOT Robot Kit. Stensat Group LLC, Copyright 2018 StenBOT Robot Kit 1 Stensat Group LLC, Copyright 2018 Legal Stuff Stensat Group LLC assumes no responsibility and/or liability for the use of the kit and documentation. There is a 90 day warranty for the

More information

AlaMode User Manual Revision

AlaMode User Manual Revision AlaMode User Manual Revision 1.0 www.wyolum.com info@wyolum.com 1 Introduction The AlaMode is an integrated Arduino compatible board. It is designed as versatile, general purpose data acquisition and control

More information

Micro-Controllers. Module 2: Outputs Control and Inputs Monitoring. IAT Curriculum Unit PREPARED BY. August 2008

Micro-Controllers. Module 2: Outputs Control and Inputs Monitoring. IAT Curriculum Unit PREPARED BY. August 2008 Micro-Controllers Module 2: Outputs Control and Inputs Monitoring PREPARED BY IAT Curriculum Unit August 2008 Institute of Applied Technology, 2008 2 Module 2: Outputs Control and Inputs Monitoring Module

More information

Build the Machine Science XBoard, with a programmable microcontroller.

Build the Machine Science XBoard, with a programmable microcontroller. Build the Machine Science XBoard, with a programmable microcontroller. Site: icode Course: Machine Science Guides Book: Assembling the XBoard Printed by: Guest User Date: Monday, May 24, 2010, 10:46 AM

More information

RaRa Academy: Raspberry Pi. Karl Heinz Kremer - K5KHK

RaRa Academy: Raspberry Pi. Karl Heinz Kremer - K5KHK RaRa Academy: Raspberry Pi Karl Heinz Kremer - K5KHK Why Are We Here? I cannot convert you into a Raspberry Pi (or Linux) expert in two hours I cannot teach you everything there is to know about using

More information

SCRATCH. Introduction to creative computing with Scratch 2.0

SCRATCH. Introduction to creative computing with Scratch 2.0 SCRATCH Introduction to creative computing with Scratch 2.0 What is Scratch? Scratch is a visual programming language that allows you to create your interactive stories, games and animations by using blocks

More information

Zero2Go. User Manual (revision 1.03) Wide Input Range Power Supply for Your Raspberry Pi. Copyright 2017 UUGear s.r.o. All rights reserved.

Zero2Go. User Manual (revision 1.03) Wide Input Range Power Supply for Your Raspberry Pi. Copyright 2017 UUGear s.r.o. All rights reserved. Zero2Go Wide Input Range Power Supply for Your Raspberry Pi User Manual (revision 1.03) Copyright 2017 UUGear s.r.o. All rights reserved. Table of Content Product Overview... 1 Product Details... 3 Package

More information

RETROPIE INSTALLATION GUIDE

RETROPIE INSTALLATION GUIDE RETROPIE INSTALLATION GUIDE CONTENTS THE FOLLOWING GUIDE WILL COVER THE INSTALLATION, SETUP AND CONFIGURATION OF THE RASPBERRY PI, RASPBIAN OS AND RETROPIE Author: http://rpiarcadebuild.wordpress.com/

More information

Quickstart CHAPTER 1. Powering Up. Installing the Software

Quickstart CHAPTER 1. Powering Up. Installing the Software CHAPTER 1 Quickstart THIS IS A CHAPTER for the impatient Evil Genius. Your new Arduino board has arrived and you are eager to have it do something. So, without further ado... Powering Up When you buy an

More information

ROBOTLINKING THE POWER SUPPLY LEARNING KIT TUTORIAL

ROBOTLINKING THE POWER SUPPLY LEARNING KIT TUTORIAL ROBOTLINKING THE POWER SUPPLY LEARNING KIT TUTORIAL 1 Preface About RobotLinking RobotLinking is a technology company focused on 3D Printer, Raspberry Pi and Arduino open source community development.

More information

DAQCplate Users Guide

DAQCplate Users Guide DAQCplate Users Guide Contents Overview 2 Board Layout 3 Address Selection Header 4 Digital Outputs (DOUT) o 4. Connector o 4.2 Specifications o 4.3 Functions o 4.4 Examples 4.4. Simple External LED 4.4.2

More information

Raspberry-Pi Shield: Binary-Coded-Decimal Clock

Raspberry-Pi Shield: Binary-Coded-Decimal Clock Raspberry-Pi Shield: Binary-Coded-Decimal Clock ASSEMBLY INSTRUCTIONS What is it? This kit builds a binary-coded-decimal clock, driven by a Raspberry-Pi (which should be mounted on the back). This is a

More information

Images Scientific OWI Robotic Arm Interface Kit (PC serial) Article

Images Scientific OWI Robotic Arm Interface Kit (PC serial) Article Images Scientific OWI Robotic Arm Interface Kit (PC serial) Article Images Company Robotic Arm PC Interface allows real time computer control and an interactive script writer/player for programming and

More information

BuffaloLabs WiFi Lantern Assembly guide version 1

BuffaloLabs WiFi Lantern Assembly guide version 1 BuffaloLabs WiFi Lantern Assembly guide version 1 Needed equipment: Solder iron Solder wire Cutter Wire stripper (optional) Hot glue gun Overview of the components (not including USB cable and box panels)

More information

Web Console Setup & User Guide. Version 7.1

Web Console Setup & User Guide. Version 7.1 Web Console Setup & User Guide Version 7.1 1 Contents Page Number Chapter 1 - Installation and Access 3 Server Setup Client Setup Windows Client Setup Mac Client Setup Linux Client Setup Interoperation

More information

HDMI A/V over Gigabit Ethernet Adapter. User s Manual

HDMI A/V over Gigabit Ethernet Adapter. User s Manual HDMI A/V over Gigabit Ethernet Adapter User s Manual HDMI A/V over Gigabit Ethernet Adapter User s Manual ABOUT THIS MANUAL This manual is designed for use with the HDMI A/V over Gigabit Ethernet Adapter.

More information

GETTING STARTED WITH RASPBERRY PI

GETTING STARTED WITH RASPBERRY PI GETTING STARTED WITH RASPBERRY PI Workshop Handout Created by Furtherfield Commissioned by Southend Education Trust GETTING STARTED WITH RASPBERRY PI INTRODUCTION Introduce Raspberry Pi and answer some

More information

Please read this manual carefully before you use the unit and save it for future reference.

Please read this manual carefully before you use the unit and save it for future reference. ANDROID STEREO RECEIVER Please read this manual carefully before you use the unit and save it for future reference. Installation Precaution: 1. This unit is designed for using a 12V negative ground system

More information

University of Hull Department of Computer Science

University of Hull Department of Computer Science University of Hull Department of Computer Science Talking to Hardware with a Raspberry Pi Vsn. 1.1 Rob Miles 2013 Introduction Welcome to our Raspberry Pi hardware sessions. Please follow the instructions

More information

Lab 0: Wire Wrapping Project: Counter Board

Lab 0: Wire Wrapping Project: Counter Board Lab 0: Wire Wrapping Project: Counter Board September 3, 2008 In this experiment, you will build a simple counter circuit that can be plugged into your breadboard. It will provide a set of TTL output signals

More information

Click Here to Begin OS X. Welcome to the OS X Basics Learning Module.

Click Here to Begin OS X. Welcome to the OS X Basics Learning Module. OS X Welcome to the OS X Basics Learning Module. This module will teach you the basic operations of the OS X operating system, found on the Apple computers in the College of Technology computer labs. The

More information

OPi.GPIO Documentation

OPi.GPIO Documentation OPi.GPIO Documentation Release 0.3.1 Richard Hull and contributors Jan 01, 2018 Contents 1 Installation 3 2 API Documentation 5 2.1 Importing the module.......................................... 5 2.2

More information

ENGR 1000, Introduction to Engineering Design

ENGR 1000, Introduction to Engineering Design ENGR 1000, Introduction to Engineering Design Unit 2: Data Acquisition and Control Technology Lesson 2.1: Programming Line Outputs for the NI USB-6008 in LabVIEW Hardware: 12 VDC power supply Several lengths

More information

1. Introduction P Package Contents 1.

1. Introduction P Package Contents 1. 1 Contents 1. Introduction ------------------------------------------------------------------------------- P. 3-5 1.1 Package Contents 1.2 Tablet Overview 2. Using the Tablet for the first time ---------------------------------------------------

More information

1/Build a Mintronics: MintDuino

1/Build a Mintronics: MintDuino 1/Build a Mintronics: The is perfect for anyone interested in learning (or teaching) the fundamentals of how micro controllers work. It will have you building your own micro controller from scratch on

More information

CS12020 (Computer Graphics, Vision and Games) Worksheet 1

CS12020 (Computer Graphics, Vision and Games) Worksheet 1 CS12020 (Computer Graphics, Vision and Games) Worksheet 1 Jim Finnis (jcf1@aber.ac.uk) 1 Getting to know your shield First, book out your shield. This might take a little time, so be patient. Make sure

More information

UM2375 User manual. Linux driver for the ST25R3911B/ST25R391x high performance NFC frontends. Introduction

UM2375 User manual. Linux driver for the ST25R3911B/ST25R391x high performance NFC frontends. Introduction User manual Linux driver for the ST25R3911B/ST25R391x high performance NFC frontends Introduction The STSW-ST25R009 Linux driver enables the Raspberry Pi 3 to operate with the X-NUCLEO-NFC05A1. This package

More information

The Digital Revolution

The Digital Revolution Raspberry Pi A Learning Experience (For me!) Charlie Rothrock K3SR The Digital Revolution Geewhiz Statistics -Digital is changing the world -Tech companies are ~10+% of US employment and the fastest wage

More information

Warranty Disclaimer. Limitation of Liability

Warranty Disclaimer. Limitation of Liability Warranty Disclaimer Purchaser acknowledges that Top Cat Engineering L.L.C.has agreed to provide this kit for evaluation purposes only. Purchaser further acknowledges that Top Cat Engineering has no obligations

More information

Lab 0: Intro to running Jupyter Notebook on a Raspberry Pi

Lab 0: Intro to running Jupyter Notebook on a Raspberry Pi Lab 0: Intro to running Jupyter Notebook on a Raspberry Pi Nick Antipa, Li-Hao Yeh, based on labs by Jon Tamir and Frank Ong January 24, 2018 This lab will walk you through setting up your Raspberry Pi

More information

Pianoteq 6 Raspberry Pi 3 Station. By Edgar Bustamante

Pianoteq 6 Raspberry Pi 3 Station. By Edgar Bustamante Pianoteq 6 Raspberry Pi 3 Station By Edgar Bustamante 1 Contents 1 Introduction...4 2 Parts...5 2.1 Raspberry Pi 3...5 2.2 Fan/Heat Sinks...5 2.3 Digital to Analog Converter (DAC)...5 2.4 Micro SD Card

More information

NAME EET 2259 Lab 3 The Boolean Data Type

NAME EET 2259 Lab 3 The Boolean Data Type NAME EET 2259 Lab 3 The Boolean Data Type OBJECTIVES - Understand the differences between numeric data and Boolean data. -Write programs using LabVIEW s Boolean controls and indicators, Boolean constants,

More information

SRI-02 Speech Recognition Interface

SRI-02 Speech Recognition Interface SRI-02 Speech Recognition Interface Data & Construction Booklet The Speech Recognition Interface SRI-02 allows one to use the SR-07 Speech Recognition Circuit to create speech controlled electrical devices.

More information

Xtra-PC User Guide. Published: April 2017 Edition: 2 Xtra-PC 4.0. Copyright Xtra-PC. All Rights Reserved.

Xtra-PC User Guide. Published: April 2017 Edition: 2 Xtra-PC 4.0. Copyright Xtra-PC. All Rights Reserved. Xtra-PC User Guide Published: April 2017 Edition: 2 Xtra-PC 4.0 Copyright 2014-2017 Xtra-PC. All Rights Reserved. Table of Contents Overview of Xtra-PC... 4 Hardware Requirements... 4 Initial Setup...

More information

Point of View Mobii 825D - Android 4.2 Tablet PC. General notices for use... 2 Disclaimer... 2 Box Contents... 2

Point of View Mobii 825D - Android 4.2 Tablet PC. General notices for use... 2 Disclaimer... 2 Box Contents... 2 Table of Contents General notices for use... 2 Disclaimer... 2 Box Contents... 2 1.0 Product basics... 3 1.1 Buttons and connections... 3 1.2 Start up and shut down... 3 2.0 Introduction to Google Android

More information

A64-OLinuXino 64-bit open source embedded computer

A64-OLinuXino 64-bit open source embedded computer A64-OLinuXino 64-bit open source embedded computer QUICK START GUIDE Document revision B, October 2017 Designed and manufactured by OLIMEX Ltd, 2017 All boards manufactured by OLIMEX LTD are RoHS compliant

More information

TROUBLESHOOTING RASPBERRY PI USER GUIDE. Troubleshooting

TROUBLESHOOTING RASPBERRY PI USER GUIDE. Troubleshooting BY EBEN UPTON, CO-CREATOR OF THE, AND GARETH HALFACREE Troubleshooting THINKSTOCK, Keyboard and Mouse Diagnostics PERHAPS THE MOST common problem that users experience with the Raspberry Pi is when the

More information

Handout Objectives: a. b. c. d. 3. a. b. c. d. e a. b. 6. a. b. c. d. Overview:

Handout Objectives: a. b. c. d. 3. a. b. c. d. e a. b. 6. a. b. c. d. Overview: Computer Basics I Handout Objectives: 1. Control program windows and menus. 2. Graphical user interface (GUI) a. Desktop b. Manage Windows c. Recycle Bin d. Creating a New Folder 3. Control Panel. a. Appearance

More information

RedBoard Hookup Guide

RedBoard Hookup Guide Page 1 of 11 RedBoard Hookup Guide CONTRIBUTORS: JIMB0 Introduction The Redboard is an Arduino-compatible development platform that enables quick-and-easy project prototyping. It can interact with real-world

More information

Prototyping & Engineering Electronics Kits Basic Kit Guide

Prototyping & Engineering Electronics Kits Basic Kit Guide Prototyping & Engineering Electronics Kits Basic Kit Guide odysseyboard.com Please refer to www.odysseyboard.com for a PDF updated version of this guide. Guide version 1.0, February, 2018. Copyright Odyssey

More information

TURN ON YOUR CREATIVITY INTERNET OF THINGS

TURN ON YOUR CREATIVITY INTERNET OF THINGS TURN ON YOUR CREATIVITY INTERNET OF THINGS CONTENTS Before you begin...6 The Pretzel board... 7 Specifications...8 Components in the tutorial kit...9 1 Meet the module... 10 1.1 Basic AT commands... 10

More information

CamJam EduKit Robotics Worksheet Four Driving & Turning camjam.me/edukit

CamJam EduKit Robotics Worksheet Four Driving & Turning camjam.me/edukit - Driving and Turning Project Description Driving and Turning You will learn how to make your robot move in the direction you want it to. Equipment Required For this worksheet, you will require: Your robot

More information

Stealth HD Bio Quick Start Guide

Stealth HD Bio Quick Start Guide Stealth HD Bio Quick Start Guide Copyright 2011 MXI Security. All rights reserved. This document may not be reproduced or transmitted in any form (whether now known or hereinafter discovered or developed),

More information

OpenSprinkler v2.2u Build Instructions

OpenSprinkler v2.2u Build Instructions OpenSprinkler v2.2u Build Instructions (Note: all images below are 'clickable', in order for you to see the full-resolution details. ) Part 0: Parts Check Part 1: Soldering Part 2: Testing Part 3: Enclosure

More information

ToF T1 User Guide. a module solution provider. Date: 2017/02/13. Hardware Test Supervisor. Software Test Engineer. Center Supervisor Rex

ToF T1 User Guide. a module solution provider. Date: 2017/02/13. Hardware Test Supervisor. Software Test Engineer. Center Supervisor Rex a module solution provider ToF T1 User Guide Date: 2017/02/13 Software Test Engineer Hardware Test Supervisor Test Supervisor Center Supervisor Rex Copyright JORJIN TECHNOLOGIES INC. LIMITED 2014 Version

More information

Getting started with Raspberry Pi (and WebIoPi framework)

Getting started with Raspberry Pi (and WebIoPi framework) Getting started with Raspberry Pi (and WebIoPi framework) 1. Installing the OS on the Raspberry Pi Download the image file from the Raspberry Pi website. It ll be a zip file as shown below: Unzip the file

More information

SCRATCH BUILDER R Q R O B O T C O D I N G G U I D E

SCRATCH BUILDER R Q R O B O T C O D I N G G U I D E SCRATCH BUILDER R Q R O B O T C O D I N G G U I D E Scratch is developed by the Lifelong Kindergarten Group at the MIT Media Lab. See http://scratch.mit.edu1 W W W. R O B O B U I L D E R. N E T 01 INSTRALLATION

More information

Operating manual. GTL - Configuration tool. Please keep the manual for future use.

Operating manual. GTL - Configuration tool. Please keep the manual for future use. Operating manual GTL - Configuration tool Please keep the manual for future use. V1.00-01 GREISINGER Electronic GmbH Hans-Sachs-Str. 26 93128 Regenstauf Germany Fon +49(0)9402-9383-0 Fax +49(0)9402-9383-33

More information

RPi General Purpose IO (GPIO) Pins

RPi General Purpose IO (GPIO) Pins GPIO RPi Setup for Today Because the cobbler connector has a notch, you can only put the cable in the right way But, it is possible to put the cable in upside down on the Raspberry Pi The colored wire

More information

College of Pharmacy Windows 10

College of Pharmacy Windows 10 College of Pharmacy Windows 10 Windows 10 is the version of Microsoft s flagship operating system that follows Windows 8; the OS was released in July 2015. Windows 10 is designed to address common criticisms

More information

Software license agreement

Software license agreement Manual 10/2008 Software license agreement Please install the program only after you have carefully read through this software license agreement. By installing the software, you agree to the terms and conditions

More information

COOKING WITH TEAM 279

COOKING WITH TEAM 279 COOKING WITH TEAM 279 ANALOG SIGNALS WITH MCP3002/MCP3008 ADC The RPi does not have analog input pins. To read analog signals, and Analog to Digital Converter (ADC) should be used. The MCP3002 and MCP3008

More information

WIRELESS N USB ADAPTER USER MANUAL

WIRELESS N USB ADAPTER USER MANUAL WIRELESS N USB ADAPTER USER MANUAL MAN-525503/525534-UM-0413-01 INTRODUCTION Thank you for purchasing this Manhattan Wireless N USB Adapter. Because many netbooks and laptops (especially those more than

More information

Bob Rathbone Computer Consultancy

Bob Rathbone Computer Consultancy Raspberry PI Traffic Lights I²C Project Notes Bob Rathbone Computer Consultancy www.bobrathbone.com 16 th of August 2013 Bob Rathbone Raspberry PI Traffic Lights (I²C)/ 1 Contents Introduction... 3 Raspberry

More information

TI-SmartView Emulator Software for the TI-84 Plus Family (Windows and Macintosh )

TI-SmartView Emulator Software for the TI-84 Plus Family (Windows and Macintosh ) TI-SmartView Emulator Software for the TI-84 Plus Family (Windows and Macintosh ) Important Information Texas Instruments makes no warranty, either express or implied, including but not limited to any

More information

PCS 7 Process Visualization on Mobile Devices with RDP

PCS 7 Process Visualization on Mobile Devices with RDP i Application Example 04/2016 on Mobile Devices with RDP SIMATIC PCS 7 V8.1 https://support.industry.siemens.com/cs/ww/en/view/102843424 Warranty and Liability Warranty and Liability Note The Application

More information

Word 2007/10/13 1 Introduction

Word 2007/10/13 1 Introduction Objectives Word 2007/10/13 1 Introduction Understand the new Word 2007 Interface Navigate the Office button Learn about the Quick Access menu Navigate the Ribbon menu interface Understand the I-beam Learn

More information

Raspberry Pi Workshop

Raspberry Pi Workshop Raspberry Pi Workshop Resources and Materials: http://bit.ly/h8dunp Presenters Nick Yee Aexander Nunes Adriana Ieraci Agenda 10:00 Registration 10:20 Introductions and Overview 10:50 Install OS and Boot

More information

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Table of Contents Introduction!... 1 Part 1: Entering Data!... 2 1.a: Typing!... 2 1.b: Editing

More information

SIMPLY PRECISE USER MANUAL. ADJUSTMENT TOOL For NUMERIK JENA Encoders with Online Compensation

SIMPLY PRECISE USER MANUAL. ADJUSTMENT TOOL For NUMERIK JENA Encoders with Online Compensation USER MANUAL ADJUSTMENT TOOL For NUMERIK JENA Encoders with Online Compensation 2 Index 1. Features and Applications... 3 1.1 Functions of the ADJUSTMENT TOOL... 3 1.2 Dynamic Offset and Amplitude Control

More information

Sigma Tile Workshop Guide. This guide describes the initial configuration steps to get started with the Sigma Tile.

Sigma Tile Workshop Guide. This guide describes the initial configuration steps to get started with the Sigma Tile. Sigma Tile Workshop Guide This guide describes the initial configuration steps to get started with the Sigma Tile. 1 Contents Contents... 2 Chapter 1: System Requirements... 3 Chapter 2: Configure Your

More information

Setting up 01/2017. Setting up the SIMATIC IOT2000 SIMATIC IOT2020, SIMATIC IOT2040

Setting up 01/2017. Setting up the SIMATIC IOT2000 SIMATIC IOT2020, SIMATIC IOT2040 Setting up 01/2017 Setting up the SIMATIC IOT2000 SIMATIC IOT2020, SIMATIC IOT2040 Warranty and liability Warranty and liability Note The Application Examples are not binding and do not claim to be complete

More information