Contents 1 – Getting Started 1.1 Introduction 1.2 Technical Specifications 1.3 Basic Setup 1.4 SD Cards 2 – Introducing Raspbian 2.1 Raspbian and Linux 2.2 Installation of Raspbian with NOOBS 2.3 Installation of Raspbian using a Disk Image 2.4 Installation of NOOBS on a microSD Card 2.5 Raspi-config 2.6 Raspbian’s Desktop Environment 2.7 Common Tasks 2.8 Network Connections and Remote Access 2.9 Other Operating Systems 3 – Building a Media Center with OSMC 3.1 OSMC 3.2 Installation 3.3 First Steps 3.
.4 Collision Detection 5.5 Enemies 5.6 More Enemies 5.7 Game Over 6 – Programming in Python 6.1 Your First Python Program 6.2 Python 6.3 Decisions 6.4 Loops 6.5 Functions 6.6 Classes and Objects 6.7 Modules and Packages 6.8 File I/O 6.9 Graphical User Interfaces (GUIs) 7 – Controlling Input and Output Pins 7.1 Electronic Circuits, Voltage and Current 7.2 Solderless Breadboards 7.3 The GPIO Header 7.4 Basic Output 7.5 Basic Input 7.6 Communication between 3.3 V and 5 V Devices 7.
5 1 – Getting Started 1.1 Introduction The Raspberry Pi is a small computer, a very small computer. It consists of mostly the same parts as a standard desktop computer or laptop. A central processing unit (CPU) acts as a brain, random access memory (RAM) and long-term storage devices are used to hold data, a video display shows you what is happening, and you interact with all of this using mice, keyboards, joysticks, and other universal serial bus (USB) devices.
6 Pi as a regular computer. It can do just about everything your main system can do…only a little slower. Playing Games The range of games available on the Raspberry Pi’s operating systems is extensive. But you can also install “emulators”, which are pieces of software that allow programs from other machines to be run on the Pi. This gives you access to titles on classic machines such as the Atari 2600, Nintendo Entertainment System, Sega Genesis, Sharp X1, MSX, Panasonic 3DO, and many more.
7 Building Controller Boards and Interaction with Electronics Its small size, low cost, and ease of programming make the Raspberry Pi very useful in “embedded” applications. In these types of project, the Pi is used along with other electronics circuits to create everything from 3D printers, to home automation systems and robots. 1.2 Technical Specifications The Raspberry Pi 2 Model B is the second generation of the Raspberry Pi.
8 Figure 1. Connectors on the Raspberry Pi 2 Model B 1 General purpose input/output (GPIO) header – these pins can be controlled from software. 2 Universal serial bus (USB) socket for attaching peripheral devices such as mice, keyboards, or memory sticks. This is a dual socket and two USB devices can be connected at the same time. 3 10/100 Mb/s Ethernet (RJ45) socket for connecting to a network router. 4 4-pole 3.5 mm output jack for audio and video. 5 Camera serial interface (CSI).
9 Without these, the Pi will do nothing. It will not even output a video signal. For the initial configuration, you may also need to connect: 1. A display (using HDMI or composite video) 2. A USB keyboard 3. An Ethernet cable or USB Wi-Fi “dongle” The display, and any USB devices you may connect, can be removed when they are not in use. For example, a Pi acting as a file/print server may only need input from computers on the network and may not always need a keyboard or screen.
10 must be a special compound so that it effectively transfers heat from the chip on the Pi to the metal of the heat sink. Figure 2. The heat-out points on a Pi (left); and installing a heat sink on the CPU (right) Connecting Power The Raspberry Pi requires a power supply of 5 V that can provide at least 700 mA of current. Before connecting the Pi and turning it on, you should check the rating of the power supply carefully.
11 There are two holes on the printed circuit board (PCB) of the Pi 2 Model B. These holes are labelled “RUN” and you can solder a switch across these two connections to create a reset button. Connecting a Display HDMI offers a high-quality video and audio signal, and is the preferred way of connecting all models of Raspberry Pi to a modern television.
12 To use a computer monitor as the Pi’s display, you will need an HDMI to VGA, or HDMI to DVI adaptor. However, when connecting to a monitor using an HDMI to VGA/DVI adapter, you will initially be unable to connect speakers to the audio connector. When the HDMI cable is connected, the composite video and audio output ports are turned off. This can be changed once you have an operating system running on the Pi.
13 To connect a USB device, insert its USB connector into an available socket on the Raspberry Pi. You can usually do this safely whether or not the Pi is turned on and running. The Raspberry Pi can only supply a limited amount of power to USB devices. It is recommended that you do not connect any devices that draw over 100 mA. To use more power-hungry devices, you can use a powered USB hub – a device that allows multiple USB peripherals to be connected to a single port, and that has its own power supply.
14 In theory, Wi-Fi is a faster technology than the 10/100 Mb/s Ethernet circuit that is built-in to the Pi 2 Model B. In practice, however, this is not always the case. As the Pi cannot process data as quickly as a brand new desktop computer, the difference in speed between Ethernet and Wi-Fi is less noticeable and you should use whichever is most convenient for you. Not all Wi-Fi and Ethernet adaptors are compatible with the Raspberry Pi.
15 Classifying Memory Cards There are three main types of SD card, with three physical-size variations and several speed classes of each. • Standard SD cards are available in capacities ranging from 4 MB to 2 GB. • Secure digital high capacity (SDHC) cards are available in capacities up to 32 GB. • Secure digital extended capacity (SDXC) cards are available in capacities up to 2 TB. Full-size cards are approximately 24 mm wide and 32 mm long. miniSD cards are slightly smaller, only 20 mm wide and 21.
16 Inserting and Removing SD Cards It is likely that you will need a memory card with at least 4 GB capacity if you are intending to run an operating system on the Pi. 4 GB SDHC microSD cards are widely available and generally very cost-effective. To insert an SD card: 1. Ensure the Pi is unplugged. 2. Locate the SD card socket on the underside of the Pi’s board. 3. When looking from above, the SD card’s contacts should be facing up. 4.
17 2 – Introducing Raspbian 2.1 Raspbian and Linux An operating system (OS) is a unique type of application that you run on your computer. It is an environment in which many other applications can run at the same time, with a consistent user interface and sharing the same resources. Microsoft Windows and Apple’s Mac OS X are probably the two most well-known operating systems, but there are others. Linux is one of a small group of operating systems that are “free”.
18 After installing an OS, if you put the SD card back into a Windows PC then the card appears to have shrunk in capacity. Windows cannot understand the Linux disk partitions. To wipe the card, use the command-line tool diskpart to destroy the partitions and create a new “primary” partition using all of the available space. Installing Raspbian To install Raspbian, you need to connect a keyboard, mouse, and display to your Pi.
19 To install Raspbian: 1. In the list, click the box next to Raspbian. 2. On the toolbar, click Install. When the installation is complete, the Raspberry Pi restarts and loads the raspi-config tool. This helps you to change certain important settings. For more information, see section 2.5 Raspiconfig on page 22. 2.3 Installation of Raspbian using a Disk Image A disk image is a special type of file for making a copy of storage devices, such as floppy disks, CDs, hard drives, and memory cards.
20 To unzip the file on Mac OS X: 1. On the dock, click Finder. 2. Find the .zip file you downloaded. 3. Double-click the .zip file to unzip it to a new folder. Users of Windows need to install Win32DiskImager from http:// sourceforge.net/projects/win32diskimager/ before continuing. Users of Mac OS X should install ApplePi-Baker from http:// www.tweaking4all.com/hardware/raspberry-pi/macosx-applepi-baker/ To write the Raspbian disk image to an SD card on Windows (8/ 7/Vista/XP): 1.
21 9. In the Windows File Explorer window, right-click the card device (usually labelled “SDHC” or “Removable Disk”) and then click Eject. On Mac OS X: 1. Insert the SD card into a card socket or USB reader. 2. On the dock, click Finder. 3. On the sidebar, click Applications. 4. In the right panel, double-click ApplePi-Baker. 5. If multiple SD cards are listed under Pi-Crust: Possible SD-Cards, click the one you want to write to. 6. Under Pi-Ingredients: IMG Recipe, click IMG to SD-Card. 7. Find the .
22 2. Download the latest version of NOOBS from http://downloads.raspberrypi.org/NOOBS_latest 3. Open the NOOBS .zip file. 4. Drag the contents of the .zip file onto your microSD card. 5. Safely eject the microSD card. 6. Ensure the Pi is completely off and unplugged, and then insert the SD card into the Pi’s memory card socket. 7. Reconnect the Pi’s power supply. 2.5 Raspi-config When Raspbian starts for the first time, it runs a tool called raspiconfig.
23 Exploring the Settings in Raspi-config The table below summarizes the options available from the main menu in raspi-config: Menu Option Description Expand Filesystem Make the full capacity of the SD card available to the operating system – if it is not already. Change User Password Change the password for the default user (pi). Enable Boot to Desktop/Scratch Raspbian can automatically load different applications when it starts. This setting changes that.
24 Menu Option Description Hostname Change the name given to the Pi when it is connected to a local network. This can be useful when searching for the device, or when you have several Raspberry Pi devices. Memory Split The Pi’s memory is shared between the CPU and GPU. You can change how much memory is allocated to the GPU using this setting. SSH Enable or disable SSH access. SPI When connecting certain SPI devices, it can be useful to load the SPI kernel module when the Pi starts.
25 2. Press Enter again to select . 3. Type a new password and press Enter. 4. To confirm the password, type it again and press Enter. 5. Press Enter to select . If you connect your Pi to the Internet and are unsure whether your network router allows incoming connections then it is a good idea to change this password so that other people cannot login to your device.
26 2.6 Raspbian’s Desktop Environment If you have not changed the setting in raspi-config, the Raspberry Pi will boot into Raspbian’s command line. To start the desktop environment: 1. Type pi as the username, then press Enter. 2. Type your password, then press Enter.1 3. Type the following command and press Enter: startx Figure 2. Raspbian's desktop environment Raspbian’s desktop is a customized version of LXDE (lightweight X11 desktop environment).
27 the /home/pi/Desktop directory then you can see links to these files on the desktop. In the top left of the screen, you can find: the Raspbian Menu, the Application Launcher, and the Wastebasket. In the top right of the screen, you can find: the network monitor, the volume control, the CPU monitor, and the clock. 1 Menu. The Raspbian menu provides access to many of the system settings, tools, and applications that you install. 2 Application Launcher.
28 3 Task Bar. Open applications are shown as an icon and title in this area. If you minimize an application window, you can click the icon in the Task Bar to restore the window to full view. 4 Wastebasket. Contains files that you delete using the File Manager. If you want to undelete a file (or permanently delete it), open the Wastebasket. 5 Network monitor. Shows the current status of your network connection. 6 Volume control. Sets the volume of all sound and music that the Pi plays.
29 • Press Alt + F4 on the keyboard. • Click the Close button in the top-right of the window. It looks like an x. • Click the icon in the top-left of the window, and then click Close. Using the File Manager You can use the File Manager to copy, rename, delete, and change the properties of files on the Pi. To open the file manager: • On the Application Launcher, click File Manager; or • Click the Raspbian Menu button, point to Accessories, and then click File Manager. Figure 3.
30 Like a web browser, the File Manager window can open multiple folders at the same time by using tabs. To open a new tab: • On the toolbar, click the first button from the left. This will create a new tab in the same folder, and will show the tab bar. You can use the tab bar to switch between the tabs that are currently open. If you have used the Windows Explorer in Microsoft Windows or the Finder in Mac OS X, you already know how to complete many of the most common tasks.
31 To Do This Select multiple files or folders In the right panel, hold Ctrl and click the icons of the files and folders that you want to select. Send a file or folder to the Wastebasket Right-click an icon and then click Move to Trash. Rename a file or folder Right-click an icon and then click Rename... View the properties of a file or folder Right-click an icon and then click Properties. Open a file in its default application Double-click a file’s icon.
32 Folder Description etc Contains most of the configuration files for the operating system. dev Linux creates file system entries in this folder for hardware devices that are attached to the system. Media devices (for example, DVD drives) are placed in /mnt or /media instead. media When storage devices such as CDs, memory cards, and USB flash drives, are inserted, the system creates a “mount point” for them in this folder. Mount points provide access to the file system on the device.
33 Accessing the Command Line While most tasks can be completed using the desktop environment, there are still some things that you will have to do from the command line. To access the command line from the graphical environment: • On the desktop, click LXTerminal; or • Click the Raspbian Menu button, point to Accessories, and then click LXTerminal. In the command line, files and folders have file names and file paths.
34 To Do This List the contents of a specific folder Type ls followed by a space and then the name of the folder. Then press Enter. Move into a subfolder Type cd followed by a space and then the name of the folder, and then press Enter. Move to a parent folder Type cd .. and then press Enter. Create a subfolder Type mkdir followed by a space and then the name of the folder, and then press Enter. Delete a folder Type rmdir followed by a space and then the name of the folder, and then press Enter.
35 • On the application menu, click File and then click Quit. • Type the following command and then press Enter: exit If you only want to run a single command, you can do this from the Raspbian Menu. Click the Menu button and then click Run. Type your command and then press Enter. Understanding Linux Users and Superusers If you have used more recent versions of Microsoft Windows then you may be used to running certain applications as an administrator. This concept is also in Linux.
36 2.7 Common Tasks In this section, you can find instructions for some of most common tasks that people perform after installing Raspbian. These instructions continue into the next section, 2.8 Network Connections and Remote Access on page 40. Restarting and Shutting Down the Raspberry Pi To restart the Pi: 1. Click the Raspbian Menu button and then click Shutdown... 2. Click Reboot, and then click OK. To shut down the Pi from the desktop: 1. Click the Raspbian Menu button and then click Shutdown... 2.
37 3. Type the following command and then press Enter: edidparser edid 4. Find the video mode that you want to use, and make note of the mode number and whether it says “DMT mode” or “CEA mode”. 5. Type the following command and press Enter: sudo nano /boot/config.txt 6. Press the Down Arrow key until you find the lines that begin with #hdmi_group= #hdmi_mode= 7. Remove the # from the start of both of those lines. 8. If the video mode is DMT, change the hdmi_group to 2: hdmi_group=2 9.
38 To open Leafpad, either: • Click the Raspbian Menu button, point to Accessories, and then click Text Editor; or • On the command line, type the following command and then press Enter: leafpad If you open Leafpad from the command line, you can specify the file that you want to edit. • Type the leafpad command, followed by a space, and then the file path and file name. For example: leafpad /home/pi/Desktop/test.txt If you want to edit system files with Leafpad, you may need to open it as a supervisor.
39 To Do This Search the file for a word or phrase Press Ctrl + F. Undo the last change that you made Press Ctrl + Z. Quit Leafpad Press Ctrl + Q. Installing a Graphical Package Manager When installing new applications, there are a few steps that need to be taken: 1. Find out whether the application is compatible with the OS. 2. Install any other pieces of software that this new application requires. 3. Download the application from the Internet. 4. Install the application to the correct folders.
40 To run the Synaptic package manager: • Click the Raspbian Menu button, point to Preferences, and then click Synaptic Package Manager. 2.8 Network Connections and Remote Access Connecting to a Network using Ethernet To connect your Raspberry Pi to your network using an Ethernet cable: 1. Plug one end of an Ethernet cable into the Ethernet cable socket on the Pi. 2. Plug the other end of the cable into your network router.
41 5. Click Scan to open the “Scan results” window. 6. Click Scan. 7. Double-click the name of your Wi-Fi network. 8. Check that the Authentication and Encryption settings match how your other computers connect to your router. 9. Type your network password into the PSK box. 10. Click Add, and then click Close. Finding the IP Address To connect to the Pi from another computer on your network, you will need to know its IP address. To find this: 1. On the Application Launcher, click LXTerminal. 2.
42 ifconfig 3. If you are using an Ethernet cable, in the section labelled “eth0”, make a note of the values “inet addr”, “Bcast” and “Mask”. 4. If you are using Wi-Fi, in the section labelled “wlan0”, make a note of the values “inet addr”, “Bcast” and “Mask”. 5. Type the following command then press Enter: netstat -nr 6. Make a note of the values in “Gateway” and “Destination”. If you can see two entries in the table, ignore the values 0.0.0.0 and use the value from the other line. 7.
43 14. Press Ctrl + X. 15. Press Y, and then press Enter. 16. Restart the Raspberry Pi. Transferring Files to and from the Raspberry Pi You can use secure copy (SCP) to transfer files from your computer to the Pi, or to copy files from the Pi to another computer. Raspbian already supports this, and so you only need to install a client on your main computer. On Windows, WinSCP is very popular application for transferring files. You can download it for free at http://winscp.
44 one of the more popular ones. Download it from http://www.chiark.greenend.org.uk/~sgtatham/putty/ You do not need an additional SSH client to connect to the Pi on Mac OS X. To connect to your Pi over SSH on Windows (8/7/Vista/XP): 1. Locate the file putty.exe that you downloaded, and then double-click it. 2. In the Host Name (or IP address) box, type the IP address of your Pi. 3. Click Open. 4. At the login prompt, type pi. 5. At the password prompt, type your password and press Enter.
45 You also need to install a small software application on the Pi before you can connect using Remote Desktop. To install the software from the command line: 1. On the Application Launcher, click LXTerminal. 2. Type the following command and then press Enter: sudo apt-get install xrdp 3. Press Y and then press Enter. To start a Remote Desktop connection from Windows (8/7/Vista/ XP): 1. Press the Windows logo key + R. Then type mstsc and press Enter. 2.
46 2.9 Other Operating Systems Raspbian Linux is not the only OS that you can run on a Raspberry Pi. Many varieties of Linux have been repackaged so that you can use them, and there are several non-Linux operating systems that also work. Arch Linux Arch Linux is an extremely lightweight version of Linux that is ideal for servers or devices with unusual purposes – where many of the packages that are normally installed to create a usable desktop environment are not needed.
47 Android 5.1 Android is an operating system for tablets and smartphones. The extra speed and memory that the Pi 2 Model B has (compared to the previous generation of Raspberry Pi devices) makes it possible to run Android 5.1 “Lollipop” on the Pi 2. For more information, see http://raspex.exton.se/ Ubuntu MATE Ubuntu is one of the most-widely used versions of Linux. Ubuntu MATE combines that operating system with a new desktop environment, MATE.
48 3 – Building a Media Center with OSMC 3.1 OSMC Open source media center (OSMC) is a free media player that is based on Debian Linux and the Kodi media player. You can use it to play music and video files on your TV. These files can be on USB sticks, hard disk drives, other computers on your local network, and the Internet. OSMC can play media files in many formats, including: 3GP, AAC, APE, AVI, CDDA, FLV, MIDI, MKV, MP3, MP4, M4A, MPEG, OGG, WAV, WMA, WMV, and many more.
49 3.2 Installation OSMC includes a customized version of Debian Linux. This means that when you turn on your Pi, it loads Debian and then immediately opens the media player. You can install OSMC on the same microSD card that you use for Raspbian, or you can install it to a new microSD card. If you want to keep one microSD card for Raspbian and use another card for OSMC, see section 2.4 Installation of NOOBS on a microSD Card on page 21. Then install OSMC using the following instructions. To begin: 1.
50 To continue: 1. In the list of operating systems, click the box next to OSMC_Pi2. 2. Click Install. 3. Click Yes. 4. Click OK. 5. On the Welcome screen, use the Up and Down Arrow keys to highlight your language, and then press Enter. 6. Click I Agree. 7. Click Finish. 3.3 First Steps When OSMC loads, you should see a screen similar to Figure 1 below. Figure 1. The OSMC home screen The default appearance of OSMC is intended for use with remote controls and smartphone apps.
51 1. Using the arrow keys on the remote, highlight the menu item or button that you want to click on. 2. Press the select or enter button on the remote. However, this guide assumes that you want to control your media center with a mouse, so you should switch to the Kodi skin “Confluence”. To do this: 1. On the OSMC Home screen, press the Down Arrow key to highlight Settings. Then press Enter. 2. Press the Right Arrow key to highlight Skin, and then press Enter. 3.
52 • Click a menu item (or option underneath) to open it. Most menu items open a different screen when you click them. To control these screens: • Click with the left mouse button to activate menu items and buttons. • Right-click an area of the screen that does not contain a menu or button to move to the previous screen. • Right-click a media file or folder to bring up a context menu which has additional options that affect the selected item.
53 3.4 Media Files and the Library Using OSMC, you can view files from USB devices (such as memory sticks and hard drives) or over your local network. In addition to browsing for files each time you want to play something, you can add devices and network folders to your OSMC library. The library is a list of all of the files that you have available, and usually contains extra information such as preview images and descriptions.
54 content (for example, a movie). When OSMC updates your library, it opens each source folder and examines all of the compatible media files inside. During this process, OSMC runs special programs called “scrapers”. These add-ons find the information about the files in your library and for this to work, the file names of movies and TV shows that you want to add must follow a set pattern. If the scraper cannot identify the file from the file name, OSMC will not add the file to your library.
55 10. If you are asked whether you want to refresh info for all items, click Yes. To add TV shows to your library, it is advisable to create a directory structure inside the TV show folder on the USB device. Create a folder for each TV series. For example, create a folder called The Addams Family. Then create subfolders inside that for each season. For example, The Addams Family/Season 1 and The Addams Family/Season 2.
56 Removing USB Devices Make sure that you properly eject USB devices from the system. This process stops OSMC from reading or writing to the device while you unplug it, and ensures that all of the changes that need to be made to the file system are completed. To safely remove a USB device: 1. On the OSMC Home screen, point to Videos and then click Files. 2. Right-click the device, and then click Remove safely. 3. Remove the USB device from the USB socket.
57 1. On the OSMC Home screen, click TV Shows. 2. Click the name of a TV series. 3. Click the episode that you want to play. In the Confluence skin, right-click a TV series and then click TV show information to view the details of that series. Right-click an episode and then click Episode information to bring up a window containing all the information that the scraper could find out about that particular episode. Figure 4. The movie information display 3.
58 You can use the OSMC settings program to tell OSMC which network you want to connect to. To access this: • On the OSMC Home screen, click Programs, and then click OSMC Settings.1 Then, to setup the Wi-Fi connection: 1. Click Network. 2. Press the Down Arrow key to highlight Wireless. 3. Press the Right Arrow key to highlight Enable Adapter, and then press Enter. 4. Press the Right Arrow key, and then use the Up and Down Arrow keys to highlight your wireless network. Press Enter. 5.
59 1. Press the Windows logo key + R. Type explorer and then press Enter. 2. Browse to a location on your PC that either all users can access (such as an extra hard drive partition) or that belongs to the user that is currently logged in. 3. Right-click in the right panel, point to New, and then click Folder. 4. Type a name (for example, Videos) and then press Enter. 5. Right-click the folder, and then click Properties. 6. On the Sharing tab, under Network File and Folder Sharing, click Share. 7.
60 6. On the File menu, click New Folder. Type a name (for example, TV Shows) and press Enter. 7. Copy or move your movie files into the movies folder, and TV show episodes into the TV shows folder. 8. On the Apple menu, click System Preferences. 9. Click Sharing. 10. Click the box next to File Sharing. 11. Below the Shared Folders list, click the + button. 12. Browse to your videos folder, double-click it, and then click Add. 13. Next to Everyone, click Read Only, and then click Read & Write. 14.
61 username if you are using Guest Sharing on Mac OS X 10.5 or later. 8. In the Password box, type the password for that user. 9. Click OK. 10. Click the new network location. This is smb://, followed by the name of your PC or Mac. 11. Browse to your movies folder and then click it. 12. Click OK. 13. Click OK. 14. From the This directory contains list, select (Movies). 15. Click OK. 16. If you are asked whether you want to refresh info for all items, click Yes.
62 2. Right-click a source, and then click Remove source. Connecting to UPnP Devices Universal plug and play (UPnP) is a collection of networking protocols that allows devices on a local network to find each other, to find out what type of services and files other devices offer, and to share those files. You can setup your PC or Mac so that OSMC on the Raspberry Pi can play the media files from it.
63 7. Click Next. 8. Press the Windows logo key + R. Type services.msc and then press Enter. 9. Double-click SSDP Discovery Service. 10. On the General tab, in the Startup type list, click Automatic. 11. Click OK. 12. Restart your PC. UPnP devices and their folders should be added to OSMC as sources. Although files stored on these types of devices cannot be added to the OSMC library, they can still be accessed using the videos and music file browsers. To add a video source: 1.
64 6. Click OK. If your UPnP device appears in the UPnP Devices list but you cannot open it to browse its content, there are a few things to check: • If you are running a firewall on a Windows PC with UPnP enabled, you may need to create an exception for the Windows Media Player Network Sharing Service or UPnP Framework. • On Windows, place your video and music files in the Videos and Music folders of the user that is currently logged-in.
65 Protocol: SCP Port number: 22 To find the IP address of your Pi: 1. On the OSMC Home screen, click System, and then click Settings. 2. Click System info. 3. Click Network. You can use SCP to download and upload files anywhere in the Debian Linux file system. However, if you are uploading files then it is best to upload them directly to your USB storage device. USB storage devices usually appear in the /media directory. 3.
66 Installing Movie Information Add-ons Movie information add-ons are a type of extension for finding information about the video files in your library. By default, the scraper that finds information about your movie files uses The Movie Database website. To install a different movie scraper, and configure a video source to use it: 1. On the OSMC Home screen, click System, and then click Settings. 2. Click Add-ons. 3. Click Get Add-ons, and then click Kodi Add-on repository. 4.
67 1. On the OSMC Home screen, click System, and then click Settings. 2. Click Add-ons. 3. Click Get Add-ons, and then click Kodi Add-on repository. 4. Click Program Add-ons. Installing Video Add-ons You can use video add-ons to stream videos across the Internet. There is a wide range of add-ons available, for content providers such as YouTube, Crunchyroll, Watchmojo, and Twitch TV. You can install a video add-on from the main add-ons menu (see 3.6 Add-ons on page 65) or from the Videos menu.
68 Figure 5. The video add-ons list in the Confluence skin 3.7 Remote Controls There are several ways that you can control OSMC with a remote control, instead of using a mouse or keyboard. Controlling OSMC over HTTP OSMC has a built-in web server that you can use to control OSMC over hypertext transfer protocol (HTTP). This turns any device with a web browser into a remote control for OSMC. The web server is enabled by default.
69 HDMI consumer electronics control (CEC) is a feature of the HDMI connection that your TV can use to send commands to Blu-ray™ and DVD players. Manufacturers of televisions use different names for HDMI CEC. For example, Samsung call it “Anynet+”, but Sony call it “BRAVIA Link” or “BRAVIA Sync”.
70 4 – Programming with Scratch Scratch is a visual programming language that helps teach the concepts of programming to people who have never worked with traditional programming languages. It is aimed primarily at people who want to learn to build small games. However, the combination of its simple interface and rich feature set also make it useful for presentations, simulations, and prototypes of software that will be implemented in other languages.
71 1 Cursor Tools. These buttons are for duplicating, deleting, growing, and shrinking the sprites on the stage. Click the cursor tool, and then click a sprite to activate the function. 2 Application Menu. 3 Blocks Palette. 4 Scripts Area. This is where you combine blocks to control the sprite that is selected in the Sprite List. 5 Sprite List. All of the sprites in your project are shown here. Click a sprite to show the scripts that you have added for a particular sprite. 6 Stage.
72 To close the current project and open another: 1. On the Application Menu, click File, and then click Open… 2. Browse to the file that you want to open, click it, and then click OK. Using the Stage All of the sprites in your project appear on the Stage, and this is where all of your actions and scripts take place. A sprite cannot completely leave the Stage. However, you can hide sprites that are not needed at specific parts of your project.
73 You cannot move backgrounds in Scratch, so if you want areas of the background to move then you have to create them as sprites. Building and Running Scripts This section describes how to work with blocks from the Blocks Palette to create scripts – sequences of blocks. Each sprite (and the Stage itself) can contain many scripts. To attach a block, select an item in the Sprite List and then drag blocks from the Blocks Palette to the Scripts Area. For example: 1. In the Sprite List, click Stage. 2.
74 12. Drag the block change color effect by 25 to the scripts area and snap it to the bottom of the wait block. 13. On the block change color effect by 25, click color and then click brightness. Figure 2. A short script Above the Stage, there are two buttons: the green flag button starts all scripts in the project, and the red octagon stops all of the scripts.
75 To Do This Remove a block, a series of connected blocks, or a script from the project In the Scripts Area, click the first block that you want to remove and drag it over to the Blocks Palette. Duplicate a block, a series of connected blocks, or a script In the Scripts Area, right-click the first block in the series that you want to copy, click duplicate, and then click in the Scripts Area to position the new blocks.
76 Blocks like if in the Control section of the Blocks Palette have spaces for six-sided blocks. Six-sided blocks represent the values Yes or No, or True or False. These are described in more detail in section 4.4 Decisions on page 84. 4.2 Sprites In Scratch, you will spend the majority of your time moving and changing the appearance of sprites in response to key presses. Adding and Removing a Sprite To add a sprite to the current project and make it appear on the Stage: 1.
77 • Above the Sprites List, next to New Sprite, click the Paint new sprite button. This is the first button in that area. If you want to import a graphic file, click Import in the Paint Editor. The editor is described in section 4.9 The Paint Editor on page 91. Importing and Exporting Your Sprites You can export your sprites to a single file (including all of their costumes and sounds). You can share these files with other Scratch users, or simply re-use the sprite in another project.
78 In Scratch, variations of a sprite are known as “costumes”. If you create a new sprite, it will only have one costume. To add another costume to the selected sprite: 1. In the Scripts Area, click Costumes. 2. To draw a new sprite using the built-in editor, click Paint. 3. To import a graphic to use as a costume, click Import. To Do This Set the current costume of a sprite from the Scripts Area (not from a script) In the Scripts Area, click Costumes, and then click the image of the costume.
79 Block Description move ? steps Moves a sprite a number of steps in the direction it is currently pointing. turn (clockwise) ? degrees Rotates a sprite a number of degrees in a clockwise direction. turn (counterclockwise) ? degrees Rotates a sprite a number of degrees in an counter-clockwise direction. point in direction ? Rotates or flips a sprite to face the specified direction. point towards ? Rotates or flips a sprite to face the mouse pointer or another sprite.
80 Variable Description direction The direction that the sprite is currently facing. When sprites are added to the Stage, Scratch assumes that they face to the right. When you change the direction that a sprite faces, Scratch rotates the sprite. To tell Scratch that it should flip a sprite and not rotate it: 1. In the Sprite List, click a sprite. 2. At the top of the Scripts Area, next to the picture of the sprite, click the only face left-right button.
81 Block Description change size by ? Grows or shrinks a sprite by the amount specified. set size to ? % Grows or shrinks a sprite by setting its size. This is a percentage of the size of the graphic used to create the sprite, and it can be greater than 100%. show Shows the sprite on the Stage if it is currently hidden. hide Hides a sprite if it is currently shown. go to front Moves a sprite in front of all others. go back ? layers Moves a sprite behind other sprites.
82 • To increase or decrease the amount of an effect that is applied to a sprite, use the change ? effect by ? block. • To remove all active effects from a sprite, use the clear graphics effects block. All sprites have two variables related to their appearance: Variable Description costume # The number of the costume that is currently displayed for this sprite. size The size of a sprite on the Stage.
83 Block Description pick random ? to ? Picks a random number between the first number and the second number. ? mod ? Performs modular arithmetic – the first number “wraps around” if it reaches the value of the second number. round ? Rounds the specified number to the nearest whole number. ? of ? Select from a range of additional math functions. You can use arithmetic operator blocks as inputs to other arithmetic blocks. For example, the expression 1 + ((14 / 3) x 3.
84 blocks in the Variables section of the Blocks Palette for working with variables: Block Description set ? to ? Sets the value of a variable. change ? by ? Increments or decrements a variable. show variable Adds the specified variable to the Stage. hide variable Removes the selected variable from the Stage. 4.4 Decisions There are six blocks that you use to compare numbers and make decisions. The result of these blocks is a “Boolean” value – either true or false.
85 Block Description if ? Runs the blocks inside it, if the attached Boolean operator is true. if ? else Runs the blocks in the top section if the attached Boolean operator is true, and the blocks in the bottom section if the attached operator is false. You can snap any number of blocks into the middle of the if and if…else blocks. This includes adding other if blocks to create highly-complicated decision-making.
86 There is a special set of operators in the Sensing section of the Blocks Palette that you can use for making decisions based on keyboard or mouse input from the user. Unlike the control blocks, these blocks must be used as part of an if decision or with a Boolean operator block. Block Description mouse down? A Boolean value that is true if the user is currently holding the left mouse button down.
87 4.5 Loops Loops have space in the middle for you to snap in other blocks, and you can use them to run pieces of a script repeatedly. There are three types of loop in Scratch: infinite loops, which run until the script is stopped; definite loops, which run a set number of times; and indefinite loops, which run repeatedly until a certain condition is met. Block Description wait ? secs This is a special kind of loop that repeatedly does nothing until the specified number of seconds has elapsed.
88 2. You cannot snap other blocks to the bottom of a forever if block. 4.6 Strings A string is a sequence of characters, like a name, word, or sentence. Many of the blocks that you can use to work with strings are introduced earlier in this chapter: Block Section Description set ? to ? Variables Sets the value of the specified variable to a string. say ? for ? secs Looks Displays a speech bubble next to the sprite for the number of seconds specified.
89 Figure 7. A basic login prompt using strings 4.7 Messages In Scratch, all scripts are associated with an individual sprite and run independently of any other scripts. Messages allow the different sprites on the Stage to communicate and synchronize with each other. These messages are never shown to the user.
90 3. To create a new message: in the Message name box, type a unique name for the message, and then click OK. To receive a specific message when it occurs: 1. In the Blocks Palette, drag a when I receive block into free space in the Scripts Area. 2. Click the down arrow, and then click the message. 3. Snap blocks onto the bottom of the when I receive block. When the message is received, Scratch runs these blocks. 4.
91 Play sound and play sound until done appear to do the same thing, but there is an important difference between them. If you snap two play sound blocks together then Scratch plays both sounds at the same time. But with a play sound until done block, Scratch will play the sound file all the way to the end before running the blocks below. 4.
92 The tools area contains tools for painting and drawing your sprites and backgrounds.. To Do This Make the picture bigger In the Tools area, click the Grow button. Make the picture smaller In the Tools area, click the Shrink button. Rotate the picture counterclockwise In the Tools area, click the Rotate counter-clock-wise button. Rotate the picture clockwise In the Tools area, click the Rotate clock-wise button.
93 Tool Description Fill Fills an area with a color or gradient. Rectangle Draws rectangles and squares when you click and drag the mouse pointer in the drawing area. Ellipse Draws ellipses and circles when you click and drag the mouse pointer around in the drawing area. Line Draws a straight line between two points. Text Type text onto the picture. Selection Click and drag out a rectangle to select a part of the picture.
94 To import a .jpg or .png file: 1. In the Paint Editor, click Import. 2. Browse to the file, click it, and then click OK. If you are importing graphic files for use as sprites, you may need to remove the solid-color background in the Paint Editor. In the color palettes area, click the transparent color (the grey and white checkerboard pattern) and then use the Fill tool to clear the sprite’s background. 4.
95 4. Press the Down Arrow key to highlight Scratch Start the Scratch programming environment upon boot, and then press Enter. 5. Press the Right Arrow key twice to highlight , and then press Enter. 6. Press Enter. 7. When Scratch appears, press Ctrl + Alt + F1. 8. Press Ctrl + C. 9. When prompted, press Ctrl + C. 10. Type the following command and then press Enter: sudo nano /etc/profile.d/boottoscratch.sh 11.
96 To publish a game on the Scratch site: 1. In a web browser, open http://scratch.mid.edu 2. On the top menu, click Join Scratch. 3. Complete the registration process and make a note of your username and password. 4. In Scratch on the Raspberry Pi, on the Application Menu, click Share and then click Share This Project Online... 5. In the Your Scratch website login name box, type your scratch.mid.edu username. 6. In the Password box, type your scratch.mid.edu password. 7.
97 5 – Building an Arcade Game in Scratch In this tutorial, you can see how to build a very basic version of the arcade game Double Dragon®1. Double Dragon® is a sidescrolling action game in which the player takes control of a character and must walk from the left-hand side of the level, to the right. In the way are numerous enemies that the player must defeat by punching and kicking. If you are not familiar with this game, it might be useful to watch a few videos of it on YouTube.
98 2. In the Scripts Area, click Backgrounds, and then click the Edit button next to background1. 3. In the Paint Editor, in the Color Palettes area, click the black square in the grid of colors. 4. In the Tools area, click the Fill tool, and then click in the drawing area. 5. Click OK. To create text that tells the player to press the Space key: 1. In the Sprite List, click Paint new sprite. 2. In the Tools area, click the Zoom out button so that you can see the entire drawing area. 3.
99 3. From the Blocks Palette, drag a broadcast block over to the Scripts Area and snap it into position underneath the when clicked block. 4. On the broadcast block, click the down arrow, and then click new… 5. In the Message name box, type StartGame and then click OK. You can use the brightness effect to create a simple fade-in animation. You can see this script in Figure 1, in the when I receive StartGame scripts.
100 If you have a sound effect in .wav or .mp3 format that you want to play when the user presses the Space key on the title screen: 1. In the Sprite List, click PressSpace. 2. Import the sound file. 3. In the Scripts Area, click Scripts. 4. In the Blocks Palette, click Sound and then drag a play sound block over to the Scripts Area and underneath the wait until key space pressed block. 5. Make sure the correct sound file is shown in the play sound block.
101 5.2 The Level Backgrounds Scrolling is an effect where the background of a game moves in the opposite direction to the player. This makes it look like the player’s character is moving when they are actually standing still. However, Scratch cannot move the project background so your scrolling has to be created using sprites. But it has two further restrictions that make this complicated: • Sprites cannot move completely off the Stage; and • The maximum size of a sprite is 480 steps x 360 steps.
102 If you prefer to draw your own background then you can do this in Scratch’s Paint Editor instead of importing your graphics in the next section. Try to make the overall shape and design similar to the image above, as this will help in later sections of the tutorial. Importing the Background Graphics To import each background sprite: 1. In the Sprite List, click Paint new sprite, and then click Import. 2. Browse to your background file, click it, and then click OK. 3. Click OK. 4.
103 To do all of this, add the following script to the L1M1 sprite: Now copy this script into the other four background sprites: 1. Right-click the when I receive StartGame block, and then click duplicate. 2. Move the mouse pointer to the Sprite List, and click L1M2. Repeat this process for the remaining background sprites. Scrolling the Background The scrolling in this project works like this: 1. There is a variable called scrollX that controls the position of the background. 2.
104 1. In the Sprite List, click Stage. 2. In the Blocks Palette, click Variables, and then click Make a variable. 3. In the Variable name box, type scrollX and then click OK. 4. In the Blocks Palette, click the box next to scrollX. When the title screen broadcasts the message “Level1” to start the game, the first background sprite should make itself visible. Add the following script to the L1M1 sprite: Since the first background sprite starts in the center of the Stage, its x position is 0 - scrollX.
105 1. In the Blocks Palette, click Variables and then click Make a variable. 2. In the Variable name box, type CanScroll. 3. Click the box next to For all sprites. 4. Click OK. 5. In the Blocks Palette, click the box next to CanScroll to remove it from the Stage. To make L1M5 scroll with the others and set CanScroll to zero, add this script to L1M5: Before continuing, it is important that these two variables are set to default values when the game begins: 1. In the Sprite List, click Stage. 2.
106 Masking the Awkward Areas To hide the two areas at the far left and far right of the Stage where the scrolling does not work properly, create a new sprite that adds 20 step (or pixel) thick black borders around the Stage. Name this sprite Border, and add the following script: Adding the Background Music Arcade games from the time period when Double Dragon® was released have background music that plays in a loop. You can use any .wav or .mp3 file for this.
107 5.3 The Player Sprite For the main sprite, you need 10 costumes: • Four “walking” sprites. • One costume for when the character throws a punch. • Two costumes for when the character kicks. • One costume for when the character is hit. • Two costumes for when the player is knocked over. Figure 3. Ten costumes for the main sprite. Original artwork ©1989 Technos Japan Corp. You can use Scratch’s Paint Editor to create your costumes. However, it is often easier to use an external editor.
108 Finally, drag the Billy sprite into its starting position on the Stage. And then in the Scripts Area, click the only face left-right button. Hiding the Sprite on the Title Screen The main sprite should not be visible until the title screen broadcasts the message “Level1”. Add these scripts to Billy: Controlling and Moving the Main Sprite The player will control an invisible “ghost” sprite which tells the Billy sprite to move by broadcasting messages.
109 The if block and costume changes cycle the sprite through the four frames of animation that show the character walking. An invisible sprite will broadcast two other messages: FakeWalk and MoveToGBilly. These are used later, so add these two scripts to the Billy sprite: The ghost sprite is not created until section 5.4 Collision Detection on page 111. If you want to test the movement with the keyboard, add scripts that broadcast and wait the move messages when the arrow keys are pressed.
110 the background to scroll. These limitations are addressed in section 5.4 Collision Detection on page 111. Adding Variables for Health, Lives Remaining, and the Player’s Score Since the Billy sprite represents the player in the game, now is a good time to create three variables that are needed for the game to work: Health, Lives, and Score. Add these three variables and select the For all sprites option so that all sprites can see and modify the variables. Health should never be displayed on the Stage.
111 position before the forever block in the when I receive Level1 script. 2. On the show variable block, click the down arrow and then click Score. 3. From the Blocks Palette, drag a show variable block over to the Scripts Area and snap it into position underneath the previous block. 4. On the show variable block, click the down arrow and then click Lives. 5.
112 3. In the Scripts Area, remove the go to front and go back 6 layers blocks from the when I receive StartGame script. 4. In the Scripts Area, click Costumes, and then click Edit. 5. Using a single, solid color (for example, bright green), draw shapes over the areas that the player sprite cannot walk. 6. Using the Eraser tool and Selection tool, delete the parts of the image where the player can walk. These areas must be transparent.
113 1. Above the Stage, click the green flag to start the game. 2. Press the Space key at the title screen. 3. When the main sprite appears, stop all of the scripts. 4. In the Sprite List, click Paint new sprite. 5. Click Import. 6. Browse to the graphic file for the first costume of the main sprite, click it, and then click OK. 7. Draw a solid color rectangle (any color) around the feet of the main sprite. 8. Using the Eraser and Selection tools, delete the rest of the sprite. 9. Click OK. 10.
114 1. In the Sprite List, click GBilly. 2. In the Blocks Palette, click Control. 3. Drag a forever block over to the Scripts Area, and snap it into position below the show block. The player should not be able to control their movement when they are attacking, or when they have been hit. 1. Drag an if block over to the Scripts Area, and snap it into position inside the forever block. 2. In the Blocks Palette, click Operators. 3. Drag a ? < ? block to the Scripts Area and snap it into the if block. 4.
115 sensing sprite then one of the touching blocks will be true. In response, the script pushes the ghost sprite and the Billy sprite to the left. If the player is not at the far right of the Stage, then the change x by 10 block moves the ghost sprite to the right. It then checks whether it collides with a wall. If it does, it moves back to its previous position. If not, it tells the Billy sprite to walk to the right.
116 When moving up, this script relies on the background masks to stop the player sprite. But the script to move down uses the y position to restrict the player’s movement. Add these blocks underneath the if key up arrow pressed? block: When you move the Billy sprite, your walking sprites may not line up with GBilly. To fix this, edit the costumes in the Paint Editor and “nudge” the costumes to the left or right.
117 5.5 Enemies When the player reaches set points in the level, the scrolling stops and the game “spawns” enemies that the player must defeat. Only having two enemies on screen at once (like the NES game) is a sensible limitation for this project. Prepare the graphics for an enemy sprite in a similar way as described in section 5.3 The Player Sprite on page 107. Enemies only need nine costumes, as shown in Figure 4 below. Figure 4. Nine costumes for the first enemy.
118 You already have the variable CanScroll which is used to stop the player scrolling the background when enemies appear or when the end of the level is reached. But you need one that holds how many enemies must be defeated before scrolling is re-enabled. Call this EnemiesRemaining, and make it visible to all sprites. To detect when the player reaches a point when enemies appear, create another invisible sprite. This is sometimes called a “spawn point”. 1.
119 The position of the spawn point is calculated using scrollX, in the same way as the background sprites and masks are positioned. Assuming the x position of the spawn sprite is 88 and the first screen starts at coordinate 0,0 then the position of the spawn sprite can be calculated as 88 - scrollX. When the spawn point touches the Billy sprite, it: 1. Sets CanScroll to 0 to stop the background scrolling. 2. Sets EnemiesRemaining to 1. 3. Broadcasts the message “Spawn1”. 4.
120 2. Calculates if it is in striking range and if so, punches. 3. Walks a few steps if it is not in striking range. Add the following blocks underneath the go to x: y: block: Eventually, there will be two copies of this sprite on the screen at the same time. To avoid them moving identically, notice how the script picks its direction by looking at Billy and then changing the direction by a random number of degrees.
121 into the distance. When the sprites move down the screen, they are coming closer. However, Scratch does not know that sprites with a greater y position should be behind other sprites. The solution is to check the y position of sprites, and use the go back ? layers block to re-order the sprite layers. You also need to allow for sprites disappearing when they are defeated, and bear in mind that the names of enemy sprites may change.
122 4. On the insert ? at ? of ? block, click the first box and then type Williams1. 5. Click the second box and then click last. 6. Click the third box and then click Mobs. The script that looks at the Mobs list and determines the order in which sprites are placed on layers will be on the Stage. For it to work, you need two other lists: ZSprites and OZSprites. Create these two lists in the same way that you created the Mobs list. You also need to clear Mobs at the start of the game: 1.
123 ZSprites is used to store the sprite names in the order that they should be displayed on the Stage. The if block checks to see whether the sprite that is second in the Mobs list has a y position that is less than the item in position one of the ZSprites list.1 If it does, then the sprite is lower down on the Stage and should be displayed in the front, so the script inserts the second item from Mobs into the first position of ZSprites. This pushes Billy into second position in ZSprites.
124 second item; otherwise the item is added to the end of the list. It does not matter if there is only two (or one) items in the list. Add the next half of the script inside the forever block, but below the previous blocks.
125 Copy these into Williams1, and then change the when I receive blocks to “GFWilliams1”, “GL2Williams1”, and “GL3Williams1”. Layer re-ordering is not instantaneous as the Raspberry Pi is not powerful enough. The approach may work very quickly in other projects, but if it slows this game down too much then remove it. Hitting Williams Enemies can have any name, so it is easier for them to detect the collisions than to have the player sprite do it.
126 1. Create an if block that reads if costume # < 5. Then duplicate it. 2. Drag one of the if blocks directly underneath the repeat until Defeated = 1 block, so that it is inside the loop and surrounds the other blocks in the loop. 3. Drag the other if block directly underneath the repeat 4 block, so that it is inside the loop and surrounds all of the other blocks in the loop. 4. Add a wait 0.1 secs to the bottom – inside the repeat until Defeated = 1 block but underneath the if costume # < 5 block.
127 and then add the following blocks as the first blocks inside the forever loop: To finish the scripts for the Williams1 sprite, click it on the Stage. Then, duplicate the whole script that begins with when Z key pressed and make the following changes: 1. Change when Z key pressed to when X key pressed. 2. Change the switch to costume Williams-6 blocks to switch to costume Williams-7. 3. Change the change by Hits by -1 blocks to change by Hits by -2. 4. Change the if costume # = 6 block to 7. 5.
128 2. Under the Broadcast Spawn1 block, create a set RespawnX to block and enter the x position where the player sprite will reappear. 3. Create a set RespawnY to block and enter the y position where the player sprite will reappear.
129 5.6 More Enemies By duplicating the spawn point and Williams1 sprites, you can fill up the rest of the level with enemies: 1. In Spawn1, change set EnemiesRemaining to 1 to set EnemiesRemaining to 2. 2. In the Sprite List, right-click Williams1 and then click duplicate. 3. Click the new sprite and rename it to Williams2. 4. In the when I receive Spawn1 script, change insert Williams1 at last of Mobs to insert Williams2 at last of Mobs. 5. Change the block when I receive GFWilliams1 to GFWilliams2. 6.
130 4. Change the block set EnemiesRemaining to 2 to set EnemiesRemaining to 1. 5. Change the broadcast block to send SpawnE. Following the previous instructions, make another copy of Williams1. Name this sprite Williams3 and change the when I receive Spawn1 block to when I receive SpawnE. In the when Z key pressed and when X key pressed blocks, replace the set CanScroll to 1 blocks with broadcast WinGame blocks. 5.
131 6 – Programming in Python Python is a widely-used programming language that is available on most modern operating systems and computers. On the Pi, Python is a great way to write software and games, and to control the GPIO pins. Unlike programming languages such as C++ or Objective-C, Python is an interpreted language. This means that special software reads your code files and runs them. You do not have to compile Python files to executables or .app files before you can use them.
132 Python programs (or “scripts”) are text files that contain all of the commands that you want to run. You can use any text editor to create these files, but there is one built-in to the Python packages on the Pi: 1. In the Python Shell, on the Application Menu, click File and then click New Window. 2. Type print("Hello, World") 3. On the Application Menu, click File and then click Save As. Save your file with the extension .py. 4. On the Application Menu, click Run and then click Run Module.
133 Terminal=False Categories=None 3. On the Application Menu, click File, and then click Save As. 4. Save the file to your desktop with the extension .desktop. If you double-click the icon on the desktop, you should see a terminal window open and display the text “Hello, World!” However, the terminal window closes as soon as the program completes. While you are developing your programs, it can be useful to keep the program running (and keep the terminal window open) until the user presses a key.
134 For example: • In the Python Shell, type the following expression and then press Enter: 5 + 5 To Do This Add two numbers together Type one number followed by a + symbol and then another number. Subtract the second number from the first Type the first number followed by a - symbol and then the second number. Multiply two numbers together Type one number followed by a * symbol and then another number.
135 In Python, variables can hold any type of information. To extend the example above, you could assign a string (a sequence of characters) to the variable result, even when it currently contains a number. result = "Hello" You can use variables wherever you would otherwise type a value. For example, in math expressions such as x + 5 and x / y. Python is a “weakly typed” language. This means that you do not have to declare what type of data a variable holds.
136 However, most things in Python are objects. You will learn more about these in section 6.6 Classes and Objects on page 144. Using Lists and Dictionaries Lists collect items together into a single variable. They are ordered – each slot in the list is given a number starting at zero. To create a list, use square brackets.
137 Method Description insert(position, obj) Adds an item to the list in the specified position. All list items that follow are moved down a position. remove(obj) Removes the specified item from the list. For example: Beatles.remove("John"). reverse() Reverses the order of items in the list. A dictionary is a special type of list. Instead of accessing the item by its position in the list, you use a name. You create a dictionary using curly braces.
138 6.3 Decisions In Python, making a decision involves calculating whether an expression is True, or whether it is False. Depending on the result of that calculation, you can run different blocks of code. The basic decision-making command in Python is the if statement. if variable == value: doThis() andThis() The == operator compares the two values and returns True if they are the same, or False if they are not. If the result is True then Python runs the commands below the if statement.
139 Operator Description >= Returns True if the first number is greater than or equal to the second, and False if it is not. <= Returns True if the first number is less than or equal to the second, and False if it is not. You can combine two (or more) expressions by surrounding each with parenthesis and then using one of the logical operators below.
140 doThis2() elif variable == 3: doThis3() else: doThisInAllOtherCases() 6.4 Loops Loops are blocks of code that repeat a sequence of Python commands a set number times, or continually until a certain condition is met. There are two types of loop in Python: Loop Description while Checks a condition in the same way as the if statement, and then runs the code underneath if the condition is True. Then it checks the condition again and if it is still True, it runs the code underneath again, and so on.
141 type some text and echoes what they type back to them, until they press the Enter key without typing anything. text = "?" while not(text == ""): text = input("Type something (or nothing to quit). >") print(text) The for loop is for “iterating” over a list or sequence. It runs as many times as there are items in the list, and assigns each one to a variable so that you can access it. For example, using the Beatles list that you saw earlier, you can print each item using a for loop.
142 (values that are passed into the function), and whether it should return a value. To create a function in Python: 1. Type the keyword def followed by the function’s name. 2. Type opening and closing parenthesis – (). 3. If you want to accept arguments: type them between the parentheses and separate each one with a comma. 4. End the line with a colon. 5. (Optional) Add a string on the next line that describes the function. 6.
143 To specify the arguments in a different order, you can use keyword arguments. As shown below, keyword arguments specify the parameter name before the argument. myFunction2(val2=y, val1=x) An argument is a variable or value that you pass into a function. In the examples above, x and y are arguments. Parameters are part of the function’s definition and refer to the names given to the data when it is passed to the function. For example, val1 and val2 are parameters.
144 6.6 Classes and Objects Python is an object-oriented language. Object-oriented programming (OOP) is a way of writing code that treats data and concepts as standalone objects. These objects can contain multiple items of data (“fields”), and even functions that operate on that data (“methods”). There are several benefits to OOP: • It is easier to reuse code in other projects. • It breaks large projects down into smaller, moremanageable chunks.
145 To access to the fields and methods that is inside an object, use the dot syntax. Alice.firstname Alice.lastname You can add methods to the class by indenting them. To refer to fields inside the object from methods, use the keyword self. class AddressBookEntry: firstname = "" lastname = "" telephone = "" def printName(self): print(self.firstname + " " + self.lastname) To call the printName() method from other parts of your code, specify the variable name, then a dot, and then the method name.
146 contains the same basic information (name, phone number, and so on), it can inherit those fields from the standard entry object. But then you can add other fields that are specific to business contacts (such as company name and website). class AddressBookEntry: firstname = "" lastname = "" telephone = "" def __init__ (self, firstname, lastname): self.firstname = firstname self.lastname = lastname def printName(self): print(self.firstname + " " + self.
147 BusinessContactEntry then you can override the inherited versions. class BusinessContactEntry(AddressBookEntry): company = "" def __init__(self, firstname, lastname, company): self.firstname = firstname self.lastname = lastname self.company = company def printName(self): print(self.firstname+" "+self.lastname+" (" + self.company + ")") Where this gets interesting, is if you have a function like the example below: def printEntry(entry): entry.
148 6.7 Modules and Packages A module is a collection of functions and classes that are related to a specific purpose. You can download modules that are written by other programmers and use them in your projects. Raspbian already has a large number of Python modules preinstalled. To see a list of all the modules that are installed on your Pi: 1. Click the Raspbian Menu, point to Programming, and then click Python 3. 2.
149 Installing a Module You can find many additional Python modules that you can download and install with the Package Manager in Raspbian. If you download a module without using the Package Manager, you will have to install it yourself. Modules usually come with an installation script (setup.py) that copies the module(s) to the correct location on your system. To run it: 1. On the Application Launcher, click LXTerminal. 2. Move into the folder that contains the module that you want to install.
150 Learning about Packages Packages group modules together in namespaces – organized and hierarchical trees of modules. Working with namespaces is a little like working with the file system, except that you use dots instead of slashes. You use package names when importing modules and reading their documentation. So you will become familiar with how this works without having to make a special effort. 6.
151 Mode Description a Open a file for “appending”. Anything you write is added to the end. This overwrites the existing file or, if it does not exist, creates the file. ab Open a file for appending binary data. Python makes a distinction between working with a text file and working with a binary file. The key difference between the two is that with text files Python deals with the text encoding and line break formats for you.
152 If you specify more characters to read then the file has left, Python reads as many characters as it can. When Python reaches the end of the file, the string returned by a call to read() will have a length of zero. Writing Text to a File To create a new text file and write a test message to it, open the file using mode “w”. Then use the method write(). For example: test = open("/home/pi/Desktop/Test.txt", "w") test.write("Hello from Python!") test.
153 Working with Folders The os module also includes many functions for creating and working with folders. Here are some of the ones you will use often: Function Description mkdir(path) Creates a new folder at the specified path. makedirs(path) Creates a new folder at the specified path, and any folders above it that do not exist yet. listdir(path) Returns a “list” of the contents of the specified folder. removedirs(path) Removes (deletes) the specified folder and everything inside it.
154 7 – Controlling Input and Output Pins One of the differences between the Raspberry Pi and the desktop computers, smartphones, and tablets that you may have used, is that the Pi is designed with a 40-pin connector that you can control from your own software. This makes it similar to development boards like the Arduino, but the Pi has the power and speed of a regular computer. The 40-pin header is made-up of many general purpose input and output (GPIO) pins.
155 Figure 1. Three types of circuit – closed (left), open (middle), and short (right). 1 Battery or power source. This supplies the circuit with electricity. 2 Light-emitting diode (LED). When power flows, it lights up. 3 Resistor. See below. In a closed circuit, electricity can flow from the + terminal, to the - terminal (ground in digital electronics). It passes through the LED, which causes it to glow.
156 so milliamps (mA, or thousandths of an amp) can be used instead. The resistance of a circuit limits the amount of current that flows and protects components. It is measured in ohms, and written with the symbol Ω. Resistors have color-coded stripes that indicate the amount of resistance that they put in a circuit. 7.2 Solderless Breadboards Breadboards (or “solderless breadboards”) are easy ways of connecting components temporarily. The various rows of holes are joined together inside the board.
157 or jacks. Unlike the designers of other development boards, the Raspberry Pi Foundation use male pins for the GPIO headers on the Pi. To connect the Pi to a solderless breadboard, you can either use: • A 40-pin female-to-female ribbon cable; or • Individual female-to-male jumper wires. If you use a female-to-female ribbon cable, you need to use regular male-to-male jumper wires or a Raspberry Pi GPIO breakout board to connect the socket on the cable to holes on the breadboard. 7.
158 Pin # Name Description 7 GPIO4 Input/output. Or provides a master clock output (GPCLK0) to external circuits. 8 GPIO14 Input/output. Or UART transmit pin (UART_TXD). 10 GPIO15 Input/output. Or UART receive pin (UART_RXD). 11 GPIO17 Input/output. 12 GPIO18 Input/output. 13 GPIO27 Input/output. 15 GPIO22 Input/output. 16 GPIO23 Input/output. 18 GPIO24 Input/output. 19 GPIO10 Input/output. Or SPI master-output wire (SPI_MOSI). 21 GPIO9 Input/output.
159 Pin # Name Description 40 GPIO21 Input/output. The GPIO pins are rated for 3.3 V. They are not 5 V tolerant and so applying more than 3.3 V to an input pin can break the Pi. GPIO0 and GPIO1 do not appear in this pinout. These functions are shared with the ID_SC and ID_SD pins, which must only be connected to a special identification EEPROM. Do not use them. 7.4 Basic Output Blinking an LED is the electronics equivalent of the “Hello, World!” program. In this example, you will: 1.
160 is not enough resistance in the circuit then the LED will draw too much current and break. Each input/output pin on the GPIO header can only supply 16 mA of current, and the Pi can only supply 50 mA of current to all of the pins in total. Figure 5. Lighting an LED Check that: 1. The + leg of the LED is on the same row as the 3.3 V wire, and the - leg of the LED is not on the same row. 2. The top wire is connected to pin 1 (3.3 V). 3. The bottom wire is connected to pin 6 (ground).
161 3. You have an appropriate value resistor. If the resistance is too great, you won’t be able to see that the LED is on. So far, you are using the Pi as a battery. But now that you know your circuit works, you can place the LED under the Pi’s control: 1. Shutdown the Pi and unplug it from the power. 2. Disconnect the red 3.3 V wire from header pin 1, and then connect it to pin 3 (GPIO2). 3. Plug the power back into the Raspberry Pi, and allow Raspbian to load.
162 To set GPIO2 as an output and turn it on: 1. Type the following command and then press Enter: echo out > /sys/class/gpio/gpio2/direction 2.
163 import RPi.GPIO import time 6. On a new line, type the following statement: RPi.GPIO.setmode(RPi.GPIO.BCM) setMode() is a function in the RPi.GPIO module that sets how you are going to refer to pins. There are two options for this: • BOARD states that when you pass the value 2 into functions in the RPi.GPIO module, you are referring to pin 2. • BCM states that when you pass the value 2 into functions in the RPi.GPIO module, you are referring to GPIO2.
164 example, sleep(2). If you want to blink the LED faster, decrease the value that you pass into sleep(). For example, sleep(0.5). You cannot run this script from IDLE3, because controlling the GPIO pins requires superuser access. To run your script: 1. On the Application Launcher, click LXTerminal. 2. Browse to your script. For example, if you saved the file as test.py on the desktop: cd Desktop 3. Type the following command and then press Enter. Change test.py to the name of your script.
165 1. When the switch is not pressed the input pin can be floating. When a pin floats, it is neither high nor low, and can change between the two seemingly at random. 2. When the switch is pressed, there is very little resistance in the circuit and so this can damage the Pi. It is, effectively, a short circuit. Introducing Pull-Up and Pull-Down Resistors In the diagram below, when the switch is open, electricity flows through the resistor and into the GPIO pin.
166 Building the Circuit The previous circuit has a problem. If the GPIO pin (the middle line on the diagram) is accidently set to a high output (either by the user or by the Pi when it is starting-up) then pressing the switch causes a short circuit and can damage the Pi. Build the circuit in Figure 7. It relies on the Pi’s internal pull-up resistor but also adds a 330 Ω resistor to protect the Pi if the GPIO pin is changed to an output.
167 1. On the Application Launcher, click LXTerminal. 2. Type the following command and then press Enter: sudo su 3. Type the following command and then press Enter: echo 2 > /sys/class/gpio/export To configure the pin as an input and enable the internal pull-up resistor: 1. Type the following command and then press Enter: echo in > /sys/class/gpio/gpio2/direction 2.
168 2. At the top of the script, type the following statements: import RPi.GPIO RPi.GPIO.setmode(RPi.GPIO.BCM) Now you need to configure GPIO2 as an input and enable the internal pull-up resistors: • Add the following statement on one line: RPi.GPIO.setup(2, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) The pull_up_down parameter can be one of three values: Value Description RPi.GPIO.PUD_UP Activates the internal pull-up resistor. RPi.GPIO.PUD_DOWN Activates the internal pull-down resistor. RPi.GPIO.
169 To connect 5 V outputs to an input on the Pi, you will need to convert the voltage levels so that high signals are only 3.3 V. The high signal from the Pi is usually enough to ensure that the 5 V device detects the line as high. This section is primarily concerned with protecting the Pi’s input pins. If you need to convert more than a two or three signals, then a bi-directional logic level converter chip is a useful purchase.
170 from the 3.3 V supply passes through the diode and into the 5 V device, pulling low the GPIO pin on the Pi. When the 5 V device outputs a high signal, the diode blocks the voltage. But because the diode is blocking, the 3.3 V cannot flow to the 5 V device and so it flows into the GPIO pin on the Pi – creating a high signal. Figure 9. Using a diode for 5 V to 3.3 V interfacing 7.
171 Pin Name Description SS Slave select. Use one of these for each slave device in the circuit. The master uses this wire to indicate which slave device should listen and respond to instructions. When the master sends information to a slave, it usually: 1. Pulls the SS line low for the selected slave. 2. Brings the MOSI line high if the bit it is sending is 1; or brings MOSI low if the bit is 0. 3. Pulses the SCK line.
172 wants to communicate with it, and others expect the SS line to be low. Enabling SPI on the Raspberry Pi You can use any of the GPIO input/output pins for SPI since it only involves bringing pins high and low, and reading input in the same way as described earlier in this chapter. This approach is often called “bit-banging”. However, five of the Raspberry Pi’s GPIO pins have alternative uses for communicating over SPI.
173 11. Press Ctrl + X. 12. Type the following command and then press Enter: sudo shutdown -r now When the Pi restarts, the SPI modules load automatically. Using SPI from Python 3 To use SPI from Python, you need to install the python3-dev libraries, and a module for Python that makes the SPI devices accessible. 1. On the Application Launcher, click LXTerminal. 2. Type the following command and then press Enter: sudo apt-get install python3-dev 3.
174 Figure 10. Connecting a 23K640 SPI memory chip to the Pi To use SPI in Python: 1. Click the Raspbian Menu button, point to Programming, and then click Python 3. 2. In the Python Shell, on the Menu, click File and then click New Window. 3. Type the following at the start of the script: import spidev import time To create an instance of the SpiDev class and open a connection, add the statements: spi = spidev.SpiDev() spi.open(0, 0) The first parameter to open() is the device number.
175 The xfer() method accepts one argument, and that is an array of bytes. When you call this method, the slave select pin is brought low and then it sends the values in the byte array to the SPI device. The clock signal is generated for you. To write a byte to the 23K640, you send the WRITE command (2), followed by two bytes that form a 16-bit address, then the value to be stored (8): [2,0,0,8] You also use the xfer() method to read from an SPI device.
176 You can use several properties of the SpiDev class to change how the SPI methods work. This is useful when you are using SPI devices that do not follow the usual process. Property Description cshigh When True, a high signal is used to tell the slave device that it should listen and respond. When False, a low signal is used. False is the default. max_speed_hz Not all SPI devices can run as fast as the Pi. Decrease the value of this property to slow the SPI transmissions down.
177 Figure 11. I2C communication between the Pi and multiple devices Enabling I2C By default, the I2C pins are disabled in Raspbian. To enable them: 1. On the Application Launcher, click LXTerminal. 2. Type the following command and then press Enter: sudo raspi-config 3. Press the Down Arrow key seven times to select Advanced Options, and then press Enter. 4. Press the Down Arrow key six times to select I2C, and then press Enter. 5. Press the Left Arrow key to select , and then press Enter. 6.
178 To add the i2c-dev module to the list of modules that Raspbian loads when the Pi is started: 1. On the Application Launcher, click LXTerminal. 2. Type the following command and then press Enter: sudo nano /etc/modules 3. On a new line, add: i2c-dev 4. On a new line, add: i2c-bcm2708 5. Press Ctrl + O, and then press Enter. 6. Press Ctrl + X. Now you need to install the i2c-tools package and build the pysmbus module: 1.
179 wget http://www.vilros.com/vfiles/ smbusmodule.c 7. Run the following two commands: python3 setup.py build sudo python3 setup.py install Using I2C from Python 3 At the top of your Python script, you need to import the module smbus and create an instance of the SMBus class. In the following example, the code sends the value 88 to the I2C device that has the address 23: import smbus bus = smbus.SMBus(0) bus.
180 The Pi’s serial port uses 3.3 V logic levels. You need logic level converters to connect the Pi to the 5 V ports used by most USB serial port adapters. In Raspbian, the Pi’s serial port is /dev/ttyAMA0. This device is usually configured for console input and output, and so if you want to control the port from your own programs then you need to change two configuration files: 1. On the Application Launcher, click LXTerminal. 2. Type the following command and then press Enter: sudo nano /etc/inittab 3.
181 2. Create an instance of the Serial class, using the line: ser = serial.Serial("/dev/ttyAMA0", 19200, timeout=0) 3. Use the write() method to send data. For example: ser.write("Hello") The first parameter of the call to Serial() is the name of the serial port device. /dev/ttyAMA0 is the serial port that is available on the Pi’s GPIO headers. The second parameter is the connection speed (also known as “baud rate”). The other device needs to open its serial port at the same speed.
182 8 – Building an IP Camera IP cameras are a type of camera that you do not need to connect to a computer in order to view the videos and images that they record. Instead, they connect to your local network router and make the output available over Internet protocols (IP). This allows the videos and images to be viewed across the Internet. Because the Raspberry Pi is small, and has good Internet connectivity, it is well-suited for building this type of camera.
183 To connect to the camera module to the Pi: 1. Ensure the Pi is unplugged. 2. Open the CSI connector on the Pi by grasping the top of the CSI connector and pulling it upwards. 3. Take the flexible cable and gently push it down into the CSI connector. It will only push in by a few millimeters. The blue stripe on the Pi end of the cable should face the Ethernet port. 4. Hold the flexible cable in position and then press down on the top of the CSI connector to close it. 5.
184 Disabling the LED The Pi’s camera module has a red light-emitting diode (LED) on the board. To disable it: 1. On the Application Launcher, click LXTerminal. 2. Type the following command and then press Enter: sudo nano /boot/config.txt 3. Use the Down Arrow key to move to the end of the file, and then add the following text on a new line: disable_camera_led=1 4. Press Ctrl + O and then press Enter. 5. Press Ctrl + X. 6.
185 wget https://www.dropbox.com/s/ xdfcxm5hu71s97d/motion-mmal.tar.gz 5. Type the following command and then press Enter: tar zxvf motion-mmal.tar.gz 6. Type the following command and then press Enter: sudo mv motion /usr/bin/motion 7. Type the following command and then press Enter: sudo mv motion-mmalcam.conf /etc/motion.conf 8. Type the following command and then press Enter: sudo chown root:root /usr/bin/motion Steps 6–8 above move Motion into a system folder and change its owner.
186 Setting Description rotate You can use this setting to rotate the image. Acceptable values are 0, 90, 180, and 270. target_dir The folder where Motion saves images and videos. stream_port The port number you want to use when accessing the live stream from other devices. stream_maxrate The maximum number of frames to send per second to devices viewing the live stream. output_pictures Set this to off if you do not want to save pictures when Motion detects movement.
187 If you only want to access the live video feed, it is recommended that you set ffmpeg_output_movies and output_pictures to off. Otherwise you may run out of space on the SD card very quickly. To change the configuration of Motion: 1. On the Application Launcher, click LXTerminal. 2. Type the following command and then press Enter: nano /etc/motion.conf 3. Change any settings. 4. Press Ctrl + O, and then press Enter. 5. Press Ctrl + X.
188 1. On the Application Launcher, click LXTerminal. 2. Type the following command and then press Enter: motion When you want to stop Motion, press Ctrl + C. To configure Motion to start automatically: 1. On the Application Launcher, click LXTerminal. 2. Type the following command and then press Enter: nano /etc/motion.conf 3. Change the setting daemon to on. 4. Press Ctrl + O, and then press Enter. 5. Press Ctrl + X. 6. Type the following command and then press Enter: sudo nano /etc/rc.local 7.
189 Internet Explorer on Windows is not able to open the stream this way, but other browsers can. You can also use VLC (http://www.videolan.org) to open the stream using its address. Viewing the Live Stream over the Internet To access the live stream from devices outside your local network, configure your router to allow incoming requests on the port stream_port (in motion.conf).
190 9 – Building a Smarter Doorbell A doorbell is a push-button switch that closes a small electrical circuit when a visitor presses the button. With the circuit closed, electricity flows into components that make the chime or buzzing sound. With a Raspberry Pi, you can make a much smarter doorbell – one which is capable of doing a lot more than playing a sound. Anything that the Pi can do, you can do in response to someone ringing the doorbell.
191 Figure 1. Basic button input You can use a push button for this project, or a standard doorbell switch. Doorbells usually have two screw terminals inside, which make electrical connections by tightly holding wires onto metal contacts. To connect a wire to a terminal: 1. Loosen the screw by turning it counterclockwise. 2. Strip 25 mm–35 mm of insulation from the wire. 3. Wrap the exposed part around the screw. 4. Tighten the screw by turning it in a clockwise direction.
192 9.2 Speakers There are two types of speaker that work well for this type of Raspberry Pi project: stereo, desktop PC speakers; and speakers that have an HDMI input and built-in amplifier. Speakers that have an HDMI input extract the audio information from the HDMI signal. If you are using the HDMI output then you do not have to change your configuration to use these speakers. Stereo PC speakers come in two varieties: passive, and active.
193 5. On the Menu, click File and then click Save As. 6. Save the file to your folder, as doorbell.py. 7. Add the Python code below, and then save your script again: import RPi.GPIO RPi.GPIO.setmode(RPi.GPIO.BCM) RPi.GPIO.setup(2, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_UP) def Ring(): pass while True: if RPi.GPIO.input(2) == RPi.GPIO.LOW: Ring() This code detects a button press in the same way as described in Chapter 7 – Controlling Input and Output Pins on page 154.
194 • In LXTerminal, type the following command and then press Enter: sudo python3 Doorbell/doorbell.py Press the switch to hear the audio file play. If you hold the button down, the script repeatedly plays the sound. To stop the script from looping the sound, you can make sure that the button is released before the script checks for another press: • Add the following statements to your script file, in the Ring() function, after the call to os.system(): while RPi.GPIO.input(2) == RPi.GPIO.
195 6. At the end of the file, add the following text on a new line: @reboot sh /home/pi/Doorbell/doorbell.sh 7. Press Ctrl + O, and then press Enter. 8. Press Ctrl + X. 9. Type the following command and then press Enter: sudo shutdown -r now Step 6 tells cron to run the command "sh /home/pi/Doorbell/ doorbell.sh" when Raspbian starts. To stop the script from starting when the Pi starts up, repeat step 5 and remove the line. 9.
196 Add a call to capture() above the os.system() call. For example: camera.capture("Ring %s.jpg" % time.strftime("%Y%m%d%H%M%S")) The string passed into strftime() determines the format of the date and time string. For more information about the time module, see http://docs.python.org/3/library/time.html The full Python script should look like this: import RPi.GPIO import os import picamera import time RPi.GPIO.setmode(RPi.GPIO.BCM) RPi.GPIO.setup(2, RPi.GPIO.IN, pull_up_down=RPi.GPIO.
197 10 – Making Free Phone Calls with Google Voice Google Voice is a form of voice over Internet protocols (VOIP) that is now available in Google Hangouts. You can use it to make free phone calls to numbers in the US and Canada1, and it gives you a landline number that others can use to call you – either from their Google account, or from a regular phone. You can use Google Voice from the Google Mail website, or the Google Hangouts apps for smartphones.
198 If you do not have a SIP phone, there are many softphones available for Windows, Linux, and Mac OS X desktop PCs, and there are also SIP apps that run on smartphones. It is beyond the scope of this guide to review all of the softphones that are available. However, as a starting point, you may want to download Linphone (http://www.linphone.org) or Zoiper (http:// www.zoiper.com).
199 When you register with IPKall, they give you a Washington state phone number and associate this number with your SIP account at sip.pregi.net. To test the number: 1. Install a SIP softphone on your desktop PC. 2. In the softphone, create an account using the following details: Domain: sip.pregi.net Username: Password: Transport: UDP Port: 5060 3.
200 3. Accept the Terms and Conditions. 4. Click I want a new number. 5. In the Phone Number box, enter your phone number or the one given to you by IPKall, and then click Continue. 6. Click Call me now and complete the verification process. 7. Complete the Choose your number process. When you have finished the Google Voice registration process and have your new phone number: 1. On the Google Voice webpage, click the Settings button. 2.
201 3. Write the disk image to a new microSD card. For more information, see section 2.3 Installation of Raspbian using a Disk Image on page 19. 4. Safely eject the microSD from your PC. 5. Unplug the Pi, and insert the microSD card. 6. Reconnect the Pi. If you are using an Ethernet cable to connect the Pi to your network, and you do not have a display, make an SSH connection. For more information, see Connecting to the Pi with SSH on page 43.
202 4. Press Ctrl + O, and then press Enter. 5. Press Ctrl + X. 6. Type the following command and then press Enter: shutdown -r now RasPBX is primarily a server distribution. However, you can still access the graphical desktop environment using the startx command. If you want to install a softphone (such as sflphone) on the same Pi that runs RasPBX then you can also do that. Accessing the Admin Panel FreePBX includes a web-based administration panel that you can use to complete this tutorial.
203 4. In the User Extension box, type a number. For example, 2001. 5. In the Display Name box, type the name of the person who uses this extension. 6. In the secret box, type a password for this extension. 7. Click Submit. 8. At the top of the page, click Apply Config. To register a SIP device on your local network to this extension: 1. In the settings of your SIP phone or softphone, create a new account. 2. In the username box, enter the extension number. For example, 2001. 3.
204 Some SIP softphones drop off the network without warning, so if you cannot dial a device try using different softphone software. When you are finished with the CLI tool: • Type the following command and then press Enter: exit Setting up Google Voice and Outgoing Calls RasPBX contains a FreePBX plugin for communicating with Google Voice. This plugin is called “Motif” and it works over extensible message and presence protocol (XMPP). To add a Google Voice account to the system: 1.
205 Motif creates the outbound route for you, and all SIP extensions can now use this outbound route to make calls. The default settings allow you dial US and Canada landlines using the 10digit phone number or a 1 followed by the 10-digit number. FreePBX uses dialing patterns to specify how different styles of phone numbers are handled. To check or change these: 1. In the FreePBX Administration panel, on the Menu, point to Connectivity and then click Outbound Routes. 2.
206 If you add multiple Google Voice accounts to your system and want to direct them to different extensions, create different rules for each Google Voice account and specify the phone number in the DID Number box for each rule. 10.
207 11 – Accessories One of the great things about the Raspberry Pi is the number of peripherals, expansion boards, connectors, and components that you can use with it. Here is a selection of a useful accessories that you can use with the projects and information in this guide. USB to TTL Cable This handy cable connects to a PC using the USB connector, and to the Pi using individual female sockets that fit directly onto the serial port pins of the Pi’s GPIO header.
208 Light-Emitting Diodes (LEDs) LEDs are components that you will use lots of. In addition to making them flash or using them as status indicators, they can be very helpful for checking which parts of a circuit are working. http://www.vilros.com/red-led.html Resistors Almost all electronic circuits contain at least one resistor. Unlike other components that you may buy specifically for the project that you are working on, you will use so many resistors that it is worth keeping a stock of different values.