Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
424 views

Raspberry Pi Complete Tutorial

It contains how to use raspberry pi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
424 views

Raspberry Pi Complete Tutorial

It contains how to use raspberry pi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 132
Raspberry Pi The Complete Manual The independent handbook for all Raspberry Pi users Welcome to spberry Pi The Complete Manual The Raspberry Pi is one of the most exciting things to happen to computer technology in recent years. ‘As an educational tool, this tiny PC has reignited interest in bare-metal computing in schools and homes all over the world, As a platform for open- source software, it has also inspired millions of people to try Linux ~ many for the first time. Most exciting of al is the potential to incorporate the device into practical projects, as demonstrated by the tutorials in this new edition of Raspberry Pi The Complete Manual. Grab your Pi and start creating! Raspberry Pi The Complete M: Future Publishing ic ichrand House ‘Bournemouth Doreet BH2 62Z ‘a +44 (0) 1200586200 oie wiv fitreple.com itor recto Ross Andrews dir in Chit Jon White Proton Eso Amy Bost ‘Sonor An Eace Greg Writer Assistant Designer Steve Dacombe Printed by ‘wa Grsbone 25 PanetyFoas, Venn Distributed inthe UK. Eire & the Rest ofthe World by Marktoro, § Chursil Place, Canary Whar. London. £14 SHU, “0203 7870060 warn markt 00 Distributed in Australia by (Gordon & Goch Australia Py Li, 26 Rodborough Rs, Frenchie Forest NSW, 3086 Austra ‘B+8120072 8200’ war gordongcihicomau Disciaimer ‘he pbts cano apegesy er ay ened abl lor “brome to oa Be on ial cepa Pave ating Srl Ncongfnesoiarne ny beropoacot tart opm ener umn hep At nore ee ato and Sy Site en ei akin antag ae i gn a iy Respbeny Pi The Complete Manual Eighth Eation "2016 Futwe Pubiehing Lines Tits b an avartwinng miernatonal mesa {yeu eralecng aiaiturexs, We each mere E’smanphene ane nari Finso ok apoto Chit executive Zar 8y99-Thove ampany ated Nonvexecutive chaleman sion grineterson Chief Hraneia officer Poy sos Bran Sookserange (Gyre FUT +48 (Oza 442 244 wrmatuurepiecom Part of the LinuxUser VIE VIE book set Content: inside the Getting started 2 4 16 20 22 Raspberry Pi models Meet models 3, A+ and Zero The starter kit What you need for your Pi Setup yourPi Configure yournew PC Set up your PiZero Startup your tiny Pi Install a distro Get yournewOS running ‘Commandline basics Leam essential new skills, 26 28 32 36 ‘The Raspbian desktop Find yourway around Master the Config tool How to tweak your settings Get online ‘Accessa world of apps Install & use packages How touse apt-get Use graphical installations Install & remove graphically GPIO explained Getto grips wth GPIO pins Top four add-on boards Four of the best peripherals The projects 40 a2 44 52 56 60 70 Backup your Pi Neverloseatfile again Beginner's guidetonano Edit text from the CLI Remote desktop access Use Raspbian anywhere Access files with SSH Getaccess fromhome Raspberry Pi plus Arduinos How to use your Arduino Program with Scratch Drag and drop coding Createa Snake clone with Scratch ‘Make yourfirst game Check your mail Let Raspberry Piactasa mail checker Boost your Pi's performance Improve performance Monitor your network ‘Analyse yourlocal network Tether to Android Access the Internet anywhere using a hotspot ‘Adda battery pack Take your Pimobile Draw circuits with paint ‘Assemble circuits using Bare ‘Conductive paint Send SMS Textfor free from your Pi MakeaRasPi HTPC Use 2 fora powerful HTPC Print wirelessly Keep those wires hidden Control lights with your Pi Use your Piasa remote control Build your first web server Learn new web skills. Build a networked Hi-Fi with Pi Zero Play music with your RasPi Time-lapse cameratrigger Makea timelapse video Pibaby monitor Build your own Raspberry Pi baby monitor Buildan always-on torrentbox Download apps easily Stream Internet TV to your Pi Use the Miro media player to watch and listen to content Create a Ras-Pi powered digital picture frame Animate your photos Build and control a Pi- powered car The ultimate in RC 8 Xbox Zeroarcade TumyourPiZero intoa console-controller combo Getting started Raspberry Pi 3 Raspberry Pi 3 A super-charged Raspberry Pi that finally does everything you'd want it to, for the exact same price as the previous models While the Raspberry Pi has enjoyed years of success, there's always been a couple of things a lot of users wanted. A slightly more powerful CPU that could handle day-to-day computing, more USB ports and maybe wireless to make connecting to the network easier. The Raspberry Pi 3 solves these problems. Asit uses the same board design as the Model By, it has four USB ports, as opposed to the two that were on the original Raspberry Pi Model 8. More importantly, it has a much more powerful processor and more RAM, making it ten times faster than the original Pi. The Pi 3 has also added builtin wireless capabilities, which makes connecting to Wii and Bluetooth a cinch The new BCM2837 chip is the heart of the Raspberry Pi 3, a modified version of the BCM2836 chip from the old Raspberry Pi 2. The quad-core, 900 MHz processor has been further powered up to become a 1,200 MHz beast, which helps to make the Pi 3 a much more functional board. Whereas before you might have had problems surfing the internet or writing a document, now the Pi 3 breezes through these tasks with ease and plenty of processor power to spare. At heart though, i's stil the same board as the Raspberry Pi B+. As well as the aforementioned four USB 2.0 ports, there's the Ethemet port for Wired internet, a good-quality 35mm headphone jack for sound, a HDMI port for digital video and audio and a 40-pin GPIO port. This expanded PIO port is fantastic for making your physical projects even more involved and complicated to do far cooler things. For those worried about compatibility all your ld files and projects and such work just fine on the Raspberry Pi 3, andall you need to do is ‘transfer them aver like any normal files. Raspberry Pi 3 Getting started GPO port The 40 isin the GPO port sive yovarange of power andtunction Sotto conote projectors Ethernet port ‘ThePr3 tains the wied network and internet connection thatwason the ModelBothe nga Raspberry Puselteps ‘Thismakesthe Raspberry 3 (uta ODM butthats plenty theperectenreforan internet fastenough forthe aspoery> ‘ThingsorMaker project ‘rgetaponered hub ; ted wireless The bigupdatebroughtin withthe Raspberry isthe Irosiction obulein 8021p ‘wsessLAN ane lastocth 41.Connecttingtothelntemet (ndother devices has been eaier Headphone jack Needtobstentoyour higher quality ones that was rothest MicroSD. Underneath the board iswhere the boot medium ivee-themirosD card uch snalerthan theSD Cardofthe orginal stl holds the fullopertingsystemand atows the? atebemuchsmaller definition video and audio “The Raspberry Pi 3 still won't be able to i power a USB hub, so if you need to expand the complement you'll need to get a powered-hub” Getting started Raspberry Pi (Model A+) Raspberry Pi Model A+ Good things come in small packages: find out v for mobile projec While the Raspberry Pi Model B+ is a step up from the Model B with its four USB ports, the Model ‘A+ is smaller than its predecessor, weighing just 23g (down from 459) and wielding one USB port. {ts also limited to just 256MB of RAM on the SoC, compared to the 512MB enjoyed on the B+. But dont think that all of this means that the A+ is inferior. Its 65mm length and lower weight MicroSD Storage « le Nomorewemes about thesO Soaneset Cardbangsnappedoffrlot The BotinewRaspbeyPmodels have faspbery int ose ash adhe co header nceased paahotforamirasD card from spins ncesng the sec feat It'ssmaller the Raspberry Pi A+ is ideal is a clue as to how it can be used. The lack of an Ethernet port meanwhile, isn't a weakness, rather an illustration of the fact that this Raspberry Piis designed not for media centres and print servers, but for projects where weight is a factor. Perhaps you'll mount it on an Arduino-powered robot, where its lower power requirement can be satisfied with a battery. _ 256MBRAM Squeezed on board Itseems amazing butentop fat ths theresa System ‘nchip700 Whe processor ‘eh 23618 of RA mounted Inthe cent ofthis vesate eecomputer ‘ It’slighter too “Theonginaaspbeny Pi Mode Repositioned power socket Unbeevably the Raspbery Awasacredtcardsaed 6mm Wah the mice USB power scketnow PidodeAjust23g Ost inlength The At messuesinat beside the OMI sock tester © oxhoredctionin weight jusesmmlongt range and manage cables Simos sopereent Raspberry Pi Zero Getting started Raspberry Pi Zero The tiny £4 computer has taken the world by storm, but what's changed? Coming in at a size smaller than a credit card, no Ethemet in sight, adapters of various kinds the Pi Zero is certainly impressive to behold. will play a vital role in more demanding projects. However its size does not mean a scale backin By ensuring every component is justified in its performance. The Zero’s 1Ghz, Single-core CPU existence, the Pi Zero is incredibly versatile. its and 512MB RAM has this board running 40% capability to run full mages such as Raspbian, faster than the original Pi means jumping into a project is as simple as ever. To achieve such a small form factor and low The minimalism of the Zero lends itself production costs, the creators stripped back a perfectly to running in a headless setup, add a lot of ports we have come to expect. With only WiFidongle and you can SSH in to control it, space saving micro and mini ports remaining and making the most of that single USB port. New mini HDMI port MicroSD card Unpopulated GIPO header Youwlneedan adaprereo make pons Th isthe same sthenewer Smodels, 5 With an Kenic pinout Medel Ai? seat this port Or beter stil oo meaning youcan swapinan existing 1/284, neaderscanoptcnaly be heackessandinstallyouslfalte ‘ardtobeupandrunninginseconds seldered on yoursel making the Zero OSimage Hat compatible Micro USB Minimal connectors Smaller thana The shortageot ports means 3 US8 hub NoEthernet oraudioportandno credit car i andan adapter wil be more important cameraor spay connect. However Measuring nat 65mm x30mmxSmn thonevertoconnectthingssuchosa Uinpopulated composite video and reset, the Zero comesineatenththemode keyboard Wi Fladapeer hendersarestllavaiable Bsoveralfompre Getting started The starter kit The starter kit There's more to your Pi than first meets the Here are some vital peripherals to get you started (NY PAY | In order to get the very best experience from your Raspberry Pi, youte going to have to get hold of a few extras on top of the actual Raspberry Pi board itself. For example, youre going to need a keyboard and mouse with which to enter commands and navigate. While it’s possible to do projects without a keyboard and mouse attached, you'll need them for the initial setup. An SD card is also an important purchase — it's where the operating system lives: Pethaps youll need a Wi-Fi adapter, or maybe just a length of network cable. Then there's the basic electronics side of the Raspberry Fi, what would you need to start sore of the beginner electronics and control experiments? Clearly, there's more to the Raspberry Pi than some might think. By ‘peripherals, we mean other hardware that can be attached and utilised by the Raspberry Pi. They could be something as simple asa decent HDM| or they could be the latest, greatest bespoke gadgets that enhance your project capabilities. There is an entire world of possibilities available for the Raspberry Pi. from robot arms to remote-controlled helicopters... The only limits are the hardware available and your imagination. Keyboard and mouse SD card Let's start with the most basic of components, the keyboard Early Raspberry Pi computers required an SD card, whereas and mouse, Generally speaking, virtually any USB keyboard later models such as the Raspberry Pi2 and 3 use microSD and three-button scroll mouse will work with the Raspberry cards for storage. This is where your chasen operating Pi, and although forsome projects you won'teven needa _systern (Such as Raspbian) is installed, and these can be keyboard and mouse, youll need them for initial setup. ought in various sizes, pre-installed with the OS, or blank. ry The starter kit Getting started ‘The Raspberry Pi uses a standard micro USB connector for its power input, running at SV. In most casesa micro USB 10 USB cable will suffice, of which one end can be plugged into your desktop computer’ USB port. An Android phone charger should also work perfectly 5.25V 1500mA\. Video output There are two video output ports,a HDMI port and an RCA Socket, HDMis the primary video-output connector for ‘most users, but the RCA video-out port can also be used to connect TWs, monitors or ta a SCART cable. Remote access to your Raspberry P's also possible via SSH or VNC. Raspberry Pi camera board This is a custom designed add-on board that attaches to cone of the Raspberry P's on-board sockets via a flexible cable It's extremely small, but remarkably powerful having a native resolution of five megapixels and supporting 1080p Video. It’s essentially a smartphone camera for the Pi. Securing your Raspberry Pin 2 case will protect it and prevent the delicate GPIO pins from accidental damage. A case can also make your Raspberry Pia more attractive or striking unit, perhaps as a media centre. Ensure you choose the right case for your Raspberry Pi model Powered USB hub Extra USB ports are worth considering as an early purchase with your Pi. Once you've connected a keyboard and mouse youl alse why! Using a powered USB hub is important, to stop any power being drained from the and allow you to attach the likes of an external hard drive for example. AS) of O23%7 USB Wi-Fi adaptor Using a US8 WiFi adaptor wil bring flexibility o where you Position your Respberry Pi Without a restrictive Ethernet cable, it could be used for more advanced projects where running 2 wired internet connection isnt a vaid option. Just make sure you buy a Raspberry Pririendly WiFi adaptor. Set up your Raspberry Pi Set up your Raspberry Pi While it looks daunting, setting up the Raspberr for day-to-day use is actually very simple. Like a ora normal computer, only certain cables will ft into the specific slots, and the main job really is making sure you've got plugged in what you need at any one time. The Raspberry Pi itself doesn't label much of the board. However, most good cases will do that for you anyway ~ if you decide to invest in one. The aspen Pscapable of pining ad a p= Iotof moder Android phones ees Feanbe poweredofalaptopor pughOMsvoigtraoder, Computer ut to rake the most JisckeTVs do However outray ‘cutofita proper mains adapter — eedanadapterin some cases Fe thisone idea eae The Raspberry Fis powered using amigo USB cabiemuch ikea There are only alimited number ofUSB ports onaaspbery Gustone.ifyouhave Modal. 5 cessorie Togetaround ths youwitnced Acuity cnete 2aUSBhub ks importantto get Preorecty,butadecentone can Spoweredone the cannot eepitwell peteted rom das, Stppiy enough hice on sown Snake Reslerto move wien Speration You wince an SD cad however ofateast4GB Le any computer youlineeda keyboardand ‘mouse or ary stand PC style operations yOu ‘dowiththeRaspberyP The more bas the leyboae the beter same with the mouse 35 same specalonesneed adctional sofware Set up your Raspberry Pi Althe peripheralsyou wanttoconnect \vaUSB- USBhubs, keyboard, mouse Ussstorage tes plugged there Forsetups thatdontuse HDMI, Ensure you hove extemal powertoth naire youlnweexteral powertothe theyellow veo out port UstHubfyouhavetouse one tho ieavabble.Tousethsuth eo a ‘ound you needto ue the Smalblck poet next wth headphones of anauliay ‘abletopipeoutthe aude The SO card goesinunderneath the Raspberry board This hold your operating system that rns the poet The IOS needs tobe setup fem anather computerbeforeusing though \ The HOM poristhe mala vdeo (and audi) eutputof the Raspoeny ‘ilowing outo dsplay videos onthe ‘desktop atarezohtion of upto 1080. ‘shar support twa pekupthe audio automaticaly thought The aspberyPidoesnot come with Urlesinteret and he youcan adda UsBadapte rs usual easier to pluginan Exnemet cable. Thisvlplog nto thetack fof yourrouteron thectherendand ge you Intemet and acces toyourhomenctwerk Maka sureyouhavethe ight section (fcables such a an Ethernet cabiefor etworkingand internet and an lor Video cable for video out Te HOM can handle audi but the video out il reque Shadtonal avn eae Getting started What you'll need... Raspberry Pi Zero Micro USB power supply Soldering iron and solder PiZero adaptor bundle Monitor, mouse and keyboard USB Wi-Fi or USB Ethernet adaptor Option! USBhub Optional Set up your Pi Zero Set up your Pi Zero ips with your Raspberry or for use toge ero, either as vith een and keyboard So you've picked up one of the tiny yet powerful Zeros, but before the coding fun can begin you need to get more familar with it Don't worry; welll walk you through the Raspberry Pi Zero, the required cables, how to prepare a NOOBS SD card, and how to solder the GPIO header onto the Pi. Once the Piis working and booted welll show you how to get it working on Wi-Fi through the Raspbian user interface. Youll need a USB hub for this, or even just to use a keyboard and mouse together. Welll also show you how to prepare a Raspbian SD card for headless use (either VNC or SSH) with only a WiFi adapter or USB- to-Ethernet adaptor. Raspberry Pi Zero Cable Overview 0 The Raspberry Pi Zero is very small, and as such cannot fit normabsized USB and HDMI connectors on. To use it, you therefore need adaptors that break out micro USB into fullsize USB and mini HOMI to fullsize HOM. You alsoneed to be very careful when connecting the micro USB cables as the micro USB power cable willfit into the connector ‘meant for USB data I's easy to tell them apart though, as they/re clearly labelled, and the USB data connector can be found between the HDMI and power connectors. Fig 1s Once you've soldered he header into place, your PZeroshould resemble any other Raspberry GPIO header Soldering your brand new 0 Raspbemy Pi Zero might seem like a scary prospect at first, but it’s not that difficult! What is dificult, however. is snapping off the correct number of GPIO header pins (0) as the kit supplies more than 40. ts also well worth noting at this point that it doesn’t matter too much if you mess upand end up missing a couple of the bottom pins Solderi kits 0 Soldering irons are very cheap these days. you are going to be doing alot of soldering then its probably worth getting a temperature-controlled one where youcan change the tip However, Set up your Pi Zero the kit we used with a soldering iron, stand, solder sucker and some lead-free solder was £8 on Amazon We managed to solder the GPIO pins Using this kitno problem, Holding the GPIO headers in place 04 Before you can solder the ‘GPIO headers, you need to be able to hold them in place. We recommend putting some blu-tack on either side of the pins for this. This also has the advantage that you can flip the Pi over and then use the blu-tack to keep it in place on a table while you are soldering. The blu-tack should just easly peel off once you are done. Solder the GPIO headers 05 the bit you might have been dreading, but don’t ‘worry! Make sure you have wet the sponge in the soldering iron holder, as you will need to wipe the iron on the sponge to keep the tip clean. If thisis the frst time your iron has been used, the heating element will probably give off lot of smoke for Getting started the fist few minutes so don't worry if that happens stil be mindful of your safety and make sure that you are soldering in a well-ventilated area — try not to breathe in any fumes. Once the iron ishot, apply some solder to the tip and wipe any excess solder on the sponge. Then start to solder the pins. For each pin, touch the tip of the iron on the bottom cof the GPIO header and the metal contact on the i, then apply a very small amount of solder. Once the solder has flowed onto the pin and the metal contact, then you can remove the iron. If there is too much solder then you can reheat the solder and use the solder sucker to remove it. Take breaks when soldering the GPIO headers for a couple of reasons: 1) you don't want to overheat any components on the Pi, and 2) you can melt the plastic of the GPIO headers and that will allow the pin to fall through. Keep wiping the tip of the iron on the sponge to keep it clean throughout the soldering process. Make sure you unplug the iron and put it somewhere safe to cool down when you are finished, Getting started GPIO (Once you've soldered on 22320 male header, your GOs wi workas usual To the igh you can Seethe four unpopulated pinsforvideo output andaveset teh Video Youlinaed amin- HOM {te HDMI adaptor to use this audoideo pot, although you can abo use the RCA compesite ‘ideo output via the unpopulted pin Prepare NOOBS SD Card 06 See www.raspberrypi.org/ help/noobs-setup for more details. NOOBS requires an SD card formatted as FAT32. You then need to download the latest NOOBS image from https://downloads. raspberrypi.org/NOOBS_latest and then unzip it to the SD card. On Linux, the steps areas follows: | sudo parted /dev/nmeblke (parted) mktable msdos Hi arted) nkpart primary Fat32 ot 100% ] (parted) quit sudo mkfs.vfat /dev/ nimcbk@pt ed /ant sudo mkdir pi sudo mount /dev/mmeblkOpl pi cd pi sudo unzip ~/Downloads/ No08S_v1_5_0.2ip syne cd. B s01o unoune Set up your Pi Zero Boot NOOBS and install Raspbian 0 ‘Connect your Pi Zero up as shown in the fist step. The minimum you need connected for a NOOBS installis a monitor and a keyboard. However, a mouse and ‘either an Ethemet adaptor or WiFi _adaptorare also very useful. Press Enter to select Raspbian and then press to install Then press Enter to agree. Once itis finished it will say’OS installed successfully: Press OK and your Pi will reboot into Respbian. Alternatively, if ‘you don't want to use NOOBS, you can flash Raspbian to an SD card in the usual manner, Raspbian will bootinto a desktop environment by default. Configure Wi-Fi 08 Ifyou are using a USB-t0- Ethemet adaptor then the Pi should already be connected tothe intemet. you are using a Wii adapter then you will need ‘o-configure ito connect to your wireless network. We are using an Edimax EW-7811UN, which works Data i The power port onthe ight mice USBas usual Thedsta port besdetis now micro USB «aswel homer sou wil key need amico Use to Use adaptor Zé l= fraser o> rine -Pheteeman S520 Wl) = LATALK-050824 a TRLINK 408362 perfectly with the Pi out ofthe box ‘Once atthe Raspbian desktop, you ‘can dick on the network con in order 10 see the available wireless networks. ‘Once you click on one it will ak you for the password, After that it should be associated; you can hover your mouse over the icon and see the networks that you are connected to. Configure Wi-Fi from another machine 0 Ifyou want to use the Fi Zero 8a headless device with WiFi then you can prepare an SD ‘ard using another Linux machine that will already be configured to connect to the correct Wi-Fi network. You have to mount the SD caid and edit /etc/wpa_supplicant/ wpa_supplicant.conf, which is the same file that is configured by the Raspian user interface from the previous step Insert the SD card into your Linux machine and work out what the device s called dnesg | tail -n 3 [320516.612984] mcd: new high speed SOHC card at address e001 Bh (220516.613437} amcbiko: fnmc0:0001 SOBGB 7.35 GiB Sothe devices Adew/mmcbik0 - now we need to work out which pation ‘number the root partition i (this will be different on a Raspbian image; we are using a NOOBS image here) H sudo parted /deviancka print This will give you a list ofthe patitions. The largest partion willbe the root partition. In this case i's parttion 7.50 the root filesystem isat dew! ‘mumebkOp7. To mount the SD card and edit the wpa_supplicantcon file dothe following Bcd sant | sudo mkdir pi ‘sudo mount /dev/mcblk@p? pis cd pis sudo nano etc/wpasupplicant/ wwpa_supplicant.conf Then filin your WeFi detaits network=t ssid="your_wifi_network” psk="your_wifi password” ey_mamt=WPA-PSK ? Then finally cd | ‘sudo umount. pi/ Remotely access your Pi TO emizimetesan the local network to find a Raspberry i. You need to know the address range of your local network (common networks are 192168.10/24, and 192.168.20/24) You can find it with the ip addr command, nenap Set up your Pi Zero Getting started q ‘ig 2: The Zero maybe tiny but Ris just as good for programming ~p22-sV 192.1681570/24 willscan fora connected), There is no audio suppor, list of devices with SSH open. Exemple but forany other tasks (including the Output: use of pygame) VNC should provide [nmap scan report for an acceptable level of performance. 192.168.157.289 You can install a VNC server with the Host is up (@.070s latency). _following commands PORT STATE SERVICE VERSION sudo apt-get update Bi zzrtep open sch sudo apt-get install (protocol 2.0) tightvncserver Then you can SSH in with: There are several free VNC cients available so a search engine will help youfind a suitable one To start a VNC session on your Flog in over SSH and, ‘then run tightvncserver. You will be E ssh pieise.i68.157.29 The password is raspberry. Ifyou ‘are using the Pi headless, youll want to disable the user interface that is prompted to enter a password the ateited or booty detaut fist time you runt. You can specifya I sudo systenctl set-default screen resolution with the-geometry multi-user.target ‘option: for example, geometry 1024x768. You can kill an existing Setup a VNC server “ne session with tightuneserver -kill “+ :], where 1 isthe session number. 1 1 \VNCstands for Virtual Network Ta connect to that session on a ‘Computing. Using VNC you Linux machine, you could use the ‘can access the Raspbian desktop ‘command: vneviewer 192.168.157.291, over the network (meaning you only substituting for the IP address of your need power and Ethemet/Wi-Fi Raspberry Pi "The minimum that you need connected for a NOOBS install is a monitor and a keyboard" Getting started What you'll need... Raspberry Pi downloads wn espberypLorg downloads Did you know... Card speed Wsagoodidesto getareasonably fstSDeord to keep yoursytem runing oot Css sor sboveisbest Card format - Beforeyoucony youosimage, Soulineed to make RirethesDenrdis formatted the FATSDfle system Install a distro Install a distro e take 2 look at sor involved in installing With its small size and cheap price, many people might be fooled into thinking that the Raspberry Pi is only usable for basic tasks, and leaning to program on. While one of the primary goals of the Pi ‘was to increase computer literacy at a lower level rather than just learning how to create Excel spreadsheets, the Pi has many other great uses. As the Raspberry Pi is essentially a mini PC, with an HDMI and analog TV output rather than a traditional monitor connection, it can perform many common tasks that a laptop or desktop is often used for. While it doesn't really have the processing power or RAM to run the latest version of Windows, there are other options. There are a wealth of fully fledged operating systems, many forked from their desktop big brothers that have been optimised specifically for the Pi. One of the most popular of these is Raspbian, which is a port of Debian. Debian is a key part of the Linux ecosystem, and many other popular open source distributions are forked from the Debian source code. The original Debian was released in 1998, and it's come a long way since. Raspbian needed work to get performance levels up to standard, as the Pi uses the older ARMv6 architecture. I's now a great everyday desktop. Command line Ifyouateusng05Xor Un then ty you ‘wlluse the command line to instal yourprebult ‘operating systems -- Automated tools ‘Tere areacouple ct graphical tools avaiable ‘which make instaling animageortoanSD_ Grdeasy Obtaining OSs 01” ‘of your first questions ‘may be ‘where can find some operating systems to download”. Mostof the common images can be found on the main Raspberry Pi site: wewewraspberrypi.org/downloads These are stable and well tested systems worth investigating, Unzipping OD eee your image, the first thing youll most likely need to do is unzip it This can be done in Windows by right dlcking and choosing ‘extract’ in OS X, justdouble click to extract the files. Install a distro 03 meee youll find a file with a jing or iso extension, These are the equivalent of a ‘snapshot of an installation CD or DVD. Simply copying the file to the SD card ‘won't do anything; youll need to use a program to extract it. SD card format 0. The SD card that you'll boot from needs to be blank, so make sure there is nothing important onitfirst. You'll also need to format it touse the FAT32 fle system This isa ‘common system, used by most USB sticks and cameras. Getting started Formatting the card 05° Windows, to format the card simply insert and wait for itto mount. Then click on My Computer’ ‘and then right click on the cards icon, ‘After that choose format and then, AT32"from the drop-down menu Using the terminal 0 youare using 05 X or Linux, then youll have to use the tetminal to copy the image. In OS X, the Terminal app comes installed by default, and most Linux versions come with one in some form or other. tt may be referred toas the ‘console’ or ‘command line. DDcommand use scalled tid" Thisisentered in the format of sudo dd bs=1m ifstimg] of=/dew/isccard]: Eg: 0 The command you need 10 uso ds bsesan if=/Users/ rachelcrabb/Desktop/ArchLinux/ archlinux-hf-2013-@2-11.img. orordevraiskt Win 32 Disk Imager OS een Disk imager. Once youve downloaded the tool, simply right dick on the exe, and choose run as ‘administrator and follow the prompts. When the instalation is complete you ‘can put the SD card in your P. Easy! Getting started Command line basics What you'll need... ae Command line basics We've probably all been there with the Raspberry Pi. You've installed Did you know. Raspbian or another Raspberry Pi OS to your SD card and you've aS rushed through the setup script or not quite done your research. eee ry You start the operating system and... you end up at a command tetas line. The first step here is to not panic: this is perfectly normal. It may just be a bit ofa foreign concept to you, only seen in films with streetwise hackers who want to bring down ‘the system. The second step, at least in Raspbian’s case, is simply to type: Is start x That's it Raspbian will load up the desktop and you can start using the mouse again. Quick and painless in this case, and in that of many other operating systems as well. What you've done is use a command, specifically in this case to start the X server. The X server handles the graphical interface and can be tumed off by default on some Pi systems, Te nea Fig}: The termina emulator alos you to access the command ine whl lbeing inthe desktop envionment Command line basics | Getting started j Fig2:Accessasp-contigoctange Anew world | Setinge suchas bot tocentoper Getting your Raspberry Pi into the desktop isn't the only thing setraaconsomodie you can do on the command line, though. There's a whole world of functionality built into the command line; in fact, most of the graphical programs youte using are just executing these commands jin sucha way. You don't have to leave the comfort of the desktop. environment to perform these commands either, as all Raspberry Pi operating systems will come with an application known as a terminal emulator. This creates a window where a command can be written in the same way that we launched the desktop, and use the exact same commands (Fig 1).On Raspbian, look for the app LX Terminal in the Accessories section of the menu and click on it. If you've had to use start x to get into the desktop, then we can now fix that before continuing. In the terminal, enter: Is raspi-config Here's the initial setup screen (Fig 2). From here you can enable thhe desktop on boot (Fig 3), and even update the firmware and add support for the official Raspberry Pi camera module. This allows you to modify Raspbian without having to reinstall again. You won't be using those two commands very often, though, so is there practical use for delving into the command line? Very much so. For starters, Raspbian doesn't have an official package manager. This is a program that allows you to browse the available software for the operating system, similar to the Pi Store. However, there's other software available to Raspbian that you can't get through the store. You also can't specifically update the Pi ay esktopforthe nextie you use the software either, and all of this can be fixed using the commandline. | SNe men 23 | Command line basics Upgrade your system ane fs, and have the ees updates andibug fies the process he first thing youll want to do is let Raspbian know exactly what's available online. I's a very simple task: all you need to dois: $ sudo apt-get update This will run down a list of online repositories (or repos) that contain the software that Raspbian uses. Once its finished, the command-line prompt will pop up again waiting for your ne command. As this is the first time you've done it, youll ikely need to update the current software on your Raspberry Pi. You can do that with the command $ sudo apt-get upgrade It may ask you to confirm the upgrade, in which case type 'y and then press Enter. What we'te doing both times is using the commandline package manager Aptitude (apt-get) to first check the repos, and then upgrade packages according to that (Fig 4) -ommand, sudo, allows it to run the apt-get task as an administrator, and is used in a lot of other commandline operations, To install software you use install instead of update or upgrade, followed by the name of the package. For example, with the mathematical programming language, you can install it with $ sudo apt-get install wolfran-engine Command line basics Move and create Installing and updating are just a couple of the many things you can do in the command line. You can also browse the entire file system, move files, create folders and delete items. All of these are very simple operations, When you first open the terminal, it will open up in your home folder. While you cant specifically tell that it is, you can display exactly what kind of files are in the directory with (Fig 5): Isis The tilde sign (+) is used to denote the home folder and can be used for navigating araund the file system. To navigate, welll be using the cd command, followed by the location you want to move to. This can be done like so: IIs cd /rome/pi/Donnloads This will move you to the Downloads directory. As we were starting off in the home folder to begin with, we actually only needed to do this: Is cd Downloads It’s context sensitive and knows to look in the directory it's already in. There's another trick you can use so you don't have to remember the exact name of the path - the command line or terminal will try to auto-complete the phrase if you press the Tab key while something is only partially typed. Try the cd command again, but try pressing Tab when you've only written ‘Down’, Finally, there are some quick commands you can use to manipulate files. Individual files can be copied using the command cp, followed by the filename and the new location like so: $ cp file.txt ~/Docunents/file.txt You can also use this to rename files by doing: Is cp file.tet otherfile.txt The original file can then be deleted by using the rm command: Bs rm fite.tet Want to create a new folder? Use cd to move to the directory you need to add a folder to, and then use mkdir followed by the name you want to give the folder: Bs mkdir NewFolder There's a lot more you can do with the command line, but these are the very basics. As you use Linux more and more, you'll be confronted with tasks that need the command line, and through this process youll leam just how much can be accomplished when you work lke a street-wise movie hacker. Getting started "The command line or terminal will try to auto- complete the phrase if you press the Tab key while something is partially typed” eek hrm Fig: There are many simple command ine toolthatcon help you browneanduse your system Getting started The Raspbian desktop The Raspbian desktop rry Pi's Raspbian system Is clo: < Briips row raspbe m7 Itmight seem a litle alien at first glance, but using Raspbian is hardly any different to using a Windows desktop. There's a menu bar, a web browser a file manager and you'd expect, you simply open the Menu and click the applications you want to get started... Menu button “The Windows ike Menu buttonin the top eft comer displays abstof pragiams andopeons Themainctegotesare Programming where youll find appropriate tools) Intemet browser andenline rescues, Games incr Pis pe-stlled), Accessories an assorunentof bles and Preferences system ool), Programs downloaded from the P Store wll appearin the appropriate category whilethe Fun launches commande terpretet juste te ane Window's Use Shutdown 0 ‘chaff logout ortestartyourRasperyP TaskBar MORE FROM THE BLOG.. Stipped across the top ofthe screens the Task Bar upon which the Menu ‘Estuated Tothe right ofthis ate shortcuts tote Epiphany browser the File Manager PcManFM), Terminal forinpiting ex-based commas, ‘the Wolfam Mathematica computational softwareand the Wolam {nguage programming appleston Nexttothese shorts youl fed ‘hatany open applcatonsare docked whileintheighthand comer youl findthe clock current CPUload, volumestatusand control and the network stats, F File manager Nocomputer woulébe complete withoutafle manager which can be opened by clicking the Tsk Ba shortcut Fes canbe copied renamed and deleted by dragging tothe washcan onthe destop fr by smi highlighting apd tapping Deleteon the keyoare). You can ako create ‘adbed windows inthe fe browser or open futher anes. Folder lecatonsean be bookmarked for easy acess and les therseles canbe \ewedasiconsorina detaled ie. “It might seem a little alien at first glance, but using Raspbian is hardly any different to using Windows" The Raspbian desktop Web browser telear browsing dot Chekonthe Optionslean 3 Getting started Empathy isthe default Raspbery i browse although you dont elt youcan adda new onefrom the Store. As with any browse we adresses ae typedint he dessa andtantel vigation buttons ae provided to navigate Back {and forth through webpages Empathy supports mukiple tabbed windows and estures private browsing andthe ality theend ofthe tool bart sceese thee functions. yoi~ fei (CUBE SOLVER Dora _SEE THE BLOG ARCHIVE oo PiStore ~ eotnenneninvesenen Youean accessthe PStorefom the Menu, or roma inkon the Uwveraapberrypiorg wet: Machi Stem, Google Pay oF the App stare the Store requires you signup foram account wath Ince) and youll needtosigninbeforeyou begin shopping oe free andpaktor software. Any games and apps donnloadedanc installed fom the Store wil appeat under the My Lbxary tab and some ofthese can oniybe wunched fomere. StatusandTime ~ COnthe farright side ofthe Task Bars the Rasobian equivalent ofthe ‘windows syst ray, where youlfind information concering your Raspberry status Inthe comeristhe lock which when clicked wallaso Asp the curent date fincorect. youcanadjustt here TotheleRtof thisyouwl finda graph displaying current CPUlbad the devievolurme ‘contol and nly confiraton that your Raspoery Pisonine. Getting started Master the Config tool weer Mlaster the ‘raaspb.onorg Config tool Tell your Raspberry Pi how to behave using the powerful built-in Config tool The 'RasPi Config! tool allows configuration of your system that ‘would otherwise be trickier in the Linux environment and it's the first thing you'll see when you install Raspbian. Why? Tasks such as setting the date and time or regional settings for your keyboard are often done in a command-line interface with no dialogs, no additional help ~ for a new user, this is a nightmare There are some further specifics for the Pi and Raspbian itself, such as: the ability to easily enable overscan for your TV; change the split of memory to the computer/graphics card or even overclock your system to make ita little faster, enable remote SSH access to the system; stop the system booting into the desktop environment among other things. The Raspi Config tool takes the pain out of the process and puts real power at your fingertips. asswerd foryour default ‘Alla youtovetyquchyandeasly ‘prusemametomake tsomething moce ‘change the partion of heraots tof Peston or ease trenemnberoryou thesDeadeompletly 01 Start by double-clicking the De a] Externe con on yout desktop. This willstart the command prompt, where youll be able to run the config tool. To do this youl need to run acommand BE sudo raspi-config ‘When asked for your password, you wont actually ee it being typed. When youve typed the password ‘and pressed Enter to submitit, the config screen will be shown to you. There area few settings of particular interest that welleover in this section, although they all ave their uses in : H the running of your Pi Some of the Configure your keyboard Overclocking settings in this menu are impoxstant Shange password Expand roots Open the raspi-config tool Setthecorecteyboardup-thereare ‘Allows youto quid and easy and some are everaible so use thei ‘rary difeentlayouts Using thewong ‘overclock yourPitogveyousomeexta le ‘onecanbeannoying Speedandpower wath iter with caution, Expand the root file system 02” default the Raspbien root filesystem will be 2GB -thisis, done so that the image provided for itcan fiton as mary different SD cards as possible, your card is larger the ‘expand_ roots option will make the 05 use the entire space. Upon using this option, the command will be executed immeciately. The operating can take some time. Reboot your system to see the changes. Configure your location 0 Locale isthe language and regional settings that your Pi isusing - while this generally has little impact on what youll see, itis also responsible for any default currency settings, etc, 0 could prove to be an initant ata later time if wrong. Upon selecting the option, you'l be taken through a wizard, Use the arrow keys to check the built locale before building more (ittakes a while) Timezone will ake you toa tadata screen where you can adjustit Overclock your Pi You can set the clock speed and voltage of your Fito several diferent presets, Setting the lock speed and voltage at higher rates than the specification may cause instability, so do so in small increments Master the Config tool and ensure good airflow around ‘yourPi. you see any noticeable instability, run this wizard again and set the clock speed back down to something slightly lower — repeat until your system is completely stable. For the scope of this tutorial, a Modest/ Medium overclackis recommended = itseems to give alittle extra performance with no noticeable side effects itis also recommended toreboot your system after making ‘this change. Hold the Shift key to temporarily disable overclocking Change the memory split OS Seranathemenen so of the Piallows you to give either the system or the graphics processor a larger amount of memory. The value you give to it must be either 16/32/64/128/256. Here are our recommendations: '32MBGPU memory for basic distro Usage where video and 3D tendering arent required. ‘64MB GPU memory for desktop Use that requires video playback or have 3D effects enabled ‘128MB GPU memory for graphical applications and games that do extensive multimedia or play 3D rendered games. For most people, a 64MB split for ‘graphics will suffice, Change boot behaviour By default the Raspbian distro will boot into.a command-ine interface, whereby you have to frst login as pit you then want to run a window manager (in this case it’s called °), you have to give the systern a command to let it know thats what you want todo, Fora lot of people this isnt really ideal since command lines scare them, Because ofthis, there's an option to Getting started start X automatically, on boot Set this ‘option to Yes'to enable this behaviour by default. You can obviously revert this at any time to retun toa text-based login where you have to start manually: BE startx Turn overscan on and off O72 noticed one of ‘wo behaviours if youre using your Pi with a modem HOTV. Thete isa black border the whole ‘way around the image output by the Pi itjust doesn't fit correctly. Thisis ‘used by underscan. you cant see the edges of your screen to get to them youre suffering from overscan, Ifyou have the formerissue, you may need to either turn on overscan, ‘orenable a 00m’ mode or similar on your Ty, Ifyou have the latter issue, you need to turn overscan off so that you can see the edges. Update raspi-config ‘The raspi-config tool receives 0 Updates from time to time. This is generally to either add more features or fix small bugs, or both! tes not a bad idea to run the Updater when you use the tool — before you start changing any system settings. While fs much ‘more likely that itl be updated tolook better or do more things, i's not impossible there could be miscellaneous bug fixes hidden within that would otherwise cause yousome grief Remember, though, when youte trying to update your copy of the raspi-config tool yout need an active intemet connection either through an LAN cable or wireless dongle. Without them, is never going to get any newer. Always try tomake sure you're on the latest version. Getting started What you'll need. Raspberry Pi distro mekrensbiosniss WiFi dongle or Ethernet Piet ae OE Fig: Witha WiFi dongle attached run the lity and sean for avaible networks Fig 2: Emer the presharedke inorder to fonnccttayourhome outer Get online Get online To access a world of utilities, apps and resources you need to get online. This is how to The easiest way to get online is to buy a Raspberry Pi Model B+, as it comes with an Ethernet socket. The Model A not only lacks the Ethemet port, but is handicapped by only having one USB port That means you will have to buy a power USB hub in order to get online. Back to the Model B+ though and to get online, simply plug an Ethernet cable into the socket on the Pi and connect it toa similar port on the back of your internet modem/router. Turn your Pi on and launch the desktop, then double-click on Empathy and you should see the intemet appear (main image) To check that it's working, look at the lights on the Pi itself. The red power light should be on. Above this is the green light that flickers when accessing the SD card. Below the power light are the three Etheret- related lights. Note that the Model A does not have these LEDs because it doesn't have the Ethernet socket. The middle light is green and comes on when it detects a Full Duplex LAN connection. This means itis able to send and receive data to the internet. The next lights green and flashes when actually accessing the internet by sending or receiving data. The last lights yellow and will come on and stay on when a 100Mb LAN connection is detected. The Wi-Fi option Ifyou aren't close enough to the modenv/router to be able to plug in the Ethemet connection, or you simply have a Model A, then a powered USB hub is required. This plugs into a USB port on the Pi. You can then plug a Wi-Fi dongle into this. Boot up the Pi and. launch the desktop. Then double-click on the Wi-Fi Config icon. You should see a name for the dongle in the Adapter section. Click on Scan to look for networks and a list of those found should appear (Fig 1). Double-click on the one you want to connect to and the details for it will be listed. Almost all home networks use a network key, which is usually written on the modem itself. Click on PSK, which stands for pre-shared key, and type it in (Fig 2), Then click on Add. It will process this, then associate the connection and Get online Getting started then finally, a new IP address for the Wi-Fi connection will appear. Ifyou click on the Manage Networks tab, the network will now be listed and have an Enabled radio button active. To get on the internet, simply launch Empathy and youll be connected, The Wii utility will remain running on the bottom right of the panel. you right-click on the WiFi icon you will see options to Disconnect or Reconnect, event history and the results of the most recent scan. Click on Status to see how it’s performing. Checking the connection To check that the Pi has a valid internet connection, double-click on. LXTerminal. Enter this command: Bh ip acdr You should see a list of numbers, with the bottom line starting ‘inet and then the IP address of the Pi connection (Fig 3). Typically this is something like 192.1681.11 and this shows that the connection is working because the Pi has been assigned an IP address based on the one used by your intemet modem/router. If this doesn’t come up then there may be a problem at the router end. The modem router should be running a DHCP server and when the Pi connects toi, it will be given the IP address. fit isn't running then nothing else connected to it will be able to access the internet either. Use the web interface with another device to log onto 192.1680 or whatever is your modem’s actual IP address in order to check that the DHCP server service is tumed on. Finally, in the terminal, type: I ping google.com Fig 3:fitdoestlook ike the connection isworking ther aresomecasy ways of checking what's going on Fig Both Windows and Mac computers canshare ther internat connections witha ‘Srecty-connected Ft Sharing a connection Ifyou don't have a Wi-Fi dongle, a powered USB hub ora long enough Ethemet cable, but do have another computer connected to the intemet, there's another way of getting access. On a Mac, connect it to the Pi via a USB or Ethernet cable. Launch ‘System Preferences; under Internet & Wireless, click on Sharing. Click on Internet Sharing, then select Wii (or AirPort) as the connection type to share, and select how the Pi is connected to your Mac (Fig 4). ‘Ona Windows PC, go to Windows Explorer>Networking> Networking and Sharing Center>Change Adapter Settings Install and use packages wove Install and use htpsinwcdienetimaniaapt Apt-get help page: == packages etdimanarapeget On its own, the Raspberry Pi is a near-perfect mini computer. It already cor fen some programming utilities and a number of system tools. But, as with most computers, this is only the tip of the proverbial iceberg. By installing more programs, you can do much more. These programs, known as packages, are as wide and as varied as the developers who originally designed them. In Linux, if there's a need for a particular program, then someone develops one They then put it out to the world and make the source code freely available, hence ‘open source’. Once the program has been tested, it will eventually make its way onto one of the many rem: for that particular Linux distro. These remote servers, called repositories, or repos, contain all the elements of the package in order for it to be downloaded and installed onto your system. The process is very quick and easy once you know how it’s done. ins a wealth of educational software, games, vers sudo apt-get .... "Have you mooed today?" Update and upgrade OT Sting sere scone on the Raspberry Pi involves, dropping into the commande terminal via the LxTerminal icon con the desktop, and entering a few commands. But before we do that werneed to make sure the system is upto date. Enter the folowing into the terminat sudo apt-get update sudo apt-get upgrade Or [sudo apt-get update a8 sudo apt-get upgrade Search for a package The apt-get command OD irsrcedratage Toons the key to downloading and installing packages on the Raspberry Pi. In the previous instance, we u the existing packages and system Upgraded any that needed it, and Updated the curtent package ist Now, ers search the lst of server packages for available games. [ apt-cache search game | less Apt searching 03 Meare find yourself inis the name of all the packages labelled as ‘games’ from the available server In the lst the t before the hyphen tellsyou the name of the package, which is what Install and use packages you will need to know ta be able to install it, Use the arrow keys up/down, tonavigate; press ‘Q'to exit Installing a package (0g Binsin voart down ano keys, navigate the list. IFyou find sor Jing you like the look of, say Angry Drunken Dwarves, remember the name of the package, in this case angrydd and press to exit thelist To instal the package enter the following in the termina! TE sudo apt-get install angrydd Executing the package O5 meet prevout command should be the successful download and installation of the game, Angry Drunken Dwarves. To execute the newly installed package, you can either run it from the LXDE Menu under Games>Angry Drunken Dwarves, or by typing in the following into the terminal: Doe Remove a package This installing of packages is 06 ric ine an youcon seejusthow powerful a command Apt realy i. But, what ifyou want 10 Using the Apt command again let's say we want to completely remove ll trace of Angry Drunken Dwarves from the Raspberry Pi I sudo apt-get —purge remove angrydd Enter Y toaccept the removal Getting started Apt Easter eggs 0 The Apt command isa shorter, non-menu-driven variant of the Aptitude command. This command has a long history in Linux, and asa result has some rather special features, also known as Easter eggs. Puraly fora little bit offun, type in the following commands and see the resuits: aptitude moo aptitude -v moo pon ati AAs aptitude -wvv oo Bi sersnae sae9 oee Batons acre me B sudo apt-get noo Man the Apt command O82 eters to the simple Apt command than what frst meets the eye. There are many diferent sub-commands that you can run, and many different variations in which to run them. ff youwant 10 see what ese the Apt command can do, enter the following: Enon apt Getting started What you'll need... ‘Synaptic: wnengnatere/ymapte/ Did you know... Use graphical installations Use graphical installations graphical ii 2ad on 0 install new rface IFyoute new to Linux, you may find using its built-in Apt package management tool a bit intimidating and confusing, The apt-get command is used for installing applications through the intemet, connecting to the remote servers — called repositories ~ which house the programs as packages. But itis used through the terminal command prompt, which can be daunting, so we need an alternative: a desktop environment interface method of getting hold of packages. This is where Synaptic comes in. Synaptic isa fiiendlyHooking graphical interface to the apt-get terminal command which allows you to manage your application installations, and removals, through the already familiar desktop environment. Think of itas a kind of online shop where you can pick and choose the programs you want and have them downloaded and installed onto your Raspberry Pi without you having to drop into the terminal Upgrade entire systems ‘yap has thea toupee andipre vy progr or ‘ackage, ane tcan upgrade your ntresystem totheletest version ~ Install and more Synaptcisa very powerful tool Withityouaninal remve, ‘Upgrade and downgrade single or ‘multe packages and programe eal imentation FromwathinSyrapic youare abletebrowae ndeead al aalable Online documentatonrelatedioa peckageorprogram ~~» Easily find programs Syraptcenablesyouto easy locate aclagesand programs ty ame ‘esetption version and even by ‘who developed program Update the system 0 Unfortunately ifyou have an aversion to dropping into the commandine terminal, then youte going to be stuck at the fist step. Before we install anything, we need to ‘make sure that the Raspberry Pits fully Updated and any existing packages are upgraded, Simply enter the following into the L Terminal: sudo apt-get update sudo apt-get upgrade Installing Synaptic To install Synaptic, youll first and run the command below ~ don't forget to type Y to any prompts asking you to accept the installation: fl sie epee synaptic Running Synaptic - Part 1 In essence, that’s all you need 03 2 ecSpapn snon rooted and ready to use. However, due to its complenity, there may be some ‘bugs that need ironing out firs, so it's best to follow these steps. To test f Synaptics working okay, ist enter the following command into the termina D eksudo synaptic Use graphical installations A etek ener eaings the Synaptic program window, where you can scroll through the list of available programs and clickon each to download and install. Now we need to test whether twill run ftom the LXDE menus, Clickon the icon in the bottom left, then go to Preferences>Synaptic Package Manager. Running Synaptic — Part 3 QB Brasco LUXDE menu results in an enor Don't panic, however alts doing isasking fora password, Enter the following password into the box T raspberry Thisisthe default Pi password so were assuming you haven't changed it Fixing Synaptic -— Option 1 0 This will temporarily ficthe issue, but to permanently resolve it, do one ofthe following, First, right-click the Synaptic icon in Getting started the menu and left-click Properties. In the Command textbox, change the ‘text to add the gksudo command. So. instead of 'synaptic-pkexec’ it will react: Bde smencicniene Fixing Synaptic — Option 2 The second, and best, option O7 oe dopbatine ne terminal and alter the way in which the program is executed from the menu. All that’s needed is to change cone line to another, so thatthe gksudo command is again used instead of the plain synapticpkexec. From the terminal type: sudo nano /usr/share/ applications/ BE synaptic.desktop Change Exec=synaptic-pkoxec' to. [ txec=gksudo synaptic-pkexec Synaptic fully working After youlve entered those 08 eres crtnono act followed by ¥ to accept the changes, ‘and then press Enter a couple of times to get back to the command prompt. You can now launch Synaptic fiom the menu, or by entering the folowing command when youre in the terminat BE exsudo synaptic Getting started What you'll need... Prototyping equipment RPi.GPIO hutps//pypLpython.ora/pypyRPLGPO ‘Above The PrsGPIO Port comprises 26 pn Tedtaconnect kth filmannerof eleetonic Componentaldevces GPIO port explained GPIO port explained an you think. The general-purpose input/output (GPIO) pins on your Raspberry Pi are often central to the success of the projects youll find in this book. Without them you have no way of interfacing with the real world, be itto trigger lights, buttons or buzzers or read sensors. GPIO pins aren't special to the Pi; theyre actually a standard designed to help control input and output behaviour with all kinds of integrated circuits. Usually you'l find that any one GPIO pin has no particular use pre-defined and they tend to be turned off by default. Raspberry Pi GPIO ‘The GPIO pins on the Raspberry Pi can be controlled and triggered in many ways. You can use them from the terminal directly and through Bash scripts, or you can control them using specially designed modules for popular programming languages. Since Python is the official language of the Raspberry Fi, you'llfind the GPIO module for Python gives you among the best control for inputs and outputs available. The library is called RPiGPIO and is installed by default on all Raspberry Pi, but can otherwise be installed in exactly the same way youd install any useful Python library. The projectiis hosted on SourceForge and can be found at sourceforge.net/projects/raspberry-gpio-python. You'll also find useful links, information and examples of how to use and control the GPIO pins from within simple Python scripts. Ithelps to have a basic understanding of Python if you plan to use RPiGPIO, so we'd recommend a basic introductory course like the one found at www.codecademy.com or by reading the official Python documentation at www.python.org/doc. There are 26 GPIO pins on the Raspberry Pi and you can use the vast majority of them in any way you want. There are a few pins that GPIO port explained Getting started have special purposes, though, so we recommend you familiarise yourself with their layout. For example, the very top row of pins are designed to offer power to external devices lke buttons and lights. ‘Since an earth line (often called ‘ground’ is needed to safely create a circuit, youll alo find several ground pins located in the GPIO port. ceeeemane lyoterihechno pond hat {yo somehive spec How to use GPIO pins Dubones che groond pe ‘To exploit the power of the GPIO port you'll need a few essential components, the most important of which are jumper leads. Since the pins on the port are male’ you'll need to purchase either ‘female to male’ or female to female’ cables, depending on what hardware you intend to connect to your Pi. Assuming the device youre connecting to also has mail connectors, ‘female to female’ jumper leads will do nicely, but often youlll be using a breadboard to prototype your circuits, in which case ‘female to male’ connectors are preferred. Cables and breadboards can be bought very cheaply from just about any online store that sells Raspberry Pi accessories and can usually be found in the ‘prototyping’ section of the store. Naming conventions Once youte ready to connect your device, the next task is to find the right pin for the job. While i's true that all GPIO ports are multipurpose, some are more multipurpose than others! As we've already discovered, some pins are reserved for 5V, 33V and ground. Others also have special capabilities, but what’s worse is that they can also be called different things. For example, GPIO 18 is also known as pin 12 and PCM_CLK. This particular pin (around halfway down the right side ofthe GPIO port) is capable of hardware pulse- width modulation (PWM), and is useful for controlling LED lights and motors among other things. The pin-naming convention you use in your Python scripts can be ‘set manually. This can either be set as BCM (the Broadcom pin name) or the physical pin locations (BOARD). Youlll see in any of the projects where we're using the GPIO port, the following line with either BCM or BOARD in the brackets: I crto.setmode(r10.B0y) The easiest way to deal with the GPIO pin-naming issues is to pick a convention and stick with it Getting started Top four add-on boards PiTFT Mini Kit £30 Thisis a 28-inch capacttveTFTLCD touchscreen that'sbeen specifically designed with the Raspery in mind by the project qurus over at al Adafrut. i's capable of siotting directly ‘on top of the Raspberry Piandis about asbig as the Piisitselt. ‘There are numerous reasons why Get more out of your Raspberry Pi by using these youd wenetonudsicha siento id-on boards to extend its functionality a Raspberry Pi but they all generally add-on boards to extend its functionality ‘come down tothe fact that the Pi ._{syerysmall and very portable and ‘most monitors are not. While you ‘could remote connect via VPN from a phone ifyoue an the go, the screen isconnected directly tothe Piand doesntinvalve awkward wireless networking. Also asa touchscreen you dontt need to bring along other input devices, asit’s powered offthe Raspberry Pi as wel Thisopens itup toa world of possiblities. Portable compute, touchscreen contro pad, video ‘camera...aiything that could benefit from your Raspberry Fihaving ascreen and human input while away from your main monitex Pi Supply Switch £15 “The Raspberry Pihas been so popula in part, because of the extremely {good value for money ofthe harchvae. packs alot of punch forthe price point and, because tis designed by a charity, they donttneed to inflate the price with high proft margins (Consider how much it would cost as 2.commercial product) Unfortunately 2s wth anything low-cost, some compromises had to be made in ade to bring tint such an affordable and small form factor ‘When comparing itto your mare standard desktop orlaptop computer, ‘two things that its obviously lacking are a power switch and power ‘management functionality tis surprising how something as simple asa power switch can be so very useful, and isnot until you do not have one that you reals this The Pi Supply Switch isa selfsolder kit which providesan on, off and soft-of ile-safe shutdown) button to give you basic power management functionality for your Pi. With some provided sample scripts youcan make sure your Pls correctly shut down when you switch off without the need to open any menus or issue any commands in the terminal - and the Gicuitryin the switch ensures that poweris only removed ater the Pi has been shut down, As wells making it more corwenient for yout also reduces the possibilty of cotuption to your SD card from prematurely pling the power cable Top four add-on boards HiFiBerry DAG+ £30~ As high qualty audio device, meanwhile, youmay find the Raspberry Pi lacking due to the fact it enly hasa 35 mm stereo output that sit suited tohigh fidelity You have probably dreamed of enhancing the audio and taking your setup to the next level The good news isthatthe clever folkat the Raspberry P Foundation have provided access to the 25 pins intlly onthe seperate 5 header, and nowon the As, Respberty Pi 2and 3it is available from the main 40-pin GAO header [2Sisa communications protocol designed specifically for audio devices and has enabled a ‘number of companies like Hiiery and Iaudt0 to caeate high qualty audio add-ons The HiFiBerry DAC is anadd-on which brings@ high resolution (1922, 24-bit Bur- Brown digita-1o-analogue converter to your it has hardware volume control using Alsamiser,among other features, and a itisa HAT-compatible board. works plug-and- play out ofthe box withthe latest Raspberry Pi firaares, and with all the popular operating systems for both standard use and media playback, such as Raspbian, Arch Linux, OSM, Open€LEC, Volumio,FiMusicBoxand many more. Ifyouare serous about your audio quality and wantahigh quality ow cost, Internet-connected solution, then you no longer have any excuse — you can build your ‘own for under £100, “The Energenie Pi-mote control starter kit contains two remote-controlled plug sockets which can be turned on and off” Getting started Energenie Pi-mote £20 Home automation isall the age atthe moment;autorating tasks tke fiddling with heating contalsend turning off the lights before you go to bed can make ‘urlives much ease. One thing that we ae always told istotum off devices atthe plug rather than leaving them on standby, 2s they usealotof electricity when not propery turned off This whete the Energenie Pimote contol starter kitcomes nt contains two remote-contilled plug sockets which can be tuned onand off with an BF remote What does this have to do withthe Raspberry PI? Well you aso get an add- ‘on board to enable you tocontral the sockets via softwareon the Raspberry 6, which unleashes whole new possibilities you could set your ampstoturnon and off automaticaly at specified times ‘when you are away to deter burglars, or create basic web app to control your plug sockets remotely using your smartphone alone. They only come in UKand EU plug types soif you usea diferent plug then you may need took for something ese {and maybe send Energenie arequest to make more versions. cts Back up your Pi vee Back up your Pi External storage Take the initiativ nake sure While the Raspberry Pisa very solid piece of kit, failure can happen, TT To) so it's best to be well prepared and keep your files safe The good news is that the Pi’s files are all kept extemally on the SD card. If your Pi breaks, everything will sil be available on the SD card and accessible from elsewhere. The SD card is still susceptible to problems, though. There are a number of ways to back up a Pi The methods can be broken down into two main categories: saving the important files and creating an exact copy of the state of the SD card. The former involves having copies of files elsewhere, while the latter has you create the same kind of image that youd normally waite to the SD card when installing Raspbian cor other Pi-operating systems. Important files To save important files, we need to create a copy on an external source, such as external hard drive or another PC. One of the best methods to do this doesn't even involve a Pall you need is, aPC or laptop with a card reader and you're good to go. Tum off your Pi, unplug it and remove the SD card from the slot. Find the SD card reader on your PC and slot itin The main file system of the SD card can be read by Linux PCs by default, and a Windows or Mac computer once you've installed a program that lets itread the ext file system, such as Ext2Fsd.On Windows, the SD card will be listed with the rest of the drives under My Computer (Fig 1). On Linux and Mac it wil be listed wherever storage is shown on the menus and file managers. Once you've found the SD card on here, open it up and navigate to home and then pi. This is where the Documents, Downloads, Desktop and other directories can be found. All you need to do is select the files you want to copy and move them toa secure directory on your PC or a connected extemal hard drive. Back up your Pi If you want to keep the files on another computer, that's fine, but it will be prone to the exact same problems as the Pi in the long tun. Keeping them on an extemal hard drive is a good idea, and putting them on a cloud storage service is better yet, enabling you toaccess them from anywhere with an intemnet connection (Fig 2) Cloning Creating a clone depends on what operating system youte using ‘on your main computer. For Macs and Linux, you can use a simple command-line tool called dd to create an exact copy of the SD card (Fig 3). This is done in the terminal emulator or command line, so bring that up first. Make sure the SD card is plugged in and enter: Is faisk 2 This lists all connected storage devices. The SD card will have 2, 4 or 8GB of space, depending on its size. It lkely be listed as something like /dev/sd, where x is the letter the computer attaches to the SD card. To copy it using dd, enter the following into the terminal: IDs dd if=/dev/sd[q of=backup.img bs=1M You can also add a path to the image you're creating to put it in a specific folder. The process will take some time, and will produce a mubt-gigabyte file which you can then write onto the SD by reversing the previous command: Is dd if= backup.img of=/dev/sdbd bs=1M While this is useful as a backup, you can also use the image to mass- produce SD cards to give to friends or keep in the various places where you use your Raspberry Pi Windows To create a clone on Windows, we can use the Win32 Disk Imager (Fig 4). Download it from here to install it: bit ly/LBJ4YG. ‘Once installed, insert the SD card and launch the software. Choose a name for the backup file and select the SD card from the list of devices. Now press Read and it will create the backup file. ‘Again, this might take a while; however, this time you are at least shown a progress bar. Storing your cloned image is alittle more difficult than your important files - the size of the image being in the gigabytes means it wil fil up a lot of cloud-storage services. If you have the space, definitely keep it on there; however, you may need to put iton an ‘extemal hard drive. Projects Fig 1: Accessing the SD card from another PCisaneasy aerate to ansfering Hes between machines via aUSB stick Fig 2: Goud storage services mahebacking upfles easy andsecue as theyrealot ss proneto problems Suse ety Fig 3 The dtoolis what youtluse ona nox and Maccompute andi'saaable by faultin the tral emulators ig Wina2 Dk imager makes backing up the entire OS easy and you can even useit Towrtetheimage back othe SD card Beginner's guide to nano vom, Beginner's guide to nano ff you have the itch to do more with your Pi, one of the skills youll need to lear to pull off many projects is the ability to edit system files. The command line text editor nano is definitely one of the best tools for the job. Text editors are very basic tools; the clue is in the name in this case. There's no formatting or colouring or anything - of the sort you would get in a word processor, but that’s the point. he kind of files you'l be creating or editing will generally contain code - code which doesn’t require to be made bold or bulleted. nano removes all of these distractions, but still has a few of the more handy features you find in a graphical text editor. Well teach you how to make the most out of nano to make your projects run quickly and efficiently Create plaintext fiesinthe commandline even rte ome cadeforapregram Fekisystem flestosut your needs and projects ‘rthout digging tough a Hlemanager Search, copy,pasteand invert tonttomanothe: fe {ing some ofthe bulin rang finetons Open nano Once commandline, and si nano This willopen a From here you can createa simple text file such 1 create system file, script or piece of code. How the system interprets your file depends on what you wnite and how you save it Save and continue (Once you've finished wath ‘out using Ciri+O. All shortcuts and functions such as this are done using Cirlanda letter key. twill ask you what name to save the fle under. Whatever you nameit it wll be saved in the directory you opened nano from Unless you specify a path. _—— Opening files To edit already existing fi O38 yectttstreedotnow hc location and name. To open them in nano, type the folowing Is nano /path/filename For example, to edit fstab you ul type: Bs nano seterfstab Beginner's guide to nano Projects Save and exit Once you've finished 04: wodifying the file and need to geton with the next task you can press Cirl4X to exit nano. twill ask if you want to save any modifications which just requires a ¥ to confirm. Ifyou want to exit without saving changes, you can just use N.To cancel before making a decision, use Cul+C. Copy and paste 0 This is more of a terminal- ‘specific command, but it can suns the eran your raphial ext eer Once highlighted, pressing CursShift+C w Copy any text. Crl+Shife+V wall paste. Insert from file Ifyou need to directly insert theresa quick way to do it wthout needing to use copy and paste. Typing Ctil#R and entering the path to the fle wll insert itinto the spot your cursors. Advanced navigation 07° probably been using the arrow keys to move one spaceata time left, right, up or down. There are other ways to move around the ile, though Using Cirl+A wil act the same way as the Home key does ina graphical editor, moving the cusorto the start of the line. Same with Ctrl#£ moving you to the end like the End key. CultV is page down, and Cirle is page up, Searching a file Sometimes you'll be looking a large text ile. Instead of using the arrow keys and tirelessly reading every line, you can use the search function via Cit. Entering the search term will begin looking through the document, and once you're finished you can press Ci to exit the search Extra help There are many more 09 fincers rite nao, Fora fullist of commands, you can tse Ctrl¥G, which lists allthe shortcuts and what they do. The caret symbol () in this list denotes the use of Clon your keyboard, nn Projects What you'll need... TightVNC wtvightuncconvieease-27php Pye RT ran Cay for accessing VNC ree] ote Gain remote desktop access Gain remote desktop access mh get top with ss to your Raspbe being in front o VNC (Virtual Network Computing) is a graphical desktop access and sharing system that allows a user to remotely control and use the desktop of another computer from their own system, it’s handy in many ways: to give you control over a remote systern; to help out another user elsewhere; to allow a computer to remain powered on, but without the need for a keyboard, mouse or even a monitor. In our case, we aim to allow access to the Raspberry Pi desktop without it being hooked up to the aforementioned peripherals. This way, you can do everything you would normally do, but with just the power supply and network attached, thereby freeing up space and saving extra expense. In real-world terms, this means you could potentially access the Pi desktop via an Android tablet or phone. Fle Edt Tabs Help Static IP address OT Retarsersbomete sure that the Raspberry Pi hhas a static IP adress. Bascaly, an IP address isa group of numbers that your network assigns to devices in order totell them apart. To set up a static IP adress, simply double-click LxTerminal and type the folowing and then press Enter. [sudo nano /ete/network/ interfaces Static IP part 2 02 file controls the IP addressing for the P. You need 10 scroll down to the ‘face ethd line and remove DHCP and replace it wth static. Now, on the line directly below, enter the IP address that you wan force your Pito have, along with the subnet mask and the gateway: address 192.168.1.93 netmask 255.255.255.0 Jeateway 192.168.1.254 Static IP part 3 03 After you've entered those details, exit nano by pressing CirisX, followed by ¥ to accept the changes, and then press Enter a couple of ies to get back to the cornmand prompt in the terminal. You can now either reboot your Pj or type the following into the terminal Jou /tcinitnetserking stp Bsudo setcrinit.d/networking start Installing VNC part 1 Gain remote desktop access 0. 4 Now well install VNC and ensure that it starts automatically whenever the Pi's booted up. This used to be a bit annoying under older Raspbian versions, as configuring services often had a nasty habit of breaking the system. But no lon ete following com i= apt-get update mands, pressing Enter after each one: sudo apt-get install tightvneserver Btightyncserver Hle Edt bs Hey Installing VNC part 2 05 Wretepecageshave downloaded and installed, follow the instructions on screen (Gee below) to set up a password and confirm ft, but answer ‘n' tothe view only option. This really i just a security feature and since you are only accessing the Pi at home, i's not absolutely necessary - is stil good tice, though, [vou witl require a password to access your desktops Password: Verify [vould you like to enter a viewonly eo Gin? n New °%" desktop is raspberrypi:1 Configuring VNC server 06t installed, up and running Now we need to make sure it loads pasa service everytime the Raspberry Pi reboots, so you can access iteven ifthe Pi undergoes a power cycle. To configure the Pi to do this, type the following inthe terminal and press Enter. Houde nano /etc/init.0/ tightvneserver Configuring boot service We're back in nano, and we'll 7 wesweeecont tes of commands in order to allow the Raspoery ito activate the VNC sever wren itboots the edt rm # /etc/init.d/tightvneserver Be sce the Wousee variable to ie md Of" "ne Mm toate tightyneserver under Bvcser-pir case “$1” in start) su SYNOUSER =c ‘/usr/bin/ tightuneserver 1° Hecto “Starting Tightwne server for” SYNCISER" stop) pkill Xtightvne echo “Tightvneserver stopped” » Becto “usage: /etesinit.d/ tightuneserver {start|stop)” exit 1 Bese Beico Projects Reboot and ready to go Now press Cirl4X then ¥ 0 beep rer couple of imes to get you backinto the Terminal. What we need to do now is edit the permissions of the script we've just created so that is executable and active. Do this by typing the following commands into the terminal, ensuring that you press Enter after each one otherwise it will rot be registered. [suco chnod 755 /etc/init.o/ tightyneserver Bpdate-re.d tightvneserver defaults sudo reboot Once you have completed these steps, the final thing that you will need to do isto unplug the Raspberry Piand locate it someihere that has easy access to.a network cable If you install the likes of Tight¥NC Viewer, or any other remote access software {@5 long asit uses the Tight protoco)) then you should be able to point the lent to the IP address 192168193: (or whatever the static IP address is of the network that you wish to connect the device to) and have full access to the Raspberry P. 45 Projects What you'll need... Any Raspberry Pi distro ‘nwvraspbemypuore/downlesds Internet connection Second computer Fig : Use thefeonfig command inthe terminal to Sscover the address of your Raspberry Access your files with SSH Access your files with SSH uter to gain Derry F While remotely logging into the full X environment is ~ as we demonstrated on the previous pages - very useful, it has its disadvantages. Firstly, it's not particularly quick or convenient to do. The user experience can be slow and cumbersome too, but worst of all, it’s not as secure as wed really lke. IF you want to take a more convenient and secure approach to accessing your Raspberry Pi from another computer, youlll find that all well-versed Pi enthusiasts will use SSH. SSH stands for Secure Shell and is a cryptographic network protocol which is designed to ensure secure data communication via the command line. While beginners might argue i's easier to remotely access their Raspberry Pi using the full graphical interface, as soon as you've leamt a handful of basic commandtline techniques you'll quickly find ‘dipping in’ to your Raspberry Pi via SSH is by far the most convenient way to talk to it remotely. You'l be pleased to hear that SSH is already well configured out of the box — there's very little you need to do to make it work, especially if your remote computer runs Linux ar OS X, as we're going to demonstrate here. SSH is easy with Linux and OS X Assuming your Raspberry Piis on and connected to a network either by Ethernet or a Wi-Fi dongle, the only piece of information you need is the IP address of your Pi. To discover this, all you have 10 dois open a terminal window on your Raspberry Pi and type the command ifconfig (Fig 1). If you're connected by Ethernet cable you'll see ‘etho, then several lines of results. The IP address will be the number on the second line next to words ‘inet addr’ If you're connected by Wi-Fi, Access your files with SSH the result will be on the second line of Wwlan0! The IP address itself is a group of four numbers separated by full stops. If you're on your home network, it wl ikely be similar to 192.168.0.15. Well use this number for our guide, but replace it with the IP address you've seen via ifconfig. With this information in hand, all you need to dois open a terminal window on your remote Linux PC and type: H ssh picis2.168.0.15 This assumes your Raspberry Pis username is still the default (which is pi) and you'te replacing the IP address with the one you made note of just now. f you've added user accounts or changed the defaul, youll need to replace the username before the ‘@' with whatever you've changed it to. When you press Enter, you'll be prompted to enter the password for your Raspberry Pi - again, if it’s the default you can type raspberry, otherwise type in your Pi’s password and press Return. Youll now see that the username details on the command line have changed to reflect those of your Raspberry Pi- youre now connected remotely. Ty looking through your files or using nano to opena file to edit it! Never type another IP address Of course, if you take your Raspberry Pi to another network, your Ps IP address will be different. If you just want to connect to it remotely, it becomes incredibly tiresome to set up your Pi with a keyboard, mouse and monitor just to get the IP address. Wouldn't it be easier if you could just type the Raspberry Pi’s name into the terminal to connect? It sounds too good to be true, but it's actually very easy to do. All you need is a small piece of software which effectively lets you discover hosts and services on your local network by name instead of IP address (Fig 2). To set it up on your Pi all you need to do is open a terminal and type: BE sudo apt-get install avahi-daemon Once the installation is complete, all you have to do to access your Raspberry Pi via SSH is type the following into the terminal: II ssh pieraspberrypi.local What’s more, you can use the name of your Raspberry Pi when you access it via any ather form of networking, be it Samba, remote login with VNC or anything else. Projects SSH with Windows ‘Asis the way with most things in the Windows world, accessing your Raspberry Piwith Microsoft's operating system isn't quite as straightforward as you'd think Fortunately there is a useful tool to help. Putty allows you to make your Secure Shell connection and it's easy to set up and use. You can download Putty from: \wwwichiark.greenend.org.uk/ ~sgtatham/putty Fig: Te Ava toolenablesyouto log Imo your Fi via Se by name, ater than needingtodscoveritsPadaress @ Projects Raspberry Pi plus Arduinos Find out just how to get y alk to and use your A\ erry ‘The Raspberry Plis a truly amazing single-board computer that gets used in lots of DIY projects. ‘That has been the basis for this whale column and the previous several articles. While the Raspberry Pi has a GPIO and can communicate with sensors and actuators, you may have cases where you want to use your Raspberry Pi as the brains of your project and offload the interactions with the physical world to another system, Thisis usually handled by one of the many microcontroller boards that are available. In this issue, we will specifically use the Arduino board and see how to connect it to a Raspberry Piand how to handle the communications between the two. As always, we will be using Python as the language of choice to handle all of the actual coding in the examples here. The Arduino is an open source prototyping platform defined as a specification. This means that you can get Arduino implementations from several different manufacturers, but they should all behave in a similar fashion. For this article, the assumption will be that whatever implementation you wish to use will behave properly. The first step is to connect the two boards together. You Pi Raspberry Pi plus Arduinos will probably want to use a powered USB hub to. connect them since the Raspberry Pi can't provide huge amounts of power through its USB port. While they are connected over USB, the Arduino will appear as a serial port to the Raspberry Pi This means that you can communicate with the Arduino directly over the serial connection. To be completely sure you have all of the relevant libraties installed, you can simply install the Arduino IDE with the command: H seo apt-get install arduino This will make sure that you are starting with all of the core software that you might need. When you plug in your Arduino, you need to know over which port communications will happen. The specific port name will vary based on the exact version of Raspberry Pi and Arduino that you are using. However, it should be something like Zdev/ ttyUSBO' or /dev/ttyACMO. In the example code below, we will be assuming that the Arduino is visible on the port /dew/ttyUSBO. Once you have the two devices connected, you can start writing code to have them talk to “For this article, the assumption will be that whatever implementation you wish to use will behave properly” Raspberry Pi plus Arduinos each other. We will start with the most low-level protocols and build upwards from there. The first step is to open a serial connection to the Arduino. In order to do this, you will need to make sure that the Python serial module is installed. f you are using Raspbian, you can do this with: IH suco apt-get install python-serial You then need to create a new Serial object connected to a given serial port, along with the speed you need to use. import serial ser = serial.Serial(‘/dev/ttyUSB0", 9600) In the above example, the speed is 9600 baud (bits/sec). With this Serial object, you can read and write data to and from the Arduino, But you need code on the Arduino to handle its part of this communication. The Arduino has its own programming language, based on C, which you use to write the code that will un on the board. The way Arduinos work is that at bootup itwill load a program that will run as long as itis powered up. Asa simple example, the following code wil listen on an input pin to see ifit goes high. fso, it will then fire off a message on the serial port. int pirPin = void setup { pinMode(pirPin, INPUT); Serial. begin(9600); 3 void loop() { if GigitalRead(pirPin) == HIGH) { Serial.printIn¢*High"); } delay(50e); I> Projects To load this program to your Arduino board, you will need to use the Arduino IDE that was installed at the beginning of tis artide. This is a graphical program, so you will need to connect your Raspberry Pi to @ monitor if you want to do this step using it. Otherwise, you can do this programming of your Arduino using your requiar desktop. if you are using the standard bootloader ‘on most Arduinos, it will start up whatever program was last uploaded to it. This way you can use your desktop to upload your code and then connect it to your Raspberry Pi later on, Moving back to the Raspberry Pi, how can you read this, message from the Arduino? You can simply do a read from the Serial object that you created earlier. import time while True: message = ser.readline() print(nessage) if (wessage[@] == ‘H') do_sonething_useful() time. sleep(.5) ‘Asyyou can see, we imported the time module in order to be able to sleep in the loop between attempts to read from the serial port. What about sending instructions out to the Arduino? This is also requires Arduino code to be uploaded ahead of time. For example, the following code will take an input number andflash an LED that number of times Hint teaPin = 13; void setup { pinMode(ledPin, OUPUT); Serial begin(9600) ? void loop) { if (Serial available) { i flash(Serial.read() ~ ‘@"); y Projects delay(1000); > void flash(int n) { for (int i= 0; i Then, you can send a count from your Python code with something like: EE serswritec's') This will flash the LED 5 connected to pin 13 on your Arduino five times. One missing element on the Raspberry Piis an analogue-to-digital (ADC) converter to take a given voltage and turn it into a number that can be used in some piece of control software. This is where attaching an Arduino can be extremely helpful, as it has a 10-bit ADC converter included. The following code will ead the voltage on pin 3 and then send it out over the serial connection to the Raspberry Pi int analogPin = 3; int val = 0; void setup) € Serial.begin(9609); y I void loop() { val = analogRead(analogPin); | Serial.printIn(val); + This maps the measured voltage to an integer between 0 and 1/023. The minimum voltage is zero, while the maximum voltage can be set with the function analogReference(. By default, the maximum is the power supplied to the board (5 Raspberry Pi plus Arduinos volts for 5V boards, or 33 volts for 3.3V boards). You can also use two internally supplied reference voltages, one at 1.1 volts and a second at 2:56 volts. For special cases, you can supply an external reference voltage to the AREF pin. You need to be sure that its only between O volts and 5 volts. Going in the opposite direction, you can use the Arduino to supply an output voltage. This is done by using a PWM (pulse width modulation) ‘output signal. The idea is to actually send out a number of pulses with some duty cycle that is on for some percentage of the time and off for the remainder of the time. For example, if you have an LED connected to one of the pins, you can light it at half brightness with the following code. int ledPin = 8; void setup() { pintode(ledPin, OUTPUT: } void 100p0) ¢ analogWrite(ledPin, 127); bb The second parameter to the analogWrite0 function is a value between 0 and 255, which defines the duty cycle between 096 (or fully off) to 100% (or fully on), This analog output signal stays on at the given duty cycle until a new call to the analogWritel) function. By having your Raspberry Pi write out values over the serial connection, it can then control the output duty cycle by sending a simple integer. This short article will spark some ideas on how you can start combining multiple computing platforms to expand the capabilities of your own projects. There is no reason to try to find the one silver- bullet platform for your project when you can pick the sub-modules that actually do their own individual jobs best and build up the complex behaviour you need from these simpler parts. Raspberry Pi plus Arduinos Projects PyFirmata can help even more Discover wi S to make interactin: While you can write your own code to run on the Arduino, there are several projects that can be uploaded to it to make interacting a bit easier. One of these is the Firmata project, which includes a Python module to help you talk to the Arduino. The frst step will be downloading the Firmata Arduino code and uploading it to your Arduino, most easily done with a desktop computer. The code is available at github. com/ firmata/arduino. There are a few different versions available, but for these examples you should upload the StandardFirmata sketch with the Arduino IDE. There are client libraries available for many different programming languages, including several for Python. The one we will look at using is pyFirmata. You can install it on your Raspberry Pi with: I suxo pip install pyFirnata You can now use Firmata to act as a sort of remote control to the Arduino port, where your Python code can get almost direct access to all of the functionality available. To get started, import the pyFirmata module and create a new Arduino object connected to the relevant serial port: import pyfirmata board = pyfirmata.Arduino('/dev/ttyUS80") You can now access digital /O pins directly. For example, the following code would write a 1 10 pin 10. H board.digital(ie}.writea) easier When you want to read from 2 pin, you have the possiblity of overflowing input buffers. To deal with this issue, you can create an iterator object and start it before doing any reads, using code like that below. it = pyfirmata.util.Iterator(board) it.startQ) You can now get selected pins for either input ‘or output. The following code will get pin 4 for digital input and pin 12 for analogue PWM output B pint = board.get_pin(sd:asi*y Hpi = board.get_pin(‘a:12:p’) You can then read and write with these new pin objects with the related methods: val = pind.read() pinl2.write(1ea) When you are done, don't forget to reset any ‘output pins back to 0 volts, and then you can close down the connection with: BD board.exito, “There are a few different versions available, but for these examples you should upload StandardFirmata sketch with the Arduino IDE" Projects What you'll need... Scratch Internet connection Did you know. The wel meee eee Scratch studio projects 0 Located at the top of the Studio are three quickaccess icons and the main menu (Fig 2) The first globe-style icon sets the language for the Studio. The other two buttons provide rapid access to the project save and share features Under the File’ menu there's atypical set of fle-management features to open, save and import Scratch projects. There is also a ‘Project Notes’ option where we are able to enter feature descriptions and comments. The ‘Edit’ menu contains a mixed bag of animation, image and audio- editing tools. While the Help’ section Program with Scratch Program with Scratch An interactive guide to coding with the Pi's graphical programming language Would you like to delve into the world of animation and game creation? Do you want to bring your creative ideas to life without leaming a software-development language? With Scratch you can do all this, and much more. Scratch 1.4is already installed on the official ‘wheezy’ Rasobian operating system image. if your Raspberry Pi doesn't already have Scratch installed, don't worry, just hop on over to the official MIT Scratch website to find the download and install instructions, To begin, all we need to do is open the Scratch Studio. Click (on Scratch’s cat icon on the desktop, or find Scratch in the LXDE desktop menu. The Scratch Studio is a complete development environment, Its divided up into a number of separate panels. Each panel has a specific role in the app-construction process and its own specific set of features and tools. provides access to the browser-hosted help pages Rather interestingly, the ‘Share! menu allows us to share our projects ‘with the whole world. Any Scratch project can be posted onto the Scratch community website via the ‘Share This Project Online...’ option and the Upload To Scratch Server’ form (Fig 3. Let's load the Aquariury’ example project Select the Open... option in the File’ menu to display the Open Project dialogue. From the list of large buttons on the left, cickon the ‘one called ‘Examples’ Next, on the right, select the Animation folder with a double click. Then select the 6 ‘Aquarium’ iter. The open dialogue ‘window contents should looklike the ‘one in Fig 4 With the Aquarium project loaded ur Scratch Sudio should look similar 10 Fig 1. Wellbegin our Studio tour with the staging area, Program with Scratch Projects eee NE re Ovewh ac a rr Open... Ee Cyt ced Import Proje¢ Pearce (Gr @ ED File edit s New Save Save As... Fig3: Project Shae Dialogue We can share our projectsusingthe Stuios Share menu Export Sprite Project Notes Quit Fig File Open Dishogue— Use the Sau’ Fle Fig 2: Scratch Studio Menu Scratch tudo’ main menwand shorcuticons inaction mmenuand Open.’ tolesdthe Aquarium project Scratch studio stage 0 The stages where athe action takes place ands located at the upper right of the Scratch Studio. The stage is constructed from graphical elements called sprites. Here we have plants, bubbles, fish and other creatures. You can also add and create your own assets with scratch, but well come to that ater. Atthe top of the ‘Staging Area’ there's a green flag and a red circle. lick on the green flag to bring the aquarium tolife. Now spend a little time studying the Aquarium animation, Note the creature's movements and rising bubbles. The red circle icon stops the action, We can set the view made with the three buttons located just above the green flag. The two left-hand buttons increase or decrease the size of the Staging Area panel. A smaller Staging Area means the central area of the Studio increases in relative size compared, The right-hand button is the Presentation Mode which displays the stage in fullscreen mode (see Fig 5) Exit presentation mode with the curly arrow button at the top left, or press the ‘esc’ key. Scratch studio sprites 03 Beneath the Staging Aea isthe collection of sprites for this project. The ‘Stage’ sprites separated from the rest.’ a litle diferent tothe others and acts as the background image for the stage. The three buttons across the top of this area offer various ways to create a ‘new sprite. The frst button opens up a blank canvas in the Paint Eitor. The second button creates anew sprite based in an image fleas selected by the popup file section dialogue window. The third wil select a random image from the pre-installed image collection We can manage sprites directly from the stage using the four buttons to the right of the main menu. Here we click on a particular button and then a sprite on the stage. Fig Stage Presentation Mode ~The Suds stage presentation models the best ay to see the project Projects Program with Scratch Use Scratch blocks and tools Getting to grips with the Scratch Studio toolbox Situated in the centre of the Studio is the Edit Panel. The panel contents relate to the currently selected sprite. Let's start by selecting the jelly ish sprite, called Creaturel, from the Sprite Collection area At the top we have the sprites image and name, plus an indication of its current stage coordinates and direction. On the left are three animation control buttons. The top button will rotate the sprite, the second switches between left- and rightfacing states, and the third tums animation off Below are three Ecit Panel tabs. The script tab is where block scripts are created. Here's where welll drag and drop our blocks, snapping them together in various combinations. To change a sprites visual appearance welll use the ‘Costumes’ tab. Each sprite can have one or more costumes. For example, the jellyfish has two costumes (Fig 1). Each costume has buttons to edit, copy and delete. New costumes can be painted, imported or captuted using the three ‘New Costumes’ buttons. The sound tab allows us to add audio to our project. farrici ee Jellyfish1 feat Bf copy ] BO anied Fig: Jesh Sorte Costumes ~The elvis spite has two diferent costumes Scratch block styles 0 The ‘Blocks Palette’ contains the complete collection of scripting blocks. Blocks come in three basic styles, namely hats, stacks and reporters (see Fig 3 on the opposite page). A nhat-style block will start block Script execution based on a specific ‘event. The classic hat block is the ‘green flag’ click event. However, there are numerous other hat blocks, including hat blocks that start script ‘execution after a specific key press, a mouse click and even following sensor event from the some GPIO ‘connected hardware. As you can. probably tell, this offers alot of ‘options to Scratch programmers, Reporter blocks allow us to specify textual, numeric and boolean values. They fitinto specific shaped ‘holes'in other blocks. rectangular reporter will contain a text string, While the rounded end reporters are associated with numeric values, angle-ended reporters contain boolean true and false values. Stack blocks are the core script building elements. They interconnect with other blocks via their top-edge notches and bottom-edge bumps. Many stack blocks contain ‘holes'for reporter style blocks, which will modify their operation depending on the specified reporter block valves. The Scratch block collection is divided into groups. We select a block group using the eight buttons located at the top of the Block Palette panel, namely ‘Motion, Control; ‘Looks’ and so on, These ‘groups are colour coded. Apart from aiding block selection this colour coding provides a visual due toa block's type when reading a block scriptn the Edit Panel Fig2: Sound Recorder Tool Scratch tut indudes a tool to record our own sounds Scratch block help UL functionality and capabilites, In one way this is great news. A large block collection means Scratch can bbe used in a vast range of software projects, such as games, animation, music, graphics, math, science, robotics, electronics and much more However, the wide selection of blocks can be quite a challenge for the novice Scratch coder. To help with this problem the Scratch Studio designers have included an informative set of block-centric help pages ‘A simple right cickon any block wil display a pop-up help page option. The help page contains context-specfic descriptions, graphical images and, where appropriate, a script example of how to use this particular block ig 4). tsa temic feature which greatly simplifies the process of deciding which blocks to use. More importantly studying these help pagesis a highly effective way to enhance our scripting skills and discover the potential contained within Scratch’ feature-rich block collection, QD Ase veseensthere ae many blocs each with their own spectic Eevg Hello! coat 2 ered Pree ced ao ET pick random €9 to &%) Fig3: Block Style Examples —the Scratch blocks come na numberof ‘ferent styles script walkthroug| () 2 Lets dia deeper into how Q)5 abiockscript works in practice. For this, we will use a simple Aquarium project block script From the ‘Sprite Collection’ panel select the Stage sprite. Then go back to the central ‘Edit Panel’ and select the ‘Scripts’ tab. ‘There's just a single block script. Starting at the top there's a ‘green flag’ hat-style block to kick offthe activity. Next there's a ‘forever Joop’ The blocks inside this loop are actioned until the stop button is pressed. This forever loop block contains two other blocks. ‘The first inner script block selects the next background image. Click on the ‘Backgrounds’ tab to view all the stage images. The second inner block simply pauses execution for ‘number of seconds. Setting the \alueto’? means that this sept will pause for a second before then performing the action specified by the next block. It’s important that you remember ese tes boteme orden the forever loop block. So, the stage background images willbe displayed in sequence for one second each 19 Block Help Window Eampleofthehalp ‘window assodated witha ‘a and wat block 5 Projects What you'll need... Scratch project archives warn scrtch mit edulecplore teaver Did you know... Egg sprite ‘Te Eog spite appears randomly on the screen and ets othe spits now when thas been eaten fouchedby the snake ongue) Snake sprite “he Snake te imovesthehead ‘Sound the tage aod drawsthe body behind Ratoaerect. clisonswththe Dodyoredge Tail ‘hen ence grou" ‘TheTal spite follows thehead,easingthe end ofthe body othe snake moves, ond pausing Create a Snake clone in Scratch Create a Snake clone in Scratch Design your own version of Snake to te new programming skills! your Here, we will create a version of the classic Snake game where you move the snake around the Scratch stage using the arrow keys. You control the head of the snake and must avoid a collision with either the body of the snake or the edge of the stage. The snake body grows longer each time you eat an egg. You get points added to your score for eating good yellow eggs and lose points for eating bad black eggs. There are also bonus sprites to eat for extra points By following this tutorial you will eam to create your own simple sprite graphics, send and receive broadcast events, use a list variable to store data, play sound effects, generate random numbers and use sensing commands to detect when a sprite is touching something, Paint the Snake sprite Oe Paintbrush icon to paint the Snake sprite. In the Paint Editor, draw a small ‘green elipse for the snake head and add a red rectangle forthe tongue Bad Egg sprite Itsimportant that the tongue isa ‘The Bad Eggsprteakoappearsrandomly different colour tothe head. Name butdecrensesthe scorewhen eter abo ‘rows insing gerung harderto avoid your sprite Snake. Create a Snake clone in Scratch ()°9 When the Snake tongue QZ touches the snake body or the edge ofthe stage, we are going twplay a Game Over sound. We need todd this sound tothe Snake spite \With the Snake sprite selected, click the Sound tab and choose Import. Select the Electronic>Screech sound. Se --.) Respond to arrow keys ()R Ds tour when key pressed {J commands from the Control palette, and four pointin direction commands from the Motion palette Configure them as shown so that the upartow changes the direction to (O degrees (up) and so on. Click the Green flag above the stage to test this, flake Snake variables 04 ) 4] Slckon the Variables palete F Make two variables, Score and Speed, that are visible to all sprites. Make alist called Next Direction which is visible to all sprites: it wil store the sequence of directions that the head takes. Only have the Score variable checked so it appears on the stage oe itialise Snake variables I Use a when green flag dicked JD Control command and initialise the Shake variables as shown, using ‘commands from the Variables palette We want to start each game with an ‘empty Next Direction lst, so delete all ofits entries. The Score must start at ze10.The Speed sets difficulty } palette to control the drawing of the snake body. You should also use commands from the Motion palette tomove the snake to the centre of the stage and point left at the beginning cof each game. The pens up until the snake is in the starting postion. In the next steps we'll use colours to check tosee if the head is touching anything itshouldnt UF anise’ command nested inside. We have a collision ifthe red tongue is touching the blue body (the head is always touching the body) or the Snake sprites touching the edge. Use the Eyedropper tool to select colours within Scratch. Handle Game Over OR Whenzcalon hasbeen UG cetecied, broadcast a Game Over event (youll need to create a new event) to the other sprites so they ‘an also react. Aso, play the Screech sound effect and stop all scripts so that the snake freezes in its curent Position atthe end of the game. Projects Handle movement Now handle the typical case QP wirere there is no colsion and the snake must move in its current direction. The pen is down soit will draw the body, The Speed variable determines how many steps to move. ‘Add the current direction to the Next Direction lst forthe tal to read Try outthe snake 10 sermons U sprite. will nave around ‘the screen in response to pressing the arrow keys. It will raw its body, which wil ust get longer and longer because we need the tal to erase it ‘And itil screech and end the game on detecting a collision Tee ners Paint icon to paint the Tal sprite. Draw a small green circle to represent the end of the tai. Name this sprite Tal The Tail sprite will follow the Snake and erase the end of ts tail so that the snake body doesn't grow indefinitely Py Create a Snake clone in Scratch lake a Grow variable pies bine aint TZ, sorts sorte only no other sprites need access to it The Grow variable is used to determine when the snake body needs to grow and the tail therefore needs to pause before following to allow the head to get further ahead. Handle events 2 The Tal needs to listen for two new events which you create as yourneed them, When it receives an Egg Eaten event from ane of the Fag sprites, it sets Grow=1 so that the tallcan pause. And when it receives Game Over event from the Snake, it must freeze tail Initialise the 7d tenth steen fais clcker TP to start the game, Grow is set 10 1 sothe snake gets a short body. Movetto the centre of the stage with the pen up and configure the pen to drawsa tral the same colour and size as the stage background so that it erases the body. Grow and move 4] Use a forever’ command to 1D seep thetal movi, Grow is Tit should pause and reset Grow to (0— this makes the body grow longer. Use the first value from Next Direction to set the direction and remove itso you geta new value next time. Move 162" tryout the Tall {O sprite. The snake won't keep ‘growing yet because it wont receive any Egg Eaten events. But the tal wll follow the snake head around the stage, erasing the snake body as it _goes by drawing over it with a white pen (whichis the same colour as the background), Create a Snake clone in Scratch Paint the Egg sprite lake Bad Egg 17 eee 0 Create the black Bad Egg in 7 Add another when green fiag F ‘conto paint a new sprite. in YU the same way as the Fag © I clicked! script tothe Bad Eag the Paint Editor, draw asmellyellow but using different graphic and the _soit setts size to the default 100% clipse. Name the sprite Egg. The Egg __Instruments>StringPluck sound, Drag when anew game is started and will appear randomly on the stage and the Egg’sgreen flag scripts ontothe then increases its size by ten every ten cause the snake to grow and increase Bad Egg tocopythem - justchange _ seconds. The Bad Egg will get bigger its score the sound that's played and reduce ——_and bigger and harder to avoid. the score instead of increasing it. om set size to €W) 0 tomo er ae Add Egg sou » Goto the Sounds tab for the Create Bonus sprite © Fg sprite and import the - - Percussion>Cymbal Crash sound. Or 9) Create the Bonus sprite in a similar way. You can choose the shape and youcan choose a different sound if 2 sound for the Bonus. Its scripts are similar to the Egg ones so you could youllke. This sound will play when the drag one of those to the Bonus sprite and work ftom that. Make sure you change snake eats an eag, the sound and increase the score by a random bonus. oe [-sermrs ¥ costumes Y senate New sound CE) CES cca go to x: pick random GE to Oe co) eo Lis) Cd oa Add Egg scripts oe eae 19 Sorynetaa sci so thar the Egg appears randomly at the start of the game. When the gg senses thatt has been eaten, it must hide, play the Cymbal sound (orwhatever you chose in Step 18) Update the score, broadcast the gg Eaten event and then randomly appear again. When the Game Over event is received, it must stop. Projects Check your mail Check your mail With Python, you can have your Raspberry Pi act as mail checke 1g list on incoming email giving you a rur Since the Raspberry Piis such a small computer, it gets used in a lot of projects where you went to monitor a source of data. One such monitor you might want to create is a mail-checker that can display your current unread emails. This issue, well ook at how to use Python to create your ‘own mail-checking monitor to run on your Pi. Welll focus on the communications between the Piand the mail server and not worry too much about how it might be displayed. That will be left asa further exercise. To start with, most email servers use one of two different communication protocols. The older, simpler one was called POP (Post Office Protocol), and the newer one is called IMAP (internet Message Access Protoco), We will cover both protocols to cover all ofthe situations that you might run into. Welllstart with the older POP communications protocol. Luckily, there is support for this protocol as part of the standard library In order to start using this protocol, you will need to import the poplib module, and then create a new POP3 object. For example, the following will create a connection to the POP server available through Gmail. import poplib T ny-p0p = poplib.ar3_ssi chost="pop. gmail.com’) You need to use the POP3_SSL class when connecting to Gmail because Google uses SSL for its connections. If connecting to a different email server, you can use POP3 to make an unencrypted connection. The POP communication protocol involves the client sending a series of commands to the server to interact with it. For example, you can get the welcome message from the server with the getwelcome() method. E y-p0p.getwelcome() The first things that you will want to communicate to the server are the username and password for an email account that you are interested in. Having the username in your code is not too much of a security issue, but the password is another matter. Unless you have a good reason to have it written out in your code, you should probably ask the end-user for it. Included within the standard library is the getpass module, which you can use to ask the end-user for their password in a safer fashion. You could use the following code, for example. mmy_pop.user(‘my_name@gmail.com’) I import getpass ny.pop.pass_(getpass.getpass()) “The first things that you will want to communicate to the server are the username and password for an email account" Check your mail You should now be fully logged in to your email account. Under POP, your account will be locked until you choose to execute the quit) method of the connection. If you need a quick summary of what is on the open server you can execute the stat() metho: BH ny_pop.stat This method returns a tuple consisting of the message count and the mailbox size. You can get an explicit list of messages with the list() method. You have two options for looking at the actual contents of these emails, depending on whether you want to leave the messages untouched or not. Ifyou want to simply look at the first chunk of the messages, you can use the top() method. The following code will grab the headers and the first five lines of the first message in the list. B emait_top = my_pop.top(t, 5) This method will return a tuple consisting of the response text from the email server, list of the headers and the number of requested lines, and the octet count for the message. The one problem with the top) method is that itis not always well implemented on every ernail server. In those cases, you can use the retr() method. t will retuin the entire requested message in the same form as that retumed from top() (Once you have your message contents, you need to decide what you actually want to display. ‘Asan example, you might want to simply print out the subject lines for each message. You could do that with the following code. for line in email_topft]: if “Subject” in i: Projects EB print You need to explicitly do the search because the number of lines included in the headers varies between each message. Once you're done, don't forget to execute the quit() method to close down your connection to the email server. One last thing to consider is how long the email server will keep the connection alive. While running test code for this article, it would frequently time our. f you need to, you can use the noop() method as a Keep-alive for the connection. ‘As mentioned previously, the second, newer, protocol for talking to email servers is IMAP. Luckily, there is a module included in the standard library that you can use, similar to the poplib module we looked at above, called imaplib. Also, as above, it contains two main classes to encapsulate the connection details. f you need an SSL connection, you can use IMAP4_SSL. Otherwise, you can use IMAP4 for unencrypted connections. Using Gmail as an example, you can create an SSL connection with the following cade. [import imaplib import getpass ayy-imap = imaplib.IMAP4_SSL(‘imap.gnail.con’) ‘As opposed to poplib, imaplib has a single method to handle authentication. You can use the getpass module to ask for the password. Hi ny imap.1ogin¢my_usernameegmail.con’, getpass. getpass()) IMAP contains the concept of a tree of mailboxes where al of your ernails are organised. Before you can start to look at the emails, you need to select which mailbox you want to work with. Ifyou don't give a mailbox name, the default is the inbox. Projects This s fine since we only want to display the newest emails which have come in, Most of the interaction methods retum a tuple that contains a status flag (either ‘OK’ or’NO?) and a list containing the actual data. The first thing we need to do after selecting the inbox is to search for all of the messages available, as in the following example. [ rysinap sotecto typ, emait_aist = my_imap.search(None, ‘ALL’) The email_list variable contains a list of binary strings that you can use to fetch individual messages. You should check the value stored in the variable typ to be sure that it contains OK. To loop through the list and select a given email, you can use the following code: H for nun in email_tistte).splito: Hyp, emait_raw = my_imap.fetch(num, “(RFC822)") The variable email_raw contains the entire emnail body asa single escaped string. While you could parse it to pull out the pieces that you want to display in your email monitor, that kind of defeats the power of Python. Again, available in the standard library is a module called email that can handle all of those parsing issues. You will need to import the module in order to use it, as in the example here. import email email_nesg = email.message_fron_bytes(email_ raw(e]C1]) All of the sections of your email are now broken down into sections that you can pull out much more easily, Again, to pull out the subject line fora quick display, you can use the code: Check your mail IE subject_ine = email_mesg.get(‘Subject’) There are many different potential items that you could select out. To get the ful list of available header iterns, you can use the keys method, as shown below: Bi enait_nesg. keys) Many times, the emails you get will come as multi-part messages. In these cases, you will need to use the get_payload() method to extract any attached parts. It will come back as a list of further email objects. You then need to use the get_payload() method on those returned email ‘objects to get the main body. The code might look like: payloadl = email_mesg.get_payload(){@] body! = payloadl.get_payload ‘As with POP email connections, you may need to do something to keep the connection from timing out. Ifyou do, you can use the noop)) method of the IMAP connection object. This method acts as a keep-alive function. When you are all done, you need to be sure to clean up after yourself before shutting down. The correct way to do this is to close the mailbox you have been using first, and then log out from the server. An example is given here: mmy.imap. logout() my_imap.close() You now should have enough information to be able to connect to an email server, get alist of messages, and then pull out the sections that Check your mail you might want to display as part of your email monitor. For example, if you are displaying the information on an LCD, you might just want to have the subject lines scrolling past. Ifyou are using a larger screen display, you might want to grab a section of the body, or the date and time, to include as part of the information. Projects “When you are done, you need to be sure to clean up after yourself before shutting down” What about sending emails? io send as well as receive Find out how t Inthe main body of the article, we have only looked at how to connect to an email server and how to read from it. But what if you need to be able to also send emails off using some code? Similar to poplib and imaplib, the Python standard library includes a module called smtplib. Again, similar to poplib and imaplib, you need to create an SMTP object for the connection, and then log in to the server. If you are using the GMail SMTP. server, you could use the code import getpass my_smtp = smtplib.SMTP_SSL(‘smtp.gmail.com’) B sess inctatn.evotiteet) com, eetcans, getpass()) [ import smtplib This code asks the end user for their password, but if you aren't concerned about security, you could have it hard-coded into the code. Also, you only need to use the login() method for those servers that require it. you are running your own SMITP server, you may have it set up to accept unauthenticated connections. Once you are connected and authenticated, you can now send emails out. The main method to do this is called sendmail(). As an example, the following code sends a ‘Hello World’ email to a couple of people. EI sy_smtp. sendmail (‘my_email@gmail.com’, [friendi@email.con’, “friend2¢email.com'], ‘This ‘email\r\nsays\r\nHello World’) The frst parameter isthe from’ email address. The second parameter isa list of ‘to’ email addresses. Ifyou have only single ‘to! address, you can putit asa single string rather than a list. The last parameter is a string containing the body of the email you are trying to send. One thing to be aware of is that you will only get an exception if the email can't be sent to any of the ‘to’ email addresses specified, As long as the message can be sent to at least one of the given addresses, it will return as completed. Once you have finished sending your emails, you can clean up with the code: H ny_sntp.quito This cleans everything up and shuts down all active connections. So now your project can reply to incoming emails, too Projects What you'll need... Raspbian rwuZaspbemypiorgtionnloads SDeard Supercharge your Pi Supercharge your Pi Your Raspberry Pi is plugged in. Raspbian is installed on the SD card and you are right in the middle of setting up a wireless print server 1 building a robot to collect your mail from your doormat. But are you truly getting the most from your little computer? Perhaps you haven't explored the full st of options in Raspbian, or yout running the entire OS from SD card, something that can reduce SD card lifespan. Various tools and techniques can be employed toimprove performance, from choosing the right hardware to overclocking the CPU. You might even maximise storage space on the Pis SD card or all but replace it with a secondary device. Use these tips and tricks to reconfigure your Pi setup and optimise software and hardware to ensure you get the best performance. Use better storage hardware Oe eter can have an impact on your Raspberry Pis performance, regardless of the operating system. Alow Capacity SD card with poor error comtection is going to be slower than a larger card with greater resilience, so you need to find the right balance for your project and shop wisely Choosing the best SD card 0 Various standards of SD card are available, with the more expensive designed for better enor confection. For the best performance con your Raspberry Pi, choose an SDHC card with a high rating, The same advice applies to MicroSD cards, which youcan use on your Raspberry Pi with an SD card adaptor or directly insert into a Raspberry Pi Bt. Make the most of your storage 0 Youll typically need 1.268 ‘of storage for your chosen Raspberry Pi distro, so any remaining storage on your SD card willbe used for updates and data you create or save. In Raspbian you can open a command line and run the configuration utility to gain more space (only if your SD card's greater than 268): W sias sesecccnety Expand the Raspbian partition A aetna eaten atid bef patty trou Dard whch ‘will increase the media’ lifespan (there is more space to write too, so the Supercharge your Pi Projects same sectors aren't being overwritten as often), With raspi-config running, use ‘the arrow keys to select expand_rootfsin the menu. Then wait briefly while the Partition is resized, Write data to RAM OS Rieter esinand ‘writing data to your SD card — something that will eventually result ina deterioration of reliability and performance in the card = you can configure Raspian to write to the system RAM, which wil speed things Up slightly and improve the SD card's, overall performance. This is achieved using fstab (file systerns table), a system configuration available in most Linux distros Enable fstab in Raspbian OG Mescehiiecestnas RAM disk in Windows In the command line, enter: sudo nano /ete/fstab ‘Add the following line to mount a virtual fle system tmpfs /var/log tmofs defaults, noatine,nosuid,mode= 0755,size=100m @ 0 Follow this by saving and exiting nano (Carl), then safely restarting the Pi: sudo shutdown =r now “Youll typically need 12GB of storage for your chosen Raspberry Pi distro” Speeding up your Raspberry Pi by migrating the root filesystem toanexternal USBdrive isa start, but what sort of device should you use for the best performance? With a USB thumb drive you can add flash storage Up to 1668 without running into any signficant problems (the larger the drive, the greater the current is required to read/write). Anything larger expensive an unnecessary. Fyoute planning touse an external HOD, no power isues as it willhaveits own power supply. As ever, our choice should suit your project. Having yourflesytemona USB sticks grent or chap well as performance boos Supercharge your Pi Upon restarting, the virtual flesystem will be mounted and /varflog on the RAM disk. Other directories that can be moved to RAM indude: J tnofs /tmp tnpfs defaults noatine,nosuid,size=1¢am 0 2 ‘imps /var/tmp tmpfs defaults,noatine,nosuid,size-30m 6 @ ‘tmpfs /Nar/log tnpfs defaults,noatine,nosuid,mode=0755,size=l00m @ @ ‘tmpfs /var/run tmpfs defaults noatine,nosuid,node=2755,size-2n © @ ‘tmpfs /var/spool/nqueue tmpfs defaults noatime,nosuid,node-2700,gid= 12,size=30m 0 0 ‘Add each to /etc/stab in nano, DQaityouteconcemed about the (Cp teate a copy of your P's SD lifespan of the SD card, why card, Shut down, remove the not reduce your Raspberry Pis reliance card and insert itinto your desktop onit? Instead of using the SD cardas. compute. In the command line, run: a sort of budget SSD, change its role and add a HDD or USB stick to run the operating system, leaving the SD The path /dev/sdb represents the card for bootstrapping Thiscan give SDcard. Copying takes 5-10 minutes a matked performance boost tothe When complete, remove the SD card SDeard and connect your USS device ) Using a blank Ext-formatted USB thumb drive (or external HDD) asthe destination drive, enter: /oackup.ing of=/dev/sde Leave the backup on your computer, justin case something goes wron an SD card and USB storage device sharing an identical disk image, it's time to consider what youre going to do next - crate a faster Raspberry Fi Supercharge your Pi Projects Split the Raspbian Partitions y ‘1 Ideally the boot pation should remain on the SD card wihile the root filesystem is run from the external HDD or USB thumb drive. Using your preferred partition ‘manager (Disk Utility isin most distros), unmount and delete the root filesystem from the SD card, ensuring you have retained the boot partition. After removing the SD card, connect your USB device and delete the boot partition, taking care to leave the root filesystem intact. Then resize the root | Shecformeriae filesystem on the USB device, making | wiley avalable and sure that 10MB remains. SSeseeer Identify the root fi ilesystem Make your Pi fast and reliable 1 ‘Youte going to have the SD ieee en a wd hen such nite Dc espe et, card and the extemal USB ‘ict and change root=/deuimmcblk0p2 to root=PARTUUID=10XXXX, storage connected, so you need totell__where the numerical string from the partition unique GUID should replace the the Piwhere the rootfilesystem is.On _XXXXXX. When youtre done, save and exit. You can then start your Raspberry Pi the desktop Linux computer with your Congratulations, your Raspberry Pi is now faster and more reliable to use. SD card inserted, run IE sudo nano /boot/endline.txt Boost performance with overclocking Find root=/devimmcb Op? (or similar) ~ and change httoreedrocited 1] Need more fom your P? Its possible to overclock the computer though sda2 which is your external USB you should be aware of the risks inherent with this activity. You should also storage. Save and exit, ‘ensure that your Raspberry P's processor's suitably cooled ~ heatsinks for the CPU, Ethernet controller and power regulator can be purchased online Add other UsB devices Overclock your Pi 1 ‘You can now restart your Prwah the sterage devices 1 ‘Overclocking i avalabe through rasp-config Launch fiom te command attached, but as soon as you connect line and arrow cown to the overclock option. Four further options are further USB media you'll suffer available: Modest, Medium, High and Turbo. With your ideal clock speed selected, problems. Avoid by installing adisk: ‘exit raspi-config and restart your Raspberry Pi to apply: sudo apt-get update IE sudo shutdown =r now sudo apt-get install gdisk _Nowyou will ned to perfor tests to see how stable itis overclocked. Raspberry Then run adisk Pi founder, Eben Upton, suggests running Quake 3as a good stress test. Should IE sudo gdisk /dev/sdb ‘the Pi fail to boot, hold Shift to boot without overclocking, run raspi-config and Enter? to display the options and select a more modest overclock. select Recovery and Transformation options (experts onb)), followed by Run Raspbian without the GUI Load MBRand Build Fresh GPT. Tap ? nelast time and select ‘Write Table to 17 eae ese togethers son yest Disk’ and exit. Remove and replace the yourself running a lot of commands in bash, the best thing to do is disable USB device and run gdisk again. This launching info X. In raspi-config, choose boot_behaviour and select the fist time enter and then 1 to display the (default) option to ensure your Pt boots to the command line. Should you need Partition Unique GUID. the GUI enter startin Terminal Projects What you'll need... NagiosPi pllmagehub com/projecinagiosp! Win32Diskimager biti /LBsavG Disk Util Binieos Intemet connection 4GB (orlarger) SD card Monitor your local network with NagiosPi a a 5 a a Lo a Lo} rr Monitor your local network with NagiosPi e the F vitcn \s your PC offline? Has your Linux box stopped serving Minecraft or Counter-Strike? If youre out of the house, or even the country, there is no real way of knowing without trying to log in - something you probably won't be able to do without being on the premises (unless you're using remote desktop software) Afar better way would be to simply receive notifications when your network devices are knacked offline, and this is why we turn +10 NagiosPi, a Raspberry Fi-built version of the popular open source network monitoring tool. NagiosPis available as a full image ready to be written to SD card, with the real configuration taking place once it’s up and running. Let's get started. Monitor your local network with NagiosPi Download NagiosPi 0 Windows users should wirite the extracted contents of the Nagios?i_v20zip file toa formatted SD card using Win32 Disk imager. Linux desktop Users can use Disk Utility or the command line (bitly/1236sp8) With the image written to SD, safely eject the card and insert it into your Pibefore booting Log in to NagiosPi 0 ‘As with most Pi projects, youll probably want to operate via SSH, so check your router list of connected devices to find the IP address and connect. You can also use a keyboard and monitor connected to your Raspberry Pi. The default usemame and password for NagiosPiis as follows: piraspbemy. Expand the filesystem 0 Before proceeding, run sudo rasp-contig. Youtl need to select the firstoption, Expand Filesystem, and wait a moment as the filesystem is expanded to the full ize of the SD card. (Once done, select Change User Password to add some security t0 your Nagios? then select Finish and reboot. Open in your browser 0 With the Pi rebooted, you'll be able to open the NagiosPi web console in your browser. Visit http/fyourlPaddress. here] to see the available options. Here you'll spota menu of links in the top-left comer of the page, each accompanied with the Username and password to signin, Start with RaspControl Nagios? Welcome to NaghosP v1.0 Additional Resources: Projects Monitor your NagiosPi box O5 Bie hescontel section youtl get a flavour ofjust ‘what Nagios can do. On the home screen youll see general hardware information such as connectivity and system status, and as you fic through Details, Services and Disks youll see ‘hat level of monitoring is possible. View host status 06 Sezer tesiosandick Hosts. Here you will see the current status for the configured hosts, which isa combination of items detected on your local network ‘and preset entities, Look for Current Network Status in the upper-left area of the console, just below this you wil find alternate views. Adda host to monitor 0 (Open NConf to add the server you wish to monitor, using the Hosts - Add’ button to input the device hostname, IP address and ales. (lick Submit when done, then switch to Services — Add; where you can assign a name and check command (euch as check_ping) to monitor. Create configuration file 0 Each check must be set up individually Some require the installation of NAPE (Nagios Remote Plugin Executor) on remote devices to interrogate and present full system details, but this isnt necessary for basic things lke ping, ‘When you'te done, click Submit, then Generate Nagios Config. Following ths, select Deploy. Monitor your server 09 Inthe Nagios? window, select Services fora view of currently monitored servers and devices. Foreach listed device, there will be ‘additional information that you drill downinto by clicking Actions, Weve ‘only shown youthe basics of NagiosPi = investigation will demonstrate just how powerful it really is! Projects What you'll need... Android device UsBeable Tether to an Android device Tether to an Android device Need the internet on your Pi? Try out for online ac The portability of the Raspberry Piis one of its most lauded features. Mini screens, mini wireless keyboard and mouse comibos, portable batteries and more can get you out and about, but the intemet is a stumbling block that you cant easily fx with an accessory. What you do also usually have with you is an interet-connected magic pocket box called a smartphone that, with a bit of know-how, you can connect the Pi to and steal some internet from. Over the next Iwo pages we will impart this know-how to get you using your Raspberry Pion the Internet when youte on the go. The easy way OR eeeeen: WiFi hotspot feature, which your Pi can easly attach to. Fist of all, tum the hotspot on and then boot into the Pi. Connect a wireless dongle and open up the wpa_qui in Preferences>Wi-Fi Configuration Scan for device aks wep ipte Q2 Servincowsrsven” Setup tether select Scan again from inside there. i _ HSoupcipyordeiee (2/3 Pscomecrhoneto connects you would to any WEF yourRaspberry Piva USB networkand the Pwillememberit cable depending on the amount of forwhenikneeds tine. ower your Pi has, it might have trouble charging your phone butt will stil letyou tether in the tethering menu you cannovw activate USB tethering Tether to an Android device Projects “What you do also usually have with you is an internet- connected magic pocket box called a smartphone that you can connect the Pi” Check connection Quick connect Your Android device will create an interface known as eth on the You can connect from the 04 roctar cuencettomiesactsstappeing estaitwd — OD torindicteromoaes letyout pa terminal and typing the folowing: the internet. You should be able to Is itcontig this by typing the following into ie terminat “Tasteonneetion Ts sudo chetient usbe This will automatically rab any avalable IP address that your phone ilgvetoit 06 Peseta orice arhicenns and ping www.google.com which you cand, oryou can click onthe browser and see ft loads the page Save the settings O7 tasty tienen, remember to automatically connect tothe phone's tether However, we can add an entry toils config so that it vwilltry and do this in the future. From 12 terminal use: Fs sue nano /etc/netwerk? interfaces Tether on the go After a save and reboot, your 09 Fercudron automaticaly connect to your phone, whether ifs via WiFi hotspot or a physica connection. It may draw a litle more Interface settings ours might look different 1d wireless settings or Here youl ind all the current network settings — O8 tome depending on ifyau have added any fi charge than ual whie tethering, ppassthroughs. Using the same syntax as the ethOline, ad: sobe sute to keep an eye on your IL face usbo inet dhep battery level : n Projects What you'll need... Shere 3-Amp UBEC buyin 3-Amp terminal strip 6x AA rechargeable Batteries "°° Add a battery pack to your Raspberry Pi ee Add a battery pack to your Raspberry Pi leave yo tind — incorporate ising Your Raspberry P's mobility is usually restricted by the length of the power lead. Rather than limiting it to your desk or ving room, however, you can use it for mobile projects as diverse as launching itinto near-Earth orbit or monitoring and automating your garden. Of course, to do this you will need batteries, but adding battery power to your Raspberry Pls simpler than you might have imagined. All that is required are six rechargeable AA batteries (or single-charge alkaline), a battery box with space for the batteries and a UBEC. The latter is a Universal Battery Elimination Circuit, a voltage regulator that will regulate the power supply and prevent damage to the Raspberry Pi, and can be bought for under £10. Add a battery pack to your Raspberry Pi Make your order 0 Ifyoute buying your components online, you should be able to get them all within five days. However, you're ordering offline Gpecifcally the UBEC), you should avoid traditional electronics stores and instead visita model enthusiast store, as these circuits are regularly used in RC devices. Check your UBEC 0 Two types of UBEC are available to choose from. f you used the store that we suggest in the resources box to the left, yout receive one with a micro USB power connector for easy connection to your Raspberry Pi However if you bought one from eBay then theresa strong chance that you will receive one with a 3+pin connector. I 4 Move connector pins 03" order to use the UBEC with a 3-pin connector, youl need toalter the position of the pins so that they occupy the two outer slots. Just use a small jeweller’ screwdriver tolever up the small plastic catch and remove the red wire from the central slot, before siding into the unoccupied outer slot. Connect to battery box 04" five batteries in the battery box, connect itto the UBEC (fechto~red, blackto-black) by twisting the wires, soldering or ‘employing a 3-amp terminal strip, cut down totwo pais. can be cutto size Using @ modelling knife. Add a battery to boot 0 ‘With your Pi ready to use and your Wi-Fi donale plugged in, connect the UBEC to the micro USB port and insert the sixth battery into the battery box. The Pis power and status lights should indicate that the computers booting up, which gives ‘you a fully portable computer. Connect the 3-pin UBEC 0 lfyou purchased the UBEC wath the now-modified 3-pin connector, youll need to connect this to the Raspberry Pi's GPIO header. Connect the positive +5V (red) connector to Pin 2 and the negative OV connector toPin 6. Projects “You can use your device for mobile projects as diverse as launching it into near-Earth orbit” Measure uptime OT usruseearead sup your Pi for SSH use, soconnect to the device via Putty after giving it time to boot fully (at least 60 seconds. In the terminal, enter: suo a bs-s0m if-Users/ Tachelcrabb/Desktop/archinux/ archlinux-hf-2013-02-11.img. of/deviisk This command will display the system. Uptime and also keep the WiFi connection active Judge your uptime results 0 Uptime results depend upon the type of battery you use and the Raspberry Pi model Single- charge batteries wil last litte bit longer, but thisisa more expensive option. Meanwhile, newer models have greater power requirements but run fo ess time. For more power add more batteries! Power extreme! QO Msatexth parallel should result in almost double the uptime (et least 16 hours ‘ona 256MB Raspberry Pi Model A), but instead of alkaline or rechargeable batteries you might consider a modem lithium-based AA cell which villlast considerably longer than alkaline batteries. Projects What you'll need... ive paint enone Maleto female jumper wires fememenlia Draw circuits with paint Draw circuits with paint Assembling circuits has never been so easy with the joys of conductive paint, g you to bring together art é lectronic hole new way Playing with electronics and physical computing is a very rewarding task. For a beginner though, the mess of wires and components can become very confusing quite quickly and things like soldering can bea safety concen when children are involved. Bare Conductive has taken the joy of electronics and made it far safer, easier and more versatile with their conductive paint. You can literally draw wires on paper with a paintbrush, use it for cold-soldering or a conductive adhesive and much, much more. There are not a great deal of boundaries to what you can do. Pair this paint with a microcontroller board and you could be creating interactive art, clothing and projects in no time. Get your tools 01": anita pains arent the fst tems that come to mind when you think about electronics, so you may be ‘wondering where to get them ftom Bare Conductive stock the paint and a selection of components in their shop (bareconductive.com/shop) but you will need to go somewhere else for art supplies. We would recommend trying 2 high street craft shop such as Hobbycraft (hobbycraft.co.uk) ora local independent. BARE | ELECTRIC PAINT Pick your platform 0 The great thing about Bare Conductive paint s that, when dry, it works just ike normal wiring! That means you can use it with any of your favourite microcontrollers like the Bare Conductive Touch Board, a Raspberry Pi or Adafruit's wearable FLORA platform. Or you can just use some small pin batteries and flashing LEDs fora standalone system, Start to paint 0 You can paint Bare Conductive paint onto pretty much any surface - paper, fabric, walls, clothing, wood, plastic and much more. For really accurate shapes and results, the best idea isto create or purchase a stencil (paper stencils are easiest to make at hore but use vinyl for the best edge finish Draw circuits with paint Connect it up 0 There are plenty of ways to connect to the conductive paint from battery packs for example) no matter what surface it's on, because once itis dry it acts just Ike anuninsulated wire. Therefore you can use wires glued on with the paint, paper dips, bulldog clips, aligator clips cr even sevwrvin conductive snaps for ‘wearable projects Make repairs 05 The conductive paint is thick and when it's dry it becomes quite strong. These means ‘you can use it to cold solder things together and repair any breakages. Inother words, you could glue components into a circuit board or lue wires together and they would still function electrically. and components can become very confusing” Clean up 0 Alot of you are probably ‘thinking that something as ‘cool as conductive paint is going to be nasty stuf. Actually Bare Conductive paints non-toxic, waterbased and water-soluble, and can therefore be deaned easily with soap and water. Make it waterproof 0 This paint only comes in black and is not waterproof However, the great thing is that you ‘can use it underneath or alongside ‘any regular paints, varnishes and ‘waterproofing sprays in order to act as insulation - or just to add some colour intoyyour designs. ni LI Touch and sound 0 Bare Conductive paint can also be used as a ‘capacitive surface, meaning you ‘can use itfor touch, gesture or proximity controls when its paited ith 2 suitable control board. Bare Conductive make their own called the Touch Board which has everything you need to start experimenting vith touch and sound. can even actasa MDI controler, an interface or an instrument. Send an SMS from your Raspberry Pi Send an SMS from your Raspberry Pi Raspberry Pi bile pt ‘Twilio account Text messaging, or SMS (Short Message Service), has become a staple of everyday communication. What began life as a 40 pence message service is now offered by most tariff providers as an unlimited service used worldwide. Twilio, a coud communications company, enables you to send SMS messages for free from your Raspberry Pi to a mobile phone using just six ines of code. Cre aa oe 4 ee ad Number - Hey! Did you know you esr ung ae Send an SMS from your Raspberry Pi Projects Set up your Twilio account _ Install the software the message that will be sent: BE message = raw_input(“Please OT esaserstisnoet Og renrectupyerrtasbery ser your nessanw 's to reqister for aTwilio Piand connectitto the account and Twilio number. This is intemet Before you install the Twiio Add your numbers free and will enable youto sendan software, itis worth updating and = : SMStoaregsmredvetiedphone, —upgadingyourPintheLX Femina ()7 Tosend the message you Once signed up, you will receive type sudo apt-get update, then sudo need to add the code line a verification code via SMS to the apt-get upgrade. Once complete, below and your two phone numbers. registered phone. When prompted, type sudo easy_install twilioor The fist number is your mobile enter this onto the Two ste to sudo pip install twiliota install phone number whichis registered authenticate your accountand phone. the software. (fyouneed to install pip, and validated with Twilio Step 2, The Gototwilio.com/try-twilio and create type sudo apt-get install python second number isyour Twilio account your account now. ip python-dey, press Enter, then number, which can be retrieved from type sudo pip install -U pip) your dashooard page under ‘Call Register numbers the Sandbox number’. Change the ‘Sandbox number to your country location and remember to add the international country code. Twilio authentication 0 Your Twilio account is just a tial account unless you OSwyesmecse 2 pay the upgrade fee, which means the SMS program that will message = you can only send and receive send the text message to yourmobile Cient-nessages, communications from a validated phone. Open your Python editor ee phone number. Enter the phone and import the Twilo REST libraries Fone RTS umber of the contact who you want (line one, below), Next, add your body=message) toverify ensuring that youselect the AccountSid and Auth Token, replacing conect country code Twiiowiltext — theXwthyours,asyouwilngon Sed themessage youa verification code and you will ——_yourdashboard eed oenteritintothewebsteform J from twilio.rest inport 032 el accountsid = “X0Q00000000K pee een ee he inecond ave The dashboard HX” ee . Biter your program. Ensure your Raspberry Cree cclomedenl Sours Pils connected to the internet and 03 ee a, that your mobile ison, then run your loggedinon Twia,vst the J|_auth token program, You have just texted from dashboard page, hich will displey ———_“SEXKXKXAXINKKKOOONNXK” our Raspbenty Bt your AccountSid and your Auth Token # Enter t if ‘These are both required to usethe Yours ae tn eae heli Twito REST Keep these secureand | client = eee MMrimessaas f6:beine Private, but be sure to make anote of TwilioRestClient(eccount_sid, them 2s youwillneed them foryour —auth_token) Python program later. print “Check your phone!” Other API and codes Create your message 0 You can also create other 0 ‘You will probably want to ‘communication programs, be able to change your such as making phone cal, recording textmessages rather than send the a cal, and retrieving data including same one, Create a new variable in caller Ds and call duration. The APL your program called message. This here also complements a wide range ‘wil prompt you toenter the phrase of programming languages, including that youwant to send to themobile Ruby, PHP, Java and Node js (twilio. phone. When the program runs,thisis com/api) toname a few. Projects Make a Pi 2 HTPC ween Makea HDMI cable i Pi 2 HTPC Case Dedicated power supply Fir Optional USB storage t erful We know people who just have a Raspberry Pi for XBMC, now called Kodi I's a great idea and a great use for the Pi — it works just well enough that you can easily play media locally or over the network. The biggest issue came with GUI response on the original Model Bs, and a lack of USB ports for connecting up everything that you want. While optimisation over the last few years has helped, the leap to Raspberry Pi 2 has basically solved all of these problems by giving you much more powerful hardware to play with. So if you're looking to upgrade or finally take the plunge, this handy guide wil help you 2 the perfect Raspberry Pi 2 HTPC crea In the past, Pi HTPCs were justa choice between Rasp8MC and OpenELEC. However, RaspBMC is ona bit ofa hiatus and OpenELEC is your best bet getting the mast up-to-date software. There'snota massive difference between the two, as they both run XBMC. Head over to openelec. tvand look for the Download section. There's a specific Raspberry Pi section ‘which is spit up into original (ARMv6) Pi and the newer Raspberry Pi2 (ARMV7). Grab the image file from this page forthe Pi 2. (Open up the terminal and use faisk-I to determine where your SD card is located on your system. Something like /dev/sdb or / devrmmcblk0 wil be ideal. Navigate to the image using ed and installit with dd using: $ dd bs=IM if-OpenELEC-RPi2. arn-5.0.5.img_ of=/dew/ anmcblk® Plug in your Raspberry Pi either t0 your TV or to another screen just to begin with, and turnit on. Open£LEC will resize the SD card partitions andi write a few extra programs before finally booting into Kod ward terface ~ Go through the basic wi to get through the i ou are connecting via wireless you will need to go to Open LECin the System menu and activate the wireless receiver before select: and then entering your password. You can attach a portable rive or USB stick to the ‘butitisreally to steam ver the network. Goto File manager Under System and Add source. Go to Bronse and choose your network tocol to browse the network or alternatively, add it manually Make a Pi 2 HTPC Placement of your Raspbe y Plis important. As it’s going to be out all the time, we highly recommend getting a case for it~ the Pibow cases from Pimoroni are quite well suited for this type of use as they are sturdy and can be attached to the rear of some TVs Kodi can be controlled with a number of different things including USB game controller and compatible IR sensors, We'v used FLIRC in the past, but ifyou have your Fi behind the TV, youll need asensoron a wire that can streich to a useful position (OpenLEC has the excel JF abiity 10 update itself without needing you to reinstall it every few months, meaning youwon'tneed todo much maintenance on it at all. Now you can sit backand enjoy your media much easier than before Projects What you'll need... Latest Raspbian image USB printer USB wireless card Below Setng your Raspberry ito pint wirelessly isa grat way to getridof annoying cables at your workstation Print wirelessly with your Pi Print wirelessly with your Pi Wireless printing has made it possible to print to devices stored in cupboards, sheds and remote rooms. You don't have to own a shiny new printer for this to work; old printers without native wireless support don't have to end up in the bin, thanks to the Raspberry Pi The setup is simple. With your Pi set up with a wireless USB dongle, you connect your printer to a spare USB port on the computer. With Samia and CUPS (Common Unix Printing System) installed on the Raspberry Pi, all that is left to do is connect to the wireless printer from your desktop computer, install the appropriate driver and start printing CUPS gives the Raspberry Fi a browser-based admin screen that can be viewed from any device on your network, enabling complete control over your wireless network printer. Check your printer works 0 documentation (online ifyou cant find = a iss subscriptions Detect your printer QD Mrerteeente Uupas usual andthe printer connected toa spare USB port enter B isusb This wll confirm that the printer has been detected by your Raspberry i. In most cases you should see the ‘manufacturer and model displayed. Set up print admin O04 sek eecare tool. Boot into the GUI (starbo and launch the browser, entering 12200131. Switch to Administration, before ensuring that the ‘Share printers and Allow remote administration boxes ae selected. Select Add Printer and proceed to enter your Raspbian Username and password. ‘printers and find ‘quest ok which you Bi auest ok = yes Print wirelessly with your Pi Before starting, check that the printer youre planning to use for the project sill works and has enough ink. The easiest way to do this s to check the the manual) and run atest print Install Samba and CUPS 0 Install Samba on your Fito enable file and print sharing across the entire network: II sudo apt-get install samba Next install CUPS: EE sudo apt-get install cups With a print server created, begin configuration by adding defauit user ‘pi'to the printer admin group: I suo uscrmod -a -6 Ipadnin pi Add your printer 05 A\list of printers will be displayed, so select yours to proceed to the next screen where youcan confirm the details, add ‘2 name and check the Share This Printer box. Click Continue to load the list of printer drivers and select the appropriate one from the list. . Configure Samba for network printing * 0 Using a Windows computer for printing? Samba wil need some ‘configuration. Open /etc/samba/smb conf" n nang, search (Cirl4W) for should change as follows: Next, search for ‘Iprit$]" Then change the path as follows D poth = suscshare/cups rivers Projects Join a Windows workgroup O7 meses search for “workgroup" in the configuration file and then add your workgroup: BE workgroup = your. workgroup_nane BE wins support = yes Make sure you uncomment the second setting so that the print server can be seen from Windows Next, save your changes and then restart Samba: BE sudo /etc/init.d/sanba restart Accessing your printer 0 Meanwhile, i’ alot easiert0 access your wireless printer from a Linux, Mac 0X ar other Uni ikesysterr thanks to CUPS. Allyou need to do's adda network printer in the usual way and the device willbe displayed Add AirPrint compatibility OO" 22zesteorere ‘wirelessly from your Apple iPad using Apple's AitPrnt system. To do this, you need to add the Avahi Discover software: IE sudo apt-get install avahi- discover Your witeless printer will now be discoverable ftom your Pad or iPhone and will be ready to print. Projects Control lights with your Pi What you'll need... ween Control lights board with RC sockets biuyriMapeOU = with your Pi 1 1 J longer; use < ‘The folks at Energenie have created some genius plug sockets that can be tured on and off via your Raspberry Pi. You can buy err a starter kit which includes the RF transmitter add-on board and ‘two sockets to get you started. The add-on board connects directly to the GPIO pins and is controlled with a Python library. Once everything is installed and set up, your Raspberry Pi can be used with the Pi-mote to control up to four Energenie sockets using a simple program. This tutorial covers how to set up the software, the sockets and how to adapt the program so that it can run on your mobile device. pte RT Remote control Take conrotofyourhome crwironmentusng your f Srartohone's browser Light source ‘aight source with ‘pl socket can ‘contoledtemotely Set up. O7 Racca bootup vo Raspberry Pi and load the LX Terminal then update your software by typing: I sudo apt-get update IB sudo apt-get upgrade Depending on which version of the OS youte using, you may need to install the Python GPIO libraries. (Raspbian Jessie comes with this library pre-installed, so you can skip this step) Type the following into the command line: I sudo apt-get install python- rpi-gpio On completion, reboot your Pi. This wil install the Python GPIO libraries, ‘meaning you can access and control the pins with Python code. Control lights with your Pi Projects [Above The P-Mote IR control board hugely versa and only costs £599, “Your Pi can control up to four Energenie sockets using this simple program” Install the Energenie library 2 Sec ents ates erate ateoa and Raspberry Pito interact with Python In the LX Terminal, depending on which version of Python you are using, type either. I sudo apt-get install python3-pip Bl sudo pip-2.2 install energenie for Python 3, or I sudo apt-get install python-pip I sudo pip install. energenie for an older version. Inthe future, nergenie will update its software and you may need to run a check for updates to ensure that you have the most recent vversion. To update the software, type the code: II sudo pip install. energenie -update rs Projects Download the set “up code 0 "Before the RaspbemyPican interact with the socket and switch it on/off itrequires programming to lear a control code thatis sent fiom the transmitter. Each socket hasits own unique code so that you can control up to four individually. nergenie provides the set-up program which can be found inside your tutorial resources (available at bit ly/21ZRW4G) A quick test 0 Beare yOu oe getto the taskof creating your Python code tocontrol your socket, itis always advisable to test that the sockets working correctly. Ensuring that the power is turned on at the wall plug and that the lamp is switched on, you can turn the lamp off by pressing the green button on the front of the Energenie socket. The lamp should tum back on again when the button is next pressed Control lights with your Pi Fitting the Pit -mote 0 Before iting the Phmote transmitter shut down your Raspberry Pi with sudo poweroff. Next, Unplug the power supply and fit the modiule onto your Raspberry Pi. The ‘U part ofthe board fits opposite the HDMI port Power up the Pi and plug in one of your Energenie sockets in the same room or area that your Piisin. The device's range isfairly good, but fumiture, walls and other objects may sometimes block the transmission signal. You can test that the socket is working by plugging in something lke a desk lamp and then pressing the green button thatis located on the socket. This will tigger the socket on and off, turning the lamp on and offin turn Set up your socket 05 wens downloaded the setup program, unit This should place the socket into ‘learning mode’, which will be indicated by the LED on the front ofthe socket housing slowly flashing. I itis not doing this, press and hold the green button for atleast five seconds and release it when the LED starts to flash at one-second intervals. Run the program and it will senda signal out. Follow the on-screen prompts, pressing the return key when required When the code is accepted, success will be indicated with a brief flashing of the LED on the housing, Ifyou have more than one socket to set up, simply Use the same program and method to do so for as many times as required Code totum the socket on 0 "The Python Energenie brary makes ft inredibly easy to createa code to tutn the socket on, which willthen tum your lap on. Before you know i, you will be using your Raspberry Pi to tum the kettle or the TV on or off ‘Open your Python editor and start a new program. Next, import the Raspberry Pi GPIO lary (ine 1, below), then import the Energenie lorry (lines 2and 3) Finaly, add in the code to switch the socket on line 4). Save and then run your program. The socket will tum on, you may hear a cick and then your lamp will come on. Inport Rei.cPI0 as ero I inport energenie from energenie import switch_on I evergenie.switch-on(t) Control lights with your Pi Projects Switching the socket on and off Web-based applications O8 Stcyeutnense els thesocte tom off it will stay on, which means. Itis possible to augment this the vl tay on forever oruntl the bub biwatTotumthe soc” — OD hacksorhar you can turn offafter five seconds, impor the time function atthe start of your program (line the lamp on and off from a mobile 2, below), add the command to tum off the socket ine 5).Then add a pause with device such as your phone, laptop or the sleep command (line 7) and finally tum off the lamp (line &). Now save andrun tablet. This makes the whole project the program. more impressive, sick and fun. The first step isto set up your Raspberry I import RPi.GPIO as GPIO Pi.as a web server which will host H import time and display a web page with the I inport energenie ON/OFF option. These buttons are II from energenie import switch_on interactive and control the socket. I from energenie import switch_off Open the LX Terminal and install pip and Flask: I energenie. switchon(1) El tine.sleep() I sudo apt-get install pip I energenie.switchof f(1) I sudo pip install flask CSS and HTML Toma bewel pace Using a mobile device such as your 10 precnatyounceso phone, laptop or tablet makes the whole set up an HTML and a CSS file é © ‘i ie HIvLsandstorHyperetMaiup —_[OFOJ@Ct More impressive, slick and fun Language ands wed to ceate we . : pages. Your browser reads HTML files and converts them into web pages, The HTML files emabing magesandobjectstobe == on a ‘embedded into the pages. Cascading 1 Open the Mobile_Lights folder and create a new folder called ‘templates. ‘Style Sheets, or CSS, is the code which This folder is where the HTML file is saved that contains the structure for describes how the web page will ook; the website layout. The code names the web page tab and, most importantly, the presentation of the HTML content. adds the links for the on and off option. It-contains instructions on how the Open a text editor from your Start menu, or use nano and create a new file. elements will be rendered. Here, it Add the HTML below to the file and then save the file into the template folder, controls how the on and off options naming it indexHTML. Remember, this is an HTML file and must end with the file will be presented, extension html Create a new folder = 1] i etealetito yourRaspberry Pi typesudo — reboot. Create a new folder called 0N«/a>
You can create the folderin the LX Terminal by typing mkdir Mobile_ Lights or right-dicking inthe window
and selecting New Folder. Projects Add some style 13 Sent 2 button syle effect tothe wr page Move backio the Mobile_Lights folderand create new folder named ‘satiThisis where the CSS fle saved Cate another new texte and addlthe code below which sets out the Style forthe web page You can austomise the colours ofthe buttons fom ine 20 ‘onwards Save the fle as‘stylecss in the static folder. body { position: absolut margin: @; top: 0; right: @; bottam: @; left: @ font-family: Arial, sans-serif; font-size: 15 px text-align: center; } div { display: block; width: 100% eight: Som 3 div a{ width: oer height: 100%; display: block; } divion { background: black; y divon a { color: white; y divoff a { color: black } ailink, visited { text-decoration: none; y Control lights with your Pi Putting it all together LA te teleerctteseip a veteryiiarenyrstacconbies the indexhhtm! and stylecss fles with the Energenie socket control code similar to the one used in Step 7 Open IDLE and starta new window, add the following code and save into ‘your Mobile_Lights folder, naming it ‘mobile_Ightspy’ Line 4 uses the route) decorator to tell Flask the HTML template to use to create the web page. Lines 7 and 11 uses approute(/on/’) and app,oute(/ot/) to tel Flask the function to ‘tigger when the URL is clicked. inline 15 the run() function is used to run the local server with our application. The f 1__! makes sure the web server only runs ifthe seriptis executed directly from the Python interpreter and ‘not used as an imported module, IE from flask import Flask, rendertenplate IE from energenie inport switch.on, switch off Bap = Flask(_name_ B exp .routec/’) def indexO): return render_tenplate(‘index HIM) BH exp.routetyorv") HE der ond: HE switchono return render_template(‘index.HIM.') B exp .routec/oft/’) ef off) switch off return render tenplate(‘index.™!) Bf rome = Lain app.rinGebugeirve, host='00.00") that bheaen fetion in Find your IP address 15 eryouseartte ne sever running, you will need to check Control lights with your Pi Projects Start the web server 16 You have arrived at the point where you are ready to start the web server. ‘Move to the Mobile_Lights folder by typing cd Mobile_Lights. Now run the following: the Python mobil_lights py program by typing sudo python mabile_lights py This starts up the web server, which is then ready to respond to the buttons that +*Youhave folder set up called are pressed on the web page. Mobile_Lights +Inthe Mobile_Lights folderis a i InteNebie-tgsieders2 Turn your lights on and off ; % oma tne Nokee sts 3 1 Grab your mobile device, smartphone or tablet and load the web browser. ee we ton bier nero In the adress bar enter the IP address that you noted down in Step 15. ae une At the end ofthe address, add “5000'—for example, 192.1681.122:5000. The 5000 SOM Ae aed anothes Fda famed isthe port number thats opened to enable the communication between your Static which contains the fle stylecss_ device and the Raspberry Pi. You willbe presented with ON and OFF options, and you can now control the socket and whatever you have plugged in - kettle, radio, eveything checks our then In TV--all from your mobile device by simply pressing ON or OFF the LX Terminal you can type sudo - Bysimply pressing) hostname -L This will displey the IP address of your Raspbery Pi for example 192158XX Makeanoeof — "YOu yyill be presented with ON and OFF it because this isthe address you wil enterintathewebbromeronyou — OPtIONS to control the socket” mobile device. 8 Wastabantat 8 am seme | cng 7 > BD ctu 8 © foniconty > Bows vise | > euca » 0 meas > Dre ryooncares | > Bone » Cabuie » BBoesop ms Te (> ere cevpene neorce Deas s » DBieraletes ocr’ came [Above Yu need to get the folder namescomacts that fies are saved propery Projects © Build your first web server What you'll need... ~~ Build your first Web browser eet web server pe cea eee turn your Raspbe v-powered web dv eb host tiny We're teaching you how to code in many different ways on the Raspberry Piin this book, so it only seems fitting that we look at web development too, There's a new way to use the web on the Raspberry Pias well internet giant Google has recently released Coder specifically for the tiny computer. Its a Raspbian-based image that turns your Pi into a web server and web development kit. Accessible easily over a local network and with support for jQuery out of the box, it’s an easy and great way to further your web development skils Plug in your Pi Serr QD fxseretatyout ony need to connect a network cable into the Pi Pop in your newly ‘written SD card, plug in the power and wait a few moments. you've got a display plugged in anyway, youl noticea Raspbian startup sequence leacing to the command line login screen. Peete] Get Google Coder Ole eee ‘website and download the compressed version ofthe image. Unpack it wherever you wish, and Connect to Coder instal it using da, ike any other aa Raspberry Pi image: 3 ar tebee erat seve alti :coderlocal Is dd if-fpath tol/raspi.ing ‘You may have to manually accept the licence. it wll ask you to set up your of-/dev/[path to SD card] bs=iM password, and then youl be in and ready to code. Build your first web server Projects Language of the web Full code listin Now t's time tocreate D4 seri onn app es website HTML lick on the +’ box next to the. ‘e 1 fn examples, give your appa name , Welcome to the internet... and then click Create. Youll be Some simple HTML | taken to the HTML section of the int us to some

Linux User & Developer

lines to: irpatant wel []

The Linux Foundation

ees ie

9)€ background-color: vartuin lings x ranean \Wemate the 5 ele nln I . lor: #fftttt: minutes readable else { color: B byaddngad# =] ig ‘Click on a playlist below: KissFM i} BBCRadio2 BBCRadiot BBCRadiog Capitaixtra BBCEMusic Solder the headers Install Music Player els : ae fone ae ss ough aweb-browser. The following Daemon (MPD) will install pyPlaylist on Raspbian: 0 The pHAT DAC comes with a 40-pin header, which you will Now goon to instal the MPD sudo pip install flask need to solder. We consider a flux 03 Bue ip pen, workelamp and thin gauge 60/40 solder essential fr this. An optional RCA jack can also be bought to give a phono-lead output for older stereos. Install drivers 0: The DAC relies on I2C, so we shave to load some additional kemel modules. if you are running Raspbian then you can type in the following fora one-script installation over secure HTTP. H curt -ss hetps://get.pinoroni. ‘com/phatdac | bash While HTTPS provides secure download, curious types may want to review the script before running it. package and enable itto start ‘on boot. MPD will be the backbone of the project, providing playback of MP3s and internet radio stations. The MPC (dient) software is also installed for debugging and setting up your initial playists. H sudo apteget instal! mpd ape [oxic srsteecet enable apd Clone and install pyPlaylist web-server 4 dePeisareponsve (mobile-teady) web-server written with Python & Flask web framework. Once configured it will python-mpd2 Ba - git clone https://github.con/ alexellis/pyPlaylist Bcd pyrlaylist ./raspbian_install.sh “An optional RCA jack can also be bought to give a phono-lead output for older stereos” Build a networked Hi-Fi with a Pi Zero We have put together a list of some popular radio stations inthe UK which can be run into MPD with the add_stationssh file You can exit this file or find your ow from this site: httpy/radiofeeds.co.uk cd ~/pyPlaylist /add_stations.sh Each of the radio station are added into their own playlists = the mpe ls command shows which of the playists are available as shown in the Ist below. Is mc 1s J BaceMusic | pecradiot | Bscradioz | BacRadiog | copitalxtra | kissrm If you decide that you want to remiove one of the stations then just type in the following: Hine rm pcetusic Build a networked Hi-Fi with a Pi Zero : Projects Start the web server © Oe /D pypuayist - x ea __| © |} 192.168.0.21:5000 vy @ 0 Now that we have some e stations we can run the web- server from the pyPRayist directory. Then ‘open up a web browser to start playing 2 radio station. The folowing command pyPlaylist radio/music player reveals your P address on Raspbian: Hs sraspbian_get_ip.sh => KISSFMUK 192.168.0.20 ‘Once you know the P address, connect tothe URL ina web-browser on port 000 ie H bttp://192.168.0.20:5000/ Adda custom music playlist BBCRadio2 08 Now put together a sub- cnectory with your music fles unde avibymedimusc/ andesite that mpdaucio has access ro read i stainiaaiian Then we update mpa's database, clear ‘out the current playist and addin all the BBCRadio4 ‘tracks from the new directory (ambient), finaly saving rasa new playlist. Capitaixtra ] mpc update wpciclear BBC6Music mpc 1s ambient | mpc add npe save anbient Finishing uy fecongsitererodos "Now that we have some stations, we can oer oeeareannres run the web-server from the pyPlaylist seuce i wor tispupose Tat directory. Then open up a web browser TBhleakctattecceheeiniags tO Start playing a radio station” tohttps/bit ly/290maiH. Go ahead and enjoy the tunes! a Projects What you'll need... Latest Raspbian Image wararaspemypiorgtounlbads Breadboard Connectors Jumper wire DSLR camera Compatibleshutter cable Set up the Raspberry Pi 0 For this tutorial we'e assuming ‘youre usinga recent build of Raspbian. With the Raspberry Piset up with a keyboard, mouse and monitor, ‘open the terminal and type: [sudo apt-get update Install the RPi.GPIO librai O22 ae make sure your development environments set up. Follow these steps to make sure youte all set. In the terminal type: [= atp-get install. python-dev sudo apt-get install. python- rpi.gpio Set up the Pi Cobbler 032 Used a cheap prototyping breadboard and an Adafruit Pi Cobbler togive useasy access to the Raspbery P's GPIO pins As you can see from the pictute, the Cobbler straddles the centre-point of the breadboard anda ribbon cable connects the two, Time-lapse camera trigger Time-lapse camera trigger Make sho camera with tac dv ice g time-lapse v a cin with our expel Youid be forgiven for thinking that creating mesmerising time-lapse ‘videos lke those of Vincent Laforet (www laforetvisuals.com) or John Eklund (www.theartoftimelapse.com) might be out of reach of the Average Joe. With the help of the Raspberry Piand a sprinkling of Python cade, though, that’s no longer the case In this guide we're going to trigger our DSLR camera to create pixel perfect time-lapse imagery. Full code listing import RPI.GPIO as GPIO import time print ‘\nNelcome to the Complete Manual Time-lapse Tool.” print “Just tell us how many shots you'd like to take and <1 the interval between them. \n” print “Try googling ‘time-lapse interval calc’ help deciding. \n” if you need «1 def mainQ): shots take?\n ->") interval = raw_input(‘tow frequently do you want to ”) aw_input(‘How many shots would you like to «1 if shots.isdigit() and interval. isdigit(): shots = int (shots) interval = int(interval) print “You'll be shooting for %d minutes.\n" % «! (shots * interval / 60) answer = raw_input(‘Are you ready to proceed?(yes/ +! no):") confirm = answer.lower() in ['yes’, ‘y'] if confil GPIO. setmode (GPIO. BOARD) tup(16, GPIO.0UT) print print ‘Starting a run of %d shots’ % (shots) Time-lapse camera trigger Manual focus ewon'tbeeonteliog theautofocus with our Python app, soset the focus tomanualand lect Yyourcamerasettingsin ‘vance ofthe shot 2.5mmto3.5mm \Weteusinga cheap Canon EOS DSLR, soto wgger the shutter wth the Raspberry Pall weneed!sa Simple 2mm to 35mm cable Pi Cobbler We'eusingthnePiCobblerasa breakout forthe Ps GIO pins, ‘making the bul process easier houghitsnotrequred) for i in range(®, shots): print print ‘Shot %d of %d’ % (taken, shots) taken +=1 PIO. output (16, GPIO.HIGH) time. sleep(2.5) GPIO.output(16, GPIO.LOW) time.sleep (interval) GPIO.cleanup() else: print “Let’s try again (or press Ctrl + C to <1 quit):\n” main() else: print “Oops - You can only enter numbers. Let’s try + again:\n” main) print print “Thanks for using the Complete Manual Time- <1 lapse Tool!\n’ ‘again = raw_input(‘Wiould you like to do another time- <1 lapse? (yes/no) :\n -> *) proceed = again. lower() in ['yes’, ‘y’] if proceed: main() else: print ‘\nSee you next time!\n" quit) if name = ‘main main() Projects Configure the breadboard O4 zeta 0% control the camera, we need to eateacircuitbetween a pin on the PIO Gn this case pin 230n the Cobbler ~ buti’sactually physical pin 16) and the pin that connects tothe head orto’ of the camera cable that activates the shutter when connected, The base of the connector cable isahvays ground, so make sure you ground the GND’ pin on the Cobbler and the middle pinon the audio jack With the dreut complete. we can focus on the code. The Time-lapse Photography Tool O5*a: small $5ine Python utility called The Linux User Time-fapse Photography Took which asks the user to input how many shots they/d like to take and the frequency they'd like them taken, It then takes that information and Uses itn a For loop to activate the shutter using GPIO pin 16. If youd tke ‘to use the project ‘n the fel’ wetd recommend using the Android app ConnectBot to SSH into your RasPi forinput and feedback. Don't forget tostart your script with sudo python ‘time_lapse_canera.py Creating a video 0 With your camera packed with images, we need to collect and output themas@ video file While it’s possible on the Pi copy them to an easily accessible folder on a separate Linux PC to make it much faster Wete going to use FFmpeg, With the ‘terminal apen in the folder where your images are stored, type ffmpeg -F imago2 ~i imagexB4d. jpg ~vcodec Libx264 -b 800k video.avi. This assumes you have libx264 installed on ‘your machine and the ‘image%o4d. {ipe’ assumes the fle format and the ‘number of digits it's dealing with (in this case‘picture0001 jpg) Wireshark wwinuinresharkor Picam module or USB webeam Get alerts with the Raspberry Pi baby monitor Get alerts with the Raspberry Pi baby monitor 1 Ra While youre settling down to enjoy a boxset, there's always that nagging feeling at the back of your mind ~ is the baby okay? We need to rely on baby monitors, specifically video monitors, in particular those that display footage on an app or by opening an P address in a mobile browser. Add in some motion detection and alert software, and you've got an incredibly useful tool - which, the Raspberry Pi can do for a fraction of the cost. Al you'll need is a Raspberry Pi (the newer the better), and a USB webcam or the PiCam (the NoIR infrared version is even more suited to nighttime use), and a device to view the streamed footage on. Get alerts with the Raspberry Pi baby monitor Survey the bedroom 0 Before you start installing and configuring your Pi head to the baby’s bedroom and take a look around. Where will you be placing the Raspberry Pi sit within reach cof a power source? Do you need to connect an Ethemet cable, ors the wireless signal strong enough? t's vital at this stage to spend the necessary time planning the Pi’ position in relation to power sourcesand network connectivity Enable the camera 0 I youte using the PiCar, this, ill be disabled by default. You can enable this in the respi-config tool. This can be accessed in the GLI by opening Menu > Preferences > Raspberry Pi Configuration, where you should select the interfaces tab and switch Camera to Enabled Altematively, run sudo raspi-config and choose option 6, Enable Camerafor USB webcams, use [J do apt-get install fswbcon And test with Test the camera OB uerrarsserhs project up tofind that the camera doesr't actually work Whether youtre using 2 USB webcam corthe PiCam, youll need to runa command to test the camera. To confirm, use the GUI to browse to / home/pi and view the image jg fie This is preferable to checking in the command line, 28 you can ensure the image is not corupt Install motion 04ers software, motion, can be installed after an update and upgrade of the Raspbian 05. sudo apt-get upgrade leet avccner install mxion [= apt-get update Older versions of motion will not start automatically, and display the “Not starting motion daemon’ ertor message. To avoid this, you need to make sure you run the update and upgrade commands. fyou'e using the PiCam module, youll also need adhiver. Activate PiCam driver 0 To activate the PiCam driver, you need to enter the following command: Hisudo modprobe ben2s35-vil2 This enables the PiCam to communicate with third party apps, such as mation. However youll need toinvoke the driver everytime you reboot, unless you addi to rclacal Open the fein nano [sudo nano /ete/re.local Find an empty line before exit ="0" Projects and enter. Trodprobe bon2835-v4l2 Then CTRL+X to exit, and ¥ to save Auto-start motion OG arrest een configuration fle [sudo nano /etc/default/notion Here, we need to instruct the software to starteach time the Raspberry Pi boots, Find the value ‘daernon off” and change it to read Hesenon on Hit CTRLIX to exit, tapping ¥ to confirm you wish to save the file, and Enter to continue. Next, confirm the motion daemon ‘works ona reboot by restarting yourPi Bi suco reboot Configure motion O7 Terese swcenique the motion software. This means setting the frame-rate (how ‘often an image is captured), image dimensions (laraer images wil take up more resources, thereby slowing the monitor) and setting the video format How you configure motion really depends on which model of Raspberry Piyou will be using for this project Fist generation devices will 7 Projects stil handle low-resolution images comfortably fora hires feed, you should probably use the Raspberry Edit the config file 0 Edit the config fle To begin configuration, just ‘open motionconf Hse nano /etcnotion/nation ear Use the CTRL#W shortcut to open search, find each ofthe following conditions, adding the values as specified a. searais 2 width 640 height 480 Fpeg_video.codee pees stream_localhost off Beontrat tocotiest: or? Hf youte recording in a dark room, you Can adjust the brightness and contrast. With the changes made, hit CTRL+X to exit, confirming with Y and Enter. Assign ownership to target directory 09% find that the camera stops streaming images after a short time. This is a permissions issve, one that causes a few images toappear on your screen before the whole thing times out. Overcome this with IE sudo chown motion: /var/ Lib/motion Get alerts with the Raspberry Pi baby monitor You canalso seta custom file path in motion.cont, Look for target_dir and change as appropriate. Remember to save the fle and restart motion when you're done, Start and test your baby monitor 10 Stee fully working baby monitor. At this stage, all thatis leftto get the baby monitor up and running isto launch the motion: Wiens srcncouscsesre, You should be able to browse to the feed by entering the IP address of your Raspberry iin a mobile browser. This would typically be something like 122.168.0.1:008 Check this on multiple devices on your home network to confirm that itworks Adjust motion detection Pee tao nse motion detection works right away. In order to adjust this forthe ervironment you have the Pi baby monitor set up in, open, BE sudo nano /ete/notion/notion conf and use CTRLW to search for “Motion Detection Settings’ Here youll find various conditions with values that you can adjust, such as threshold and area_detect_value These will equite some patient tweaking for the best results. Make motion beep TD cance detection, you can enable a beep to sound when movementis captured. As a project lke this needs some calibration to get the best results, this isa useful feature. ‘Again, this setting is found in motion.cont. Search for ‘quiet on” and change the setting to read Hause off Remember to undo this when youre happy with the movement capture, as itmay cisturb the little one! Adjust image quality While you can alter dimensions 1 of the images captured by the PiCam board, i's important to be careful with the figures you enterin motioncont For instance, a dimension of 133x255 pixels probably won't work. Dimensions need to be multiples of For larger options, look at 1280x800 or 1920x1080. Notonly will larger images impact bandwidth, they'l make the resulting AM fle larger Get alerts with the Raspberry Pi baby monitor Check saved images 1 To confirm the quality of the images captured by the Raspberny Pi baby monitor, boot into the GUI Grinstalltightwncserver and remote connect) and browse to /var! lin/motion to see how they are tuming ‘out. This should give you the info you need to adjust the dimensions of the captured images Troubleshoot camera connectivity 15 reeiroumeicetat motion will work straight away. Ifo images are found, or you cant connect to the stream, run: [tain -F /var/log/systog and W tinese | t2i2 This will display any issues that the process is currently having, which is intended to (and hopefully wall) help you diagnose and resolve any problems. Most issues will be driverelated, so keep this in mind with USB webcams Press CTRLAZ to end, Name your images 16°" collected by the motion software can be configured with a specific naming convention, based on date and time You can find these listed under “target base directory” in motion cont. For instance, you can specify folder for new images, based on date: BD tnt /10-evtnztras-zq) Note the 7" — both directory and Projects images will be named according to date, with images also labelled with the timestamp, Go beyond your home network 17 eestor your chiles sleep from your favourite restaurant? You can do this by installing the No+P software on your Raspberry Pi. This software enables you to get around the fact that your SP won't giveyoua dedicated IP address without paying a hefty premium, by installing a cient app that enables you to view the baby monitor outside your home network Head to wwwnnoipcom and check their knowledge base for deta Projects What you'll need... Aportable hard drive Raspbian srenanpberporgtioloas Pew Reeth eR Deluge Svadeugeronents External storage Store cmplee leon an eter ard ahve frmore spacer esy wana “The Raspberry Pi makes for a great tiny, low-wattage, always-on torrent box to better manage your files” Build an always-on torrent box Build an always- on torrent box Torrenting your open source software has a number of advantages ~ it can be faster, alleviates bandwidth and allows you to share back with the community. Distros, packages and more are available via torrents, and the Raspberry Pi makes for a great tiny, low-wattage, always-on torrent box to better manage your files. Wired networking Yeufbetanfertng ge amountsof amg rednerwarungeomust Install Raspbian Raspbian works justfine for our 01 Sreroacimcline ase on an SD card and go through the basic setup process, making sure to enable SSH in the advanced options and to disable the desktop, Remote access Type ifconfig into your Bis 02 Sirmardine:oteaher address. At this point you can unplug the monitor and set it up remotely, but either way you cen now access the Pi bytyping Is ssh fuserletip address) and entering your password to login. “Tiny and convenient “Tumyour Minoan ays on torent bonyoucanhiienalwcventaed) sralpsce Build an always-on torrent box Mount hard drive 0 Unless you plan to reformat ‘your portable drive, youll need toinstall NTFS support onto your P Type in Hs sudo apt-get install ntfs 38 ‘Add the hard drive to etc/fstab (open itwith sudo nano /etc/fstab) by adding the line: I ddewthard drive address] [mount point] auto noatime 0 0 Use fdisk to find the name of the storage, and create a mount point such as /home/pi/torrents with mk. Reboot for it to mount. Install Deluge torrents. Install t with Is sudo apt-get install deluged deluge-console Now start and then siop Deluge soit creates a config fle we can edit with Is deluged Bs sudo pkitl deluged And finally, un the following to copy the configfilein case we mess up $ cp ~/config/deluge/auth ~/confi’ deluge/authold 04“ use Deluge for our Basic configuration O5 fw deluge/auth And add to the bottom: B tusert:fpasswordt:1¢ to estict access Now start it up with: Is deluged Is deluge-console Remote connection Now you'e in the client, 06 typetthe following three commands: [contig -s allonremote True H contig atlow_renote exit Restart the Deluge daemon with Hs sudo pkit1 deluged 88 deluged Now open the araphical cient on your Linux PC © concton Manage Remote interface 07 2rreeee Interface, then disable Classic Mode and restart Deluge. Click ‘Add on the Connection Manager, and enter the IP in Hostname and the user we set up earlier Click Connect to see any torrents you have downloading or uploading. Projects Download location 082” Edit again and then Preferences, and change to the Downloads tab fits not on there already. Set the download location to the directory we mounted the hard driveto, and enable ‘Auto add torrents, setting it to ary destination i youplan to dump torrents to the Fi Start on boot OQ fiesrettonuourucan be used tohave Deluge start con boot. Download it with Hs sudo weet -0 /etc/aefautt deluge-daemon http://bit. Iy/13nKOS} Open /etc/default/deluge-daemon ‘with nano and change the usemame tothe one we set up eater. Save it, then download the full int sert and Update with Is sudo wget -0 /etc/init.d/ deluge-daemon http://bit. Iy/3nkKlz Is sudo chmod 755 /etc/init.d/ deluge-daemon IDs sudo update-re.d deluge- daemon defaults Projects What you'll need... Raspbian Wheezy HDMI cable Monitor Stream Internet TV to your Pi Stream Internet TV to your Pi ind v Finding the content you'te interested in viewing can take a while Whether youte looking for Internet TY stations, video podcasts, audio podcasts or shows syndicated online, taking the time to find and download them can be slow going, particulary if you have a busy lifestyle. You might even have ne time to watch after you've waited for the download. Thanks to the Miro media management software, we can automate all of this, and with the software running on a Raspberry Pi, you can easily build a compact system for downloading and playing back shows that you have an interest in. We're talking targeted TV on demand, which makes this project ideal for staying up to date with particular news and trends on a certain topic. MMe Set up your Pi with Raspbian 1 eee eee oie sse vate to \Wheezy, available via raspberrypi.org/downloads/raspbian. Ensure your Piis connected to a TV or display via HDMI. AS Mirois a desktop application, you'll need yourmouse and keyboard connected to configure it Stream Internet TV to your Pi Projects Above Miro gvesyoua Install Miro decent playback interface hd exelent export options , fer converting videos for (D2 ee ett meu cated you Poms cpen therm ‘Terminal and enter: I sudo apt-get install miro Installation wil take a few moments. Once complete, you'lfind Miro in Menu>Sound and Video Click to get started Set Miro to launch at startup O3 Massrsion configured to launch at startup. Open le>Preferences>General and check ‘Automatically tun Miro when Hog in’ and ‘When starting up Miro remember what screen | was on when I last quit, Also set your Pi to boot into X using the raspi-config utility. Check for content 4 Seishinste res [TG and place acheckinthe box ja LL, Bele labelled Show videos ftom pod inthe Videos section’. On the right- mom hand side ofthe window, set your ferred frequency for checking for new content. Mo will poll your favourite websites and feeds based on this setting, Projects ight lack setings can be ated the evant ab wen secessing Mia's Preferences Stream Internet TV to your Pi (Aaya on na aepae ido L Atrnabcaly anal fir sues hun aval omnes ayback (Ply vdeo and nti tems one erat? Sep ater ideo auto ter Resume Poytock conan playing dee rm nha hy wa at oped 1 concn paying mui es tem where they wer ast taped 1 conan ping pens fis ram wna hey em st gp Conf igure playback settings 0. i Yoeaaw the Playback tab, and check Play media in Miro. This limits reliance on other apps, which may drain resources. You should also click the Play video and audio items one after another radio button, ‘and under Resume Playback, check the first and third items, “The more links you add, the more regularly updated content will be downloaded to your media manager” Source videos and podcasts 06 Wrticnorse ued ready to play back the video ‘and audio content that you want to enjoy it's time to find some! The best ‘way to do this is to just check the ‘websites that you regularly use for video and audio podcasts (preferably ‘the former) and then copy the XIML link. ‘Add Podcast feeds 07 In Miro, open up File>Add_ Podcast and then paste the podcast feed URL into the dialog that appears, clicking Create Podcast when youte done. The more links you add, the more regularly updated content will be downloaded to your P-powered Miro ‘media manager, ready to watch or listen to on demand. Stream Internet TV to your Pi Projects oo Fie Sidebar Plafsts Playbeck Sats Comment Heb ‘ter the Uo ‘Above Youcan subse First time use Avoid YouTube eg vencais nt te 08 mzeatents OO Rzzistnatcs comedy ancinews podcasts tutorial when we instructed to building a video podcast Miro to behave in a particular way streaming center, displaying material hen it aunched? I's time to setthat that youte interested in on demand, behaviour now. i's sadly ust no good for videos on The processis started by opening YouTube. This doesn't really restrict the Videos view in the left-hand pane you too much as there are plenty of of the Miro window, and then playing other media outlets to cover, but it's the first video. Each time you boot worth mentioning if youre a frequent your system, Mico will jump to this YouTube watcher Ths isa shame, but View and immediately begin playing shouldn't impact the way you use your content, making sure youget up _it- your Raspberry Pi now downloads and running quickly and smoothly focused content on demand. Checking for new content 10 Itistempting to seta regular frequency for your content checking in File>Preferences>Podcasts, but note that checking too regularly is {going to resutt in resources being hogged temporarily, which may result in an interruption if you happen to be actually watching something when Miro checks for new content. Limit polling to hourly or daily checks. Projects What you'll need... Raspberry Pi2or3 with Raspbian Jessie Wé-Fi dongle rusingraspbenyPi2) Display total 7neh Teucscren Display ecommended) Phillips screwdriver Frame and/or stand (xitsbe options forthe ofc! ouchscrean ply are avalableat Poors and othe deicated i fardwareandacessorysupphers) Scripts intpstthucomamueleyospbery Phote-tame Make a Pi-powered digital picture frame Make a Pi-powered digital picture frame Digital picture frames that display a selection of your favourite photos were quite popular for a time, but are now seemingly available only as free gifts when signing up to magazine subscriptions. These tabletlike devices often made for interesting talking points, but were often let down by low memory, a poor user interface, or both, Make a Pi-powered digital picture frame Projects We don't have to worry about either of those problems with this project. Here we are going to set up a Raspberry Pi with some photo-displaying software, connect a touchscreen display, place it ina suitable stand, and sit back to enjoy the results. Better stil, with this set-up, welll be able to pull images from a range of online and offline sources, giving us some great variety. Prepare your Pi Oats of time with this project f you ensure that wireless networking is set up, and SSH is enabled, Do both via the Raspbian Jessie desktop - youll find the new Raspberry Pi Configuration utility in "5, et up a Menu>Preferences, where you can enable SSH in the Interfaces tab. . Raspberry Pi Gonenneneeny .. _ with some OD Wreeislonyardeiomac shes comes he eigen photo-displaying the back of the 7” Touchscreen Display, making sure that the eables are software” connected correctly. (Older releases require you to also connect and mount the display board) Secure with screws, and then mountin stand, Make a Pi-powered digital picture frame Lightdn.conf ‘Add this ine under SeatDefauls: ) Naturally, youl need a PD collection of photos to cisplay con the Prpowered digital picture frame. We have different options here (See boxout, page 107) but xserver-commandéX -s @ ~dpns ‘When done, save and exit with CirlaX, recommend you start with photos then reboot stored on your P ones that have been copied via USB, via a network drive, or sudo reboot downloaded through your browser. Nimage viewing software feh () Jj configure the Raspberry =D isthe best option for building JF rasa picture frame,wefrst 4 simple Pi picture frame, so install this need to prevent the sereen from switching off This means editing the sudo apt-get install feh lightdm.cont file , ‘Once installed, instruct feh where to sudo nano /etc/lightdn/ find the images, changing /media/ STORAGE/test with your directory path, eg, [orsetay=:0.0 xauTHortTy=/home/ pi/-Xauthority /usr/bin/feh -q plF-R 6 -¥-D150/ media/STORAGE/test Make a Pi-powered digital picture frame Save the script 0 The previous script should have prompted the Raspberry Pi picture frame to begin displaying images from the specified folder, for 15 seconds each, To force this to start at boot, we need to add it into a script. Greate this with: [sudo nano /tome/pi/start= plcture-frawe.sh ‘Add the following, Devinn DISPUAe8. 9 RALTHORITY=/home/ pirxauthority fos/bin/ten a spar oR 60 -¥-0150/ medi a/STORAGE/test Exitand save, then test with: bash rone/pi/start-picture- frame.sh Make picture frame run at boot 0 The script can now be set to run atboot Open BE sudo nano /ete/rc.local and before exit 0, add: [sexo 19 su - pi -c ‘/bin/bash /home/ pifstartpicture from sh & Save and exit. Reboot your Pi and test 08 youte pretty much done! To testit out, use the Usual sudo reboot command to restart the Raspberry Pi and check that the device boots straight into picture frame mode: Ifyou experience any problems, check that your commands have been entered correctly, and in the right places using lightdm.cont ‘and rclocal Stop the picture frame 0 Should you need to stop the picture frame software at any time, this can be done with the following simple command [sudo pkitl feh ‘As long asthe images you prepared for your picture frame don't take up too much space on the disk, they should load up without any problems. Projects Did you know... Build a Raspberry Pi-powered car oa | Bullda Atoy RC carwith two A channels (steering and drive) eae Raspbe Servo driver jumper cables SV battery power bank ° Ente #0790 Hoowered Car Components from Make use of cutti eda i wavwumodmypicom eb Build a Raspberry Pi-powered car @ 47 Web technologies are moving forward at a huge pace, cloud technologies are bringing mass computing 1o individuals, and hardware has reached a perfect moment in time where sensors, displays and wireless technology have all evolved into efficient and affordable devices. We truly are at a point where nearly anyone can take an idea from nothing to a working product in a week and at very little cost. Just lke this project, which is fun, quick and easy to build on and a fantastic way to learn, We're going to grab an old remote-control car, rip off ts radio receiver and replace it with the Raspberry Pi, hook it up on the network, fire up a bleeding-edge web server and then get your smartphone or tablet to control it by tilting the device. By the end of this, not only will you have a fun toy, you will have leamt about the basic technologies that are starting to power the world’s newest and biggest economy for the foreseeable future Projects Build a Raspberry Pi-powered car Raspberry Pi-controlled car build process To help our toy car come to life using the latest web technologies and our credit card-sized computer, we're going to need to make some pretty significant changes to its workings. Fortunately, the most complex aspects of the build can be accomplished with a couple of affordable purchases, namely a servo controller board to take care of the steering and throttle, and a 5V battery pack to keep the Raspberry Pi running smoothly. Identify and remove old radio OTmsece effectively battery forthe electronics, but those supply elsewhere. Many shops sell replacing the car's normal (especially with an electronic speed SV battery power supplies - often as transmitter and recelver.Noticethe controller with BEC) get their SV mobile phone emergency top-ups. three sockets on the original receiver, power supply directly rom the speed www.modmypi.com sells a suitable cone goes to the motor controller controle, saving on components SV battery power bank for under £20 and one to the steering servo.Some _fyoudon‘thavea speed controller and you should get a couple of hours remote-control cars also have separate with SVBEC, youll need to get a5V_—_of use from your Raspberry P Powerup TissVatery packkanns wrt =e Servocontrol ‘Adafrle PWM 2 servodverboard from wmodmypicom powered The Raspbery Pst front andeentretokeep hassafe spossble Pickacar ‘oucan use pretty much ny sfforale carter thi project Build a Raspberry Pi-powered car Attach the servo cables to the new controller O2 = 6-channel 12 servo controller board from www.modmypi.com as per its instructions and simply plugged channel 0 (steering) and channel 1 (moto) headers onto it There are six cables in total:the bottom two are ‘ground, the middle two are the power and the top two are the PWM (pulse- width modulation) signals. Thisis 2 good time to thinkof places to mount the extra components and the best fixing ‘method seers to be sticky-back Velcro. Connect the I2C bus to the Raspberry Pi 0 We're using the Raspberry Pi's 12C bus to control the servo interface board, which only needs four cables they all go between the Raspberry Pi and the servo controller board as pictured, Visit httpbitly/ N3nq4j for a tutorial on how to set up BC on the Raspberry Pi From top tobottom we need to use the 1. GND, 2. SCL, 3.SDA and 4 ‘VCC, which map directly to the same ports on the Raspberry Pi Essentially this s power, ground and two communication channels. Find everythi a home Overview of the main components 0 Youshould nowhavethe 0 servo board in the middle Projects Hook it up to the Raspberry Pi 4.3 ee Rate she ‘ables look the same. Though the Rev boards have different labelling, the physical pins are inthe same place. Bottom left (losest to the RasPi ower connection is the 33V power; next to that is the SDA header, which isthe data channel. Next to that in the bottom right isthe SCL channel, which ‘controls the dock of the I2C devices. ‘And finally -on the top-right port ~is the Ground. We recommend printing a labelled image of the GPIO pins. We can now put ittogether. Use plenty of sticky-back Velcro, tie wraps or elastic bands to keep everything secure and find spaces in the car's with the steering servo and speed controller on one side and the Raspberry Pion the other. The motor is connected to the other end of the speed controller (that end should have much thicker wires, the speed controller also has two thick wires going to the main cars battery - in this case a 72V NiCad. We now have two very separate power systems with the high current motors on one side and the low current electronics on the other. Let's make sure it stays that way. body to hide the wires where possible. While itis possible to stick or screw the Raspberry Pi directly 0 the car, we recommend to use at least the bottom half of a case for added protection and ease of access. Insert your SD card, network cable or Wi-Fi dongle and power supply Sit backand admire your hacking skis Projects Control your Raspberry Pi-powered car What you'll need... woncamveg,”” ~— CONtrol your Aninternet connection ‘omy _ Raspberry Picar source code aoe Pipowered car Now that we have our fantastic Raspberry P-powered car all wired, charged and ready to go it's time to make it come alive. We're using the best web technologies that the JavaScript programming language offers, to harness the natural movernent of your hand and wirelessly drive the vehicle Each litle movement of your hand will trigger an event that calculates what the car should do and then sends it over a socket connection. Ifall goes to plan you should have complete control over your vehicle Below Allyou need te frish eff your projects access toa smartphone or able 01= of all you will need to the I2C connectivity ‘working, Next wellneed to find a home for our new project code —how about /var/www/picar Type sudo mkdir /var/wen/picar in the terminal to make the directory and then change into that directory: ed. /var/ ww/picar Now, to download the project using Git, type sudo git clone http://github.con/shaunuk/picar- Ifyou havertt otGit instal with sudo apt-get install git. This will download the custom software for diving the car, but we sil need the webs server and some other bits before we can start buming rubber. Control your Raspberry Pi-powered car Do 2 d install Node. Next were using Nodels and its package tool, the ©. Node package manager nom).Type sudo wget http://nodejs. org/dist /v0.10.21/node-va.10.21-1inux arm=pi.tar-gz. This will download a feily recent version of Nodejs-- the version Raspbian has in its repositories is way too Gd and just doesn't work with the new technologies we're about to use. Extract the node package by typing sudo tar -xvzF node-v0.10.21-linux-arm-pi.tar.gz Below You ncedtoadst some ofthe variables to conto your partic remote conta ar setup To make iteasy to un from everywhere, we wall create symbolic inks for Node and npm binaries. Type sudo In =s. /var/wwn/node-v2.10.21- Linux-arm-pi/bin/nade /bin/node and then sudo In -s /var/www/node-v0.10.21-Linux-arn-pi/bin/ rnpm_/bin/npm. Then, to get the extra modules, type rnpm install socket io node-static socket.io adafruit-i2e-pun-driver sleep optinist Now we have everything, you should see three fies the server (apps), the client (ockethuml) and the jQuery JavaScript library for the client The server nat only drives the servos, butt isa web server and sends the sockethiml file and jQuery to the browser when requested ~itsa really neat and simple setup and just right for what were trying toachieve IE Our handy ttle program (ppjs) has a special mode just for testing. keywords here: beta for servo 0 (steering) and gamma for servo 1 (motor control) Type node apo. js beta=300. You should see the front wheels tur. Now the numbers need ‘experimenting with. On our example, 340 was lef, 400 was centre and 470 was fight. Do the same for the motor by typing node appjs gamwma=400 and take note of the various limits of your car Projects ey Hrme Control your Raspberry Pi-powered car “We're using the best web technologies that the JavaScript programming language has to offer” Configure sensible defaults Now you know what your caris capable OG Sire can sete detutsnappisand socket html Edit app js and find the section that says function emergencyStop!. Adjust the two numbers to your car's rest values. Then open socket html and adjust the predefined values Under’Define your variables here! Going for a spin [8 Acre vactar at hse esata the IP address of your Pi car, so type ifconfig atthe terminal Then fire up the app by typing node app js. Now grab the nearest smartphone or tablet, making sure ison the same network as your PL Open the web browser and go to httpe// [your IP address}8080/socket.html. You should get an alert message saying teady’ and as soon as you hit OK, the gyro data from your phone willbe sent to the car and you'e off. ———— de socket html fe. angle to get var wingomas © 250; //backwards 1 var maxgamma = 400; //forward limit var multganma ctor to multiply the dicate of accelerati