MrRsPiManualGuide-KernelPanic

204
(Please wait while this loads! Don’t try opening on a Pi at all, it won’t ever finish!) Dedicated to John Routledge 03/02/47 10/05/2013. He never hid the screw drivers! and Penelope Alice Routledge 21st July 2013 Last Updated:12th Nov 2013 Total Pages 204 1

Transcript of MrRsPiManualGuide-KernelPanic

Page 1: MrRsPiManualGuide-KernelPanic

(Please wait while this loads! ­ Don’t try opening on a Pi at all, it won’t ever finish!)

Dedicated to John Routledge03/02/47 ­ 10/05/2013.

­ He never hid the screw drivers!

and Penelope Alice Routledge21st July 2013

Last Updated:12th Nov 2013 ­ Total Pages 204

1

Page 2: MrRsPiManualGuide-KernelPanic

Random Links to Sort. 2http://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/robot/getting_started/http://pkgs.org/http://www.moop.org.uk/index.php/2013/08/10/voice­controlled­lights/

WinSCP not able to copy files?Defaults !authenticate

To the /etc/sudoers file.

Currently Working on:­ Setting up Newsreader on a Pihttp://www.howtogeek.com/162060/how­to­install­nzbget­for­lightweight­usenet­downloading­on­your­raspberry­pi/

­ Mini CNC Laser Engraver ­http://funofdiy.blogspot.co.uk/2013/10/a­raspberry­pi­controlled­mini­laser.html

­ DukePad ­ https://wiki.openjdk.java.net/display/OpenJFX/DukePad

­ Cloud Lamp ­ http://falldeaf.com/2013/07/the­pi­control­script/

­ Sonic Pi http://www.cl.cam.ac.uk/projects/raspberrypi/sonicpi/teaching.htmlhttp://www.raspberrypi.org/phpBB3/viewtopic.php?f=63&t=58313&p=438279

­ Internet Radio Receiver.http://www.tommedley.com/403/raspberry­pi­radios/

­ NFC with the PI.http://learn.adafruit.com/adafruit­nfc­rfid­on­raspberry­pi/overviewhttps://docs.google.com/viewer?url=http://learn.adafruit.com/downloads/pdf/adafruit­nfc­rfid­on­raspberry­pi.pdf&chrome=true

­ Raspberry Pi Camera module Web Streaming using Motion.http://www.raspberrypi.org/phpBB3/viewtopic.php?p=356814

­ IKEA Lights Hack

­ Setting up the Pi as an Wireless Access Pointhttp://learn.adafruit.com/setting­up­a­raspberry­pi­as­a­wifi­access­point?view=all

­ Pirate Pi???

2

Page 3: MrRsPiManualGuide-KernelPanic

­ Minecraft rendering 3D OBJ Models (Cthulhu didn’t work very well, nyan cat to follow!)­ SiriProxy Test at school?­ Using Cameras ­ Working with PS3 Eyetoy (only connected to Pi Though, not the hub!!!),multiple cameras running will try timelapse video next, time lapse up and running, but need to doa serious school test!!! (removed the IR sensor from a PS3 Eyetoy, now will pick up Infrared, ormore importantly if you bathe stuff in an IR Light (stronger than Wii Bar) you can see what’shappening in the dark!!!­ EmulationStation ­ selected PSX games not working.­ CUPS (Printing from Linux!) ­ Tested and need tweaking, try at school.­ Telnet http://www.youtube.com/watch?v=NS6t8HnrrXw­ PiUi ­ http://blog.davidsingleton.org/introducing­piui/

­ Connecting your Pi to GMail ­http://mitchtech.net/connect­raspberry­pi­to­gmail­facebook­twitter­more/

­ Remote Pi Accesshttp://pihw.wordpress.com/guides/direct­network­connection/

­ Pi as a NAShttp://www.makeuseof.com/tag/turn­your­raspberry­pi­into­a­nas­box/

­ QRCodes on the Pi.http://linuxg.net/scan­qr­codes­in­ubuntu­with­libdecodeqr­simpletest/http://linuxaria.com/pills/qr­code­in­linux?lang=enQreator???http://ralgozino.wordpress.com/2011/06/13/how­to­create­and­decode­a­qr­code­in­python­using­qrtools/­ ZBar https://github.com/herbyme/zbar QR Code Checker.

­ XBOX 360 Ring / RF Transmitter Hack.http://www.astrorats.org/blog/2013/07/29/xbox­360­rf­module­and­the­raspberry­pi/

RFID Ideashttp://www.raspberrypi.org/phpBB3/viewtopic.php?f=37&t=55321&p=419718

PiPresents ­ https://github.com/KenT2/pipresents­nexthttp://pipresents.wordpress.com

3

Page 4: MrRsPiManualGuide-KernelPanic

On the back burner ­ Stuff to try when parts arrive! :) 4

­ LED INDICATOR (Some good stuff here)http://www.howtogeek.com/140063/build­an­led­indicator­with­a­raspberry­pi­for­email­weather­or­anything/

Cheap PIR Sensors.­http://www.raspberrypi­spy.co.uk/2013/01/cheap­pir­sensors­and­the­raspberry­pi­part­1/

Berry Cliphttp://www.youtube.com/watch?v=r­4kHfQ0cJI&feature=em­subs_digest

How to use Pi as a low power network storage device.http://www.howtogeek.com/139433/how­to­turn­a­raspberry­pi­into­a­low­power­network­storage­device/

Steepen Motor Controller?I ordered two from “4tronix_uk” on eBay and they arrived the next day. There are additionaldetails in the Stepper Motor 28BJY-48 Datasheethttp://www.raspberrypi­spy.co.uk/2012/07/stepper­motor­control­in­python/

Ultrasonic Distance Meterhttp://www.raspberrypi­spy.co.uk/2012/12/ultrasonic­distance­measurement­using­python­part­1/

Stuff I’d like to buy if I had the cash. 4

­ PI Lite LED Matrix ­http://cpc.farnell.com/ciseco/b040/pi­lite­led­matrix­raspberry­pi/dp/SC13018?in_merch=New%20Products&MER=e­bb45­00001002

Rapiro Robot Kit­ http://www.kickstarter.com/projects/shota/rapiro­the­humanoid­robot­kit­for­your­raspberry­p

Frindo­ http://robotbits.co.uk/robot­kits/frindo­robot­kit/prod_162.html

4

Page 5: MrRsPiManualGuide-KernelPanic

General Links. 5

Official Pi Stuff http://www.raspberrypi.org/ ­ The official Site.http://www.themagpi.com/ ­ The Magazinehttp://www.raspians.com/ ­ Raspberry Community ProjectsOCR Guides / Recepie Sheets ­ Guides and Tutorialshttp://pibeginners.com/ ­ Pi Beginners Youtube Clips.http://downloads.raspberrypi.org/Raspberry_Pi_Education_Manual.pdf ­ Pi Education Manual.

Python and Programming http://www.codecademy.com/ ­ A great prgramming place to start.http://pythondictionary.code­it.co.uk/ ­ Python Dicitonary / Resource.http://www.pythoncode.co.uk ­ Good examples / tutorials / questions. (Based on Python 3)http://www.ictvideohelp.co.uk/python.html ­ Python Videos.http://usingpython.com/ ­ Using Pythonhttp://www.pythontutor.com/visualize.html#code=#Enter your python program here.%0A#Press 'VisualizeExecution' to see it running line by line!http://www.tutorialspoint.com/python/index.htm ­ Seems like a simple resource with examples.http://www.staff.city.ac.uk/afl/tinybasic/index.html ­ TinyBasichttp://inventwithpython.com ­ Some good guides of Python / Pygame.http://pythonbooks.revolunet.com/ ­ A good selection of python books.

Linux General http://elinux.org/RPi_Hub ­ Great source for Pi info / hardware.http://linuxmanpages.com ­ Linux Commands, no fuss.http://unix.stackexchange.com/ ­ Linux Q&A Forums.

Youtube Links / Channels GigaFide / TinkernutRaspberryPi Tutorials ­ http://www.youtube.com/user/RaspberryPiTutorialsRaspberry Pi IV Beginnershttp://www.youtube.com/user/raspberrypitutorialsOCR Pi Tutorials

5

Page 6: MrRsPiManualGuide-KernelPanic

Foreword 6My father died suddenly at 66. This document would not exist without him. He did not effect it directly, (orprobably even know of it’s existence) When I was a boy I wanted to ‘work with computers, like daddy’. Ialso seemed to have a knack at taking things appart. Luckily for me Dad never hid his tools or thescrewdrivers, they were always a couple always present in the ‘Draw of Doom’, (EVERY house has one,usually a small draw full of bits, fuses, a torch, batteries and other assorted guff.) I made good use of themto fulfil my curiosity of what was inside things! Indirect support often goes unnoticed, but Thanks Dad Iowe you!

This document has been a labour of love. I’ve spent far too long messing with Pi’s and not writing stuffdown. I hope this guide is useful. It will be for me, but hopefully it will get passed into the hands ofstudents. Those with more time to experience and mess with the system, to continue to innovate, design,create and best of all dream! I don’t mean to tread on anyone’s toes and a lot of this is copied and / orpasted from t’web.

This document is a scaffold, it will take you to numerous websites, is totally full of errors / mistakes and halfcompleted instructions, but like I say it has come together over a year and I plan to keep adding to it. Ifyou find a mistake or wish to add to it then Email me, I’ll fix it. (Similarly if you want anything that isexplicity yours and you don’t want sharing then again email me!)

This document is very much NOT my own work, just TONS of stuff that I’ve copied from other peoples sitesand hard work. As such please ‘share and share’ alike, that’s what the original authors would want! (Notthe creative commons link at the top!)

I’d like to say THANKS to everyone the guys (and gals) at the RaspberryPi organisation that dared to create,see a project through and hopefully reap the rewards. The people who have created individual projects /tutorials etc that I’ve lovingly followed and all those who offer tons of help and support on the forums.

On a personal note, thanks, it’s been just the boot (up the a*se) I needed to learn some new stuff, Linux,Python and for the first time since Uni, pick back up my Multimeter! Let the projects begin! Although I’mnot very innovative myself I love taking other peoples ideas, giving them a go, and maybe combiningthem!

Thanks to all those who have spent the time listening to me rabbit on about how good these little boardsare. To Lloyd for keeping me busy with technical questions, Arron for helping me find answers andtolerating my Linux stupidity and Lewis for the blind belief that I could get Linux running on his Netbook. Ihope you both do well in the future.

Finally an apology to my wife as I’m sat here in the small hours of the morning when I should be in bed,knowing that I’m going to be knackered tomorrow, but I’m keeping my noggin busy and that’s importanttoo! As this document approaches 200 pages I wonder just how many hours I’ve spent dabbling! Bugger.

Keep on hacking.

Mr R.

6

Page 7: MrRsPiManualGuide-KernelPanic

Contents 7*Random Links to Sort. * 2On the back burner ­ Stuff to try when parts arrive! :) 4

­ LED INDICATOR (Some good stuff here)Cheap PIR Sensors.Berry ClipHow to use Pi as a low power network storage device.Steepen Motor Controller?Ultrasonic Distance Meter

­Stuff I’d like to buy if I had the cash. 4­ PI Lite LED Matrix ­Rapiro Robot KitFrindo

­*General Links. * 5 ­Official Pi Stuff *­Python and Programming *­Linux General *­Youtube Links / Channels *

­Foreword * 6Contents 7­*FAQs* 15

Back Your card up often! (every couple of weeks!)What happens if (when) you corrupt your memory card!Constant keyyyyyyyyyyyyyyyyyyyyyyyyyboard pressesCorrupt MemorycardConstant Reboots.Reboots when you plug something USB in!­Falling off the Network RandomlyApt­get update Fails.SSH on the school system???

­The Hardware 18

How to check what RPi.GPIO version you haveHow to check your Raspberry Pi Revision number?

* DISTROs. * 20Backing up the Memorycard using the PI (working)Setup Raspbian Memory Split and config.Update and Install updated packages!­Recommended Packages to Install (You’ll probably need them later!)RPi­update ­ Firmwaresudo rpi­update* GitHubs Worth Cloning *

­Backing up files to GDrive (Tested)

* PC Software to get familiar with * 24SSH ­ KitttySSH or Putty

7

Page 8: MrRsPiManualGuide-KernelPanic

WIN32Imager7ZipAdvanced IP ScannerUltraVNC (Portable)Geany / Ninja IDE. (versions available for both Windoze and PI!)WinSCPXming / Xming Portable (not got this working for me! :( )MobaXTerm ­ Works as well as VNC

­Useful Linux Commands* 26

cd ~lsmvcpmkdirrmifconfighcitoolnanovilessapt­get installapt­get purgeapt­cache searchhistorydmesggrep>wget­helpdudf­Rps&&&depmodfilecat

­A note about the command prompt­Installing Software / DriversVI (Called using vi) a Basic Text Editor like NANO!

Edit a file, look at it, stop editingUsing GREP Properly.­

Basic syntaxAdditional Arguments

­SYSTEM 30

­Setting a Static IP (network address)How to Change Your Raspberry Pi (or Other Linux Device’s) Hostname

8

Page 9: MrRsPiManualGuide-KernelPanic

Why Do I Want to Do This?Changing the Host on your Pi

Setting up Wi­Fi *Setting up ad­hoc wifi*School Site Proxy Info (to remember)

Edit this file to set Permanently Across All Profiles.Allow programs other than Bash access to a (school) network under Proxy.Temporarily from the LXTerminal (not ideal and only works for ROOT!)

Changing the Font Size of the Terminal Textsudo dpkg­reconfigure console­setupChoosing which programs run when the Pi boots­Setting up VNC *

VNC ­ http://myraspberrypiexperience.blogspot.co.uk/p/setting­up­vnc.htmlRunning VNCServer at Startup

­Sound on the Pi. *Check Alsa & remove Pulse!Test the sound using­Force HDMI sound using­Making the Pi Speak *SOX ­ The Swiss Knife of WAV / Raw audio on LinuxMPG321Turning your Raspberry Pi into an FM Transmitter*­Voice Recognition on the Pi using Google Voice APIAsking Wolfram Alpha QuestionsText To SpeechCombining Speech to Text and Text to Speech.­*Mounting a USB the Easy Way! *

...Or the hard way­Printing on a Pi. *

­Making a Program LOOP FOREVER*

­Making a program repeat every so often (CRON Jobs!) *

­HARDWARE 45­CasesRaspberry­Pi­GPIO­Layout­Revision­2­GPIO Stuff­­Connecting a Pi to the outside worldPIN Basics­Making an LED Flash­*LedBORG ­ http://www.piborg.org/ledborg

Rev 2, 2013­09­10 or 3.6.11+ build #538Usage

9

Page 10: MrRsPiManualGuide-KernelPanic

Controlling LedBorgTo set the colour from a Python script:To set the colour from a terminal type:To set the colour from a terminal with the basic driver type:To disable LedBorg from a terminal type:To enable LedBorg from a terminal type:Managing boot options

­Singing / Screaming Jelly Baby (Probably works with Fruit Pastels too!)Make sound playback through the headphone socket

­Pi Camera Module­How to use the Raspberry Pi camera softwareExample commands­To shoot video with the Raspberry Pi CameraBerrycam Photos (Tested)Time Lapse Photos­Time Lapse Video from Stills.Converting the Video output­Extra Tricks by Bill TideyWatermarking with another Graphic!Using the Pi Camera module with MotionCreepy Face Tracking (Partly Tested)

­Cheap PIR Sensors and the Raspberry Pi – Part 1 (untested)­Robot Arm Stuff.

Robot Arm Basics­

Robot Arm with PS3 Pad­

Robot Arm With Wii­MoteRobot Arm GUI (in Python) ­ WIP­7 Segment Display Project (One of my first!)**­Chips for driving motors­LCD SetupCheap 3.5 LCD Display.

­HARDWARE ­ Controllers 84

­Graphics Testing / Visual Joystick TestWiimote Basics *

­Getting the drivers / setupRunning WiiMote as a Mouse.­Wii­Mote Button MappingsWIIMote InfoCreating Custom WiiMote Configs­Using Wii­Motes in Python Projects

­XBox 360 Pad*­Install the XBox Pad Drivers.Create a mapping file

10

Page 11: MrRsPiManualGuide-KernelPanic

Alternative Setup For XBMC.­Call the mapping using

­Using a PS3 controller*Dualshock 3 and Raspberry PI

­PS3 Move???­PS3 Joystick Buttons and AxesQJoyPad ­ Turning Joystick Commands into Keypresses.

­HARDWARE ­ USB Devices* 98

­WIFI ADAPTER???

TP Link wn725n (V2)Edimax Dongle

PS3 Camera Test under XDE.PS3 Eyetoy Camera StreamingFace Recognition on the Pi.

GUVCVIEWCMAKEOPENCVInstall the face recognition APIInstall the Reco ProgramFINALLY...

­Removing the IR Filter on The Eyetoy­Using Multiple Cameras with Motion­Retaliation (USB Rocket MOD!)Retaliation Modification to Script. (TO REDO to use KEYBOARD!)­TVHead Test for XBMC

­SOFTWARE 109­GitHubs ­ Why They Rock!

How to clone your repo to your local machine ?­Compiling Your Own Version of Software (Roll your own!)

­Grab­Configure­MakeMake Install

­SOFTWARE ­ Interfacing 111

­Pi­Wall (WORKING!)Setting up the units.Network configurationTesting the software­Looping an Video on the screens.Multicasting Input from the Pi Camera (untested!)

­FritzingPI­CarUsing Twitter

11

Page 12: MrRsPiManualGuide-KernelPanic

Creating An Array of Followers (Partly Tested)Creating a Python Script that can Tweet (Tested)Creating a Python Script that can Tweet Images (Tested)­Create a Python Script that can Tweet Images Via Raspicam, watermark them and TweetThemCreating a Python Script to Output System Info­Tweeting on a Set Interval­Read Out Tweets (Untested)Tweeting Webcam Pics (Part Tested)­­ Reading Tweets from a #Tag­Creating a TweetBot

­SOFTWARE ­ GAMES 123 ­

A good list of Games that run on the Pi­SDL DispManx­­Q3 Arena on RASP PI (Build)­Quake 3 Quick Install ­ School Build

School Build Error solutionsOR fix the permissions so non­root uses can access /dev/input/mice and /dev/input/mouse0as follows.Create new file in "/etc/udev/rules.d/99­input.rules"Add a new group and add your user(s) to it (my login is just 'pi')Sound through headphonesShow FPS in GameQuake 3 Config File Guide

Full version of Quake 3.Q3 ­ Models, Levels, Maps and ExtrasQ3 Console ManualQuake 2 on the Pi.Installing Quake 2 on PiInstalling DOOM 1 / 2

­OPTIONAL: Create a WAD­specific launcherOPTIONAL 2: Create a laucher for multiple kinds of DoomInstalling Aliens TC and Aliens Doom 3.0 (AVP) in Chocolate Doom.­Instructions for LAN play

­Installing Minecraft on the Pi.­Custom Textures PacksPython Scripts for Minecraft.

Rendering 3D Models in the Minecraft WorldMaking the OBJ Files.Viewing 3D Meshes on a Pi.wget http://jestermon.weebly.com/uploads/1/6/2/1/1621282/pyobjviewer.zipList of Minecraft Blocks

Minecraft Twitter (untested)­Installing Descent on the Pi (untested)

­

12

Page 13: MrRsPiManualGuide-KernelPanic

SOFTWARE ­ Games Emulation 148­A Note about ROMS­­RetroPie ­ Emcompassing Most Emulators.­RetroPie ­ XBox Pad­RetroPie ­ Exit Games Using Your ControllersRetroPie ­ Installing ROMsMAMENESSnes Emulator ­ SNES9xScummVMDGen

DGen Manual.DGen Build InstructionsTweaking DGenSonic Level Select

­DGen CONTROLS

­SOFTWARE Projects 154­

*SiriProxy ­ As UserSiriProxy InstallSiri Proxy PluginsAdding your own Siri CommandsSiriProxy ­ As Root

Ultrasonic Distance MonitorTaking Screenshots on the Raspberry PiSimple Samba Share *SMBGET (tested and working!)SAMBA Server on the Pi.

­*SOFTWARE ­ XBMC * 174

­Booting to Black ScreenWindows 7 and Adding Sources­How to add Sources/Repos/Addons­Custom XML for better remote usage (at least on our big telly!!!)­Fixing TV Scraper Error­Setting up a Shared Library

First setup the SQL DB.Edit the advancedsettings.xml

­Remote Controls.­Accessing Region Locked Content. :)­Get iPlayer­USEFUL BITS OF PYTHON 187

Running A Console Command Via PythonPassing Arguments to Python programs­Changing Terminal Text Colours / Effects Via PythonQuick Python Pygame Joystick Axis Detection (Tested and Rechecked.)

13

Page 14: MrRsPiManualGuide-KernelPanic

Using Pygame to detect Joystick Presses­Pi Club 192

Session 1 ­ Basic Setup (Network) and Minecraft (an Easy Win)What worked

Session 2 ­ USB Rocket LaunchersIssues

Session 3 ­ Quake 3 and Emulation (DGEN?)Suggestions:What Worked.:What didn’t work:

Session 4 ­ Breakout Board(s), Wiring bits?Suggestions:What Worked:What Didn’t Work

Session 4.5 ­ Fail.Session 5 ­ Robot Arm.

What WorkedWhat didn’t work.

Session 6 ­ Pi Camera.What WorkedWhat didn’t work.

Session 6.5 ­ A Short Pi Club due to meetings and other commitments.What WorkedWhat didn’t work

Session 7 ­ Minecraft Hacking on the Pi using Python Scripts?Session 8 ­ PiFM (Pirate Radio!)Session 9 ­ Twittering

­COST OF STUFF / PRICE GUIDE 196Linux Mini Guide (for Laptop / PC) 198

­How to Enable SSH on Linux Mint 15 /14 / 13 / 12VNC on Linux to Pi

14

Page 15: MrRsPiManualGuide-KernelPanic

FAQs 15

Back Your card up often! (every couple of weeks!)I’ve had cards die a few time, probably something I’m doing, could be dodgy hardware. But eventually thecard will die. It’s all good though as you did back up right? If you lose lots of stuff it’s your own fault.Luckily for me I’ve got a handy guide like this that keeps me up­to­date and helps so I don’t forgetanything!!! WICKED. If I’m a good soldier I’ll back up after every Pi­Club session (and keep what’s onthe card incase the kids mess theirs up too!) One word of warning, please try to keep to the same brandof memory card as an 8GB Sandisk card will NOT be same size as a 8GB Transcend card, it might onlybe a few MB, but it’s enough to NOT allow you to install the backup image you made!

What happens if (when) you corrupt your memory card!GRRRR: CAUTION if using crappy / cheap PSU / Cables you will probably end up with a corrupt memorycard (due to reboots etc!) This can cause much heartache, back up often. I speak from experience. ButI’ve always got this document to fall back on!!! Note if it all goes horribly wrong and you mess up yourcard, you can rescue it by using a Live Linux Distro e.g. Ubuntu (or Mint) this will let you (hopefully) graband rescue all the stuff from the memory card (just use a card reader!) but as it also has GParted on it,you can format your memory card back to something Windoze will recognise!

Constant keyyyyyyyyyyyyyyyyyyyyyyyyyboard pressesIf you start getting weird keyboard presses it’s due to the combination of hardware, namely the keyboardand probably the Hub. I’ve had this several times, I generally plug the keyboard straight into the Pi,everything else into the hub!

Corrupt MemorycardIf you’ve got a a memorycard that keeps becoming corrupt it might be due to dodgy sectors,recommendations is that you get a new card. I have a Sandisk SDHC 8GB class 4. Would be fine for afew installs, but then would seem to corrput. You’ll know when it becomes corrupt as it’ll start scrollingerrors up the page and lots of red warnings, you may also get errors on boot sectors and will ask you torun fsk!

Going to give a Trascend 8GB Class 10 a go instead!

Constant Reboots.I had this today with a student’s PI.... it just kept rebooting. It failed at some point while booting, seemedto have to a check of the filesystem on the memory card,, find an error and reboot (ad infinitum). Turnedout this was a dodgy power cable (between the Pi and the USB from the Computer powering it!) ­ Thanksfor this one Lloyd.

Reboots when you plug something USB in!Many devices, often WIFI dongles etc can cause the Pi to reboot when inserted. Some devices are fine(it tends to be the lower power ones!) Most USB Pendrives don’t cause the system to reboot (often youmight have to do the keyboard/mouse/memory stick shuffle if you don’t have a hub handy! However I

15

Page 16: MrRsPiManualGuide-KernelPanic

discovered today that Verbatim Blue USB did cause the Pi to reboot!

Falling off the Network RandomlyI had this wth a a Pi running powered by a PC, turns out it was the cable that was supplying power.Some cables just do NOT work. Took me a while, I suspected the Pi, or memory card, however it wasjust the cable. The Pi would appear on the network for a while, maybe run a few commands, then wouldjust drop off. You’d get an occasional error on boot.

Apt­get update Fails.if apt­get update fails, it could be for a few reasons. First check /etc/apt/apt.conf and check your proxy is

not still set, second check /etc/bash.bashrc and check the proxy lines (usually added at the end).

However if it can connect, but fails when building, or comes up with Reading package lists... Error!

It might be something has become a little corrupt. Well worth trying the following. Fixed it for me.Run

sudo apt­get clean

It will often tell you where the error occured, e.g.E: Error occurred while processing libwww­mechanize­perl (NewVersion2)

or E: Error occurred while processing gnoemoe (NewVersion2)

So after a bit of googling I ran this…sudo rm /var/lib/apt/lists/mirrordirector.raspbian.org_raspbian_dists_wheezy_main_binary­armhf_Packages

however you might have to run.sudo rm /var/lib/apt/lists/* ­vf

sudo apt­get update

16

Page 17: MrRsPiManualGuide-KernelPanic

SSH on the school system???

Most managed networks at school will not allow students to have access to SSH, it will be considered asecurity risk. However I know that it does work (as I can run extra software on my Laptop!) However ifyou want kids to have the benefits of SSH (and they’ll be doing lots of copy and pasting of code!) why notget them using a LiveUSB of Linux (Full blown linux, either Ubuntu or Mint!) I’ve recently been doing sometesting of Linux distros, mainly due to an overzealous student wiping his netbook in a fit of rage! Thenetbook an Acer Aspire One (225) or similar would happily boot a LiveUSB of linux, but would not installthe bootloader so when you tried an install you just got left with a blank screen maybe with a flashingcursor! However we tested lots of version of the LiveUSB (Ubuntu) in the hope one of them would work.Verion 9 went on okay, but didn’t isntall the network card drivers… useful NOT. However in all fairness,Mint went on flawlessly, and worked out of the box. The student seemed much happier using thanwindoze. So much so that I’ve been dabbling with it all evening and I’m typing this on my school laptop(running a LiveUSB (2GB tiny stick burnt with Win32Imager)) and am quite liking it. It’s responsive andstable (well Firefox is, Chromium (which I tried installing) not so much, but at least unlike Windowswouldn’t crash out completely, but would discreetly kill the page in question! However I tried an ‘apt­getupdate and upgrade’, this no longer fit on the 2GB stick (be warned!)

I have managed to pilfer a couple of old laptops that I intend to hook up to the school network runningLiveUSB versions of MINT, and see how they go. In theory they /etc/apt/apt.conf and /etc/bash.bashrcedits should be enough to get them up and running! :)

17

Page 18: MrRsPiManualGuide-KernelPanic

The Hardware 18All this document is designed to work on a Raspberry Pi Model B (preferably version 2.0), but some maywork with the 256 MB Version.

I’m guessing if you’ve reading this you either have a Pi, an interest in one, or at least held one! Pleasenote, version 1 has a black headphone socket, and no mount holes. Version 2 has a blue headphonesocket and mount holes in all 4 corners of hte board. (version 1 pictured ablove)

The key specs of Rapsberry Pi (a.k.a RasPi) are:Linux based operating system

700 MHz ARM11 CPU 256MB (or 512MB) RAM SD Card Storage 2 USB ports Composite and HDMI Video out Stereo audio out 8 GPIO pins Wired Ethernet

18

Page 19: MrRsPiManualGuide-KernelPanic

How to check what RPi.GPIO version you have

This works for all versions of RPi.GPIO

find /usr | grep ­i gpio

And the output will look something like this (although there will be more of it)…

You can see all those lines with 0.5.3a.egg­info telling me I have version 0.5.3a.

How to check your Raspberry Pi Revision number?

There’s a way to see what your Pi Revision is…cat /proc/cpuinfo

You can see this gives lots of info. Near the bottom is “Revision : 000f”This tells me I have a Rev 2 Pi, but it’s a bit clunky. There are several different rev. codes for different Pimodels and manufacturers (here’s a list of them). We could write some code to check the cpuinfo andextract the bit we want, compare it with known revision codes etc. But we don’t need any of that because,from RPi.GPIO 0.4.0a onwards (September 2012) we can use a built­in RPi.GPIO variable which does itall for us.

19

Page 21: MrRsPiManualGuide-KernelPanic

Backing up the Memorycard using the PI (working)http://learn.adafruit.com/adafruit­raspberry­pi­lesson­1­preparing­and­sd­card­for­your­raspberry­pi/make­a­backup­image

Use wget to get the file off pastebin.wget http://pastebin.com/raw.php?i=48fr9BAS

Then rename the file backup.shmv raw.php?i=<tab> rpi_clone.sh

If you're not sure that sda is the right card, you can run this command to list the cards connected to yourPi.

sudo fdisk ­l

The SD card slot with your running Pi system will show up as /dev/mmcblk0. Your blank card will belisted as /dev/sda1 (or possibly /dev/sdb1, if you have more than one USB card readers attached to thePi).

Note that you don't enter the '1' ­ if your card is listed as '/dev/sda1', then you would still enter 'sda' whenyou run the script ('sda' is the name of the card, 'sda1' is the name of the first partition on the card).

Ok, so now you should be ready to run the commandschmod +x rpi­clone.shsudo ./rpi_clone sda ­f

As noted earlier, the first parameter passed to the script is is the name of the target SD card, in this case'sda'. The ­f tells the script to entirely re­format the card.

The script will ask you if you're sure you want to initialize the destination card. Type 'y', and hit the returnkey.

I edited the scipt to make an mro­rpi­backup.sh (using nano), if you edit out the read commands carefullyyou can make the script run without intervention. That also means you can clone to multiple cards oneafter another .

do fdisk ­l (I found you had to have the card in the reader first, then connect to hub!) fdisk shoudl showyour disks. E.g. sda1, then sdb1 etc.You can then run using

sudo ./mro­rpi­backup.sh sdb ­f && sudo ./mro­rpi­backup.sh sda ­f

21

Page 22: MrRsPiManualGuide-KernelPanic

Setup Raspbian Memory Split and config.raspi­config

I would recommend a 256/256 split and you can comfortably overclock to 900 MHz (Medium) setting.

Update and Install updated packages!(First time you run these it might take a while, maybe an hour or so!)

sudo apt­get updatesudo apt­get upgrade ­ysudo apt­get install ­y git dialogsudo apt­get dist­upgrade

Or run both at once.sudo apt­get update && sudo apt­get dist­upgrade

Recommended Packages to Install (You’ll probably need them later!)

sudo apt­get update

sudo apt­get install usbmount espeak mpg321 ffmpeg imagemagick fbi sox samba samba­common­bin git­coretightvncserver geany espeak cups xboxdrv wminput wmgui jstest­gtk bluetooth bluez­utils bluez­compatbluez­hcidump libusb­dev libbluetooth­dev libsdl­dev joystick checkinstall pyqt4­dev­tools python­setuptoolspython­cwiid python­pip python­dev python­cwiid dialog motion flac ­ y

sudo reboot

RPi­update ­ FirmwareAn easier way to update the firmware of your Raspberry Pi. (not working at school, proxy issue?)

PreparationsYou need git installed to use this too. To install run:

sudo apt­get install git­core

InstallingTo install the tool, run the following command:

sudo wget http://goo.gl/1BOfJ ­O /usr/bin/rpi­update && sudo chmod +x /usr/bin/rpi­update

UpdatingThen, to update your firmware, just run the following command:

sudo rpi­update

22

Page 23: MrRsPiManualGuide-KernelPanic

GitHubs Worth Cloning Install the software to manage GITHUBS

sudo apt­get install git­core

Then clone the GIT using. (sometimes you have to remove the ‘s’ off the https to get access to the files!)git clone <git>

https://github.com/rpl/python­wiimote­hacks.git ­ WiiMote Hacks.https://github.com/brooksc/mcpipy.git ­ Minecraft Python Scripts.https://github.com/martinohanlon/minecraft­renderObj.git ­ Minecraft Objhttps://github.com/raspberrypi/quake3.git ­ Quake 3.https://github.com/chep/snes9x­rpi ­ Snes9x­rpihttps://github.com/peterlavelle/maplinarm ­ Maplin Robot Arm.https://github.com/walac/pyusb.git ­ Python USB Libs (needed for Robot Arm and Rocket Launcher!)https://github.com/petrockblog/RetroPie­Setup ­ RetroPie (Emulation Station!)https://github.com/dozencrows/motion ­ Motion for Use with the Pi Camera.

Backing up files to GDrive (Tested)http://raspberrywebserver.com/serveradmin/back­up­your­pi­to­your­google­drive.html#.UjkKbFhmu1s.twitter

The trouble with this is that it syncs with GDrive, i.e. not only will it upload to GDrive, but it willaslo LEECH down all your GDrive docs!

However this script could be useful for Zipping the entire content of the home directory for use later!!!

Save as Backup.shuse

cmod ­x Backup.sh

to make it executable.

#!/bin/bash

tar ­crvf backup_$(date +%y.%m.%d).tar /home/pi­­exclude="/home/pi/google_drive"gzip backup_$(date +%y.%m.%d).tarmv backup_$(date +%y.%m.%d).tar.gz ./google_drivecd ./google_drive./grivecd ..

23

Page 24: MrRsPiManualGuide-KernelPanic

PC Software to get familiar with 24All these apps have portable versions (so you don’t have to install anything, and can run from a memorystick!)

SSH ­ KitttySSH or PuttyThis will allow you to remotley connect to your Pi, all you have to know is the ipaddress of your pi(ifconfig), then try connecting to it. MEGA useful and will run on just about any system (there are portableversions kicking about too!). Note if SSH­ing from Linux (e.g. Live CD), just goto the terminal and use ‘sshpi:raspberry@<ipaddress>’ the computer should then try connecting, you might have to accept a key orsimilar and enter your password

WIN32ImagerYou will probably use this every once in a while to flash your cards when you screw them up, or find anew OS you wish to try out! Dead easy to run, just make sure you install the IMG file to the memory cardand not a HDD, many images come bundled with this in a Zip File! I discovered recently that thisprogram is also really good at producing LIVE USBs of Linux Distros, you download a Linux ISO, you’llhave to browse for the file (show all files) as it doesn’t list it, but then you an select the USB and it willproduce a working copy. Tested for both Ubuntu (various versions) and Linux Mint!

7ZipWell worth a mention as it let you Unzip, Uncompact, Uncompress just about anything including TARs.

Advanced IP ScannerIf you want to remote to your Pi and you don’t know the IP address as it’s setup with DHCP and notSTATIC IP address.

UltraVNC (Portable)At some point you might want to run your PI headless and yet still have access to X and all the wondersof the GUI (see guide later for setting up VNC), but this app is pretty good and free.

Geany / Ninja IDE. (versions available for both Windoze and PI!)If you’re coding in Python it’s probably a good place to start, a versatile IDE.

apt­get install ninja­ideapt­get install geany

WinSCPVery good for similar FTP for PI, great for getting files on / off a Pi Quickly!

24

Page 25: MrRsPiManualGuide-KernelPanic

Xming / Xming Portable (not got this working for me! :( )For this I use the portable version, which allows you to not install, run the Xming +putty.bat file. StartsXming (from the system tray start a new Putty session) ensure under SSH that X11 is selected (not gotthis to work yet!)

MobaXTerm ­ Works as well as VNCFree for personal use.

First, you will need to download and extract a copy of MobaXterm (as of 2/9/2013 the current version is 6.5). Once you have extracted the files, double click on MobaXterm_Personal_6.1Click on the Sessions button at the top of the window. Choose New Session. Choose SSH as the session type. In the Host field enter the IP address of your RasPi. Leave the port set to 22. You can also at this point enter the username that you will be using. Make sure that “X11­Forwarding” is checked. Choose “LXDE desktop” for the remote environment type. Click on OK at the bottom.Once you click on OK you will see an X11 window open on your desktop. You may have to move it out of the way to enter credentials into the SSH window. Once you enter credentials and choose whether or not you want to save your password you should then (after a couple of moments) see the desktop of your RasPi.NOTE: I am using the Raspian “wheezy” OS on my Raspberry Pi. However, the instructions above will most likely work for a majority of Linux distributions as long as XDMCP login is enabled.

25

Page 26: MrRsPiManualGuide-KernelPanic

Useful Linux Commands 26Command Args Usage.

chmod ­R 775 Sometimes files need their properties changing,read­only and suchlike. To sort that use

sudo chmod ­R 775 <filepath>+r=read , +w=write, +x=executable, ­R = recursive.

cd ~ ~ Takes you to your home dir.

ls ls / lsusb/ -l Lists, either files / folder / devices (lsusb good checking forusb devices) ­l will print out the file attributes too, e.g. write,executable etc.

mv <old> <new> Rename a file, mv <file1.ext> <newname.ext>

cp cp <current><new>

Copy the file from one location to another.

mkdir <foldername> Make a Directory within your current directory.

rm <filename> Delete / Remove a file (use the ­rf if trying to delete a folderwith contents of files!).

ifconfig ifconfig Get your current network info.

hcitool dev / scan Check for bluetooth devices and what’s happening.

nano <filename> Brings up simple text editor for you to mess with configfiles etc.

vi <filename> Brings up the VI editor, an alternative to Nano and showsline numbers.

less <xzy>| less You know when you run something and it scrolls 12 pagesof text up the screen, well the ‘LESS’ command lets youlook through it a page at a time! <press any key tocontinue>

apt­get install <package> choose some software to install.

apt­get purge <package> removes a package from your system! AND all it’ssettings / config etc.

apt­cachesearch

<keyword> You know you’ve just updated your packages list, well youcan search the cache!!! e.g. ‘apt­cache search chrom’, notyou may want to use ‘| less’

history history Gives you the previous commands typed at the BASH!You can run any of these commands using‘!<commandno>e.g. !333 would run command 333 from the list!

dmesg dmesg | grep ^<searchterm>

dmesg prints out all the messages from the kernel sincethe Pi was last powered ON!, this can be a lot. Using the

26

Page 27: MrRsPiManualGuide-KernelPanic

grep tool you can channel this text through it and thensearch it!

grep grep ^<term> search through whatever you trying to push through grep.

> <filename> Using this simple symbol you can dump the output fromthe bash straight into a specified file for looking at later!

wget <url> Great if you just awnat to grap a file or zip off the internet.

­help wget –help |less

Great for getting help on commands.

du du Gives you current disk usage, good for finding out howmuch space you have left (numbers in bytes I think!)

df df | less Shows you the size of folder on the PI, good for weedingout big programs / blockages etc.

­R chmod -R xyz ­R is used to mean recursive, meaning not just applied tothe file / folder, but all of it’s contents too!!!

ps ps | grep <xyz> Lists all the programs running on your pi. Use the Grep tofilter down the long list!!!

&& <c1> && <c2> Lets you run one command, wait for it to finish then run thesecond, eg. apt­get update && apt­get upgrado

& <c1> & Will allow you to run a command or program in thebackground and start something else! (run with the &)once running press enter and the command line will beyours again.

depmod depmod -a Sometimes you will be required to add drivers manuallyto Linux (often for wonky hardware!) these often comein the form of .ko files (when untar’d) The will oftenneed to be copied to the right folder e.g./lib/modules/3.6.11/kernel/drivers/... but then you needto update the OS to know you’ve put it there! That iswhat this command does, at least that’s what I think itdoes!

file file <xyz> informs you what format your file is.

cat cat [filename] |less .

Will just churn out the contents of a file to theprompt for quick viewing.

27

Page 28: MrRsPiManualGuide-KernelPanic

A note about the command prompt

When using the command prompt, the colours of headings mean different things.

Also by typing file <xyz> it will tell you what format the file is!

Installing Software / DriversMany times in this document you will come across apt­get which is one particular way of installingupdates to software and drivers... However there are alternative managers out there.

Aptitude (base on apt­get) will run in or outside of X.

Synaptic ­ A software visual installer designed to be used within X.

VI (Called using vi) a Basic Text Editor like NANO!

Edit a file, look at it, stop editing

Edit a file from command prompt vi <filename>

Edit a file from command promptfor reading only

vi -R <filename>

Edit a file from within vi :e <filename>

Edit a new file from within vi,discard changes to current file

:e! <filename>

Reload current file, discardingchanges

:e!

Go forwards a page Ctrl+F (or PgDn)

Go backwards a page Ctrl+B (or PgUp)

Move around single lines orcharacters

Arrow keys

Save changes :w

Save changes and overrideprotected (read-only) files

:w!

Save changes and exit vi ZZ

Quit :q

Quit and discard changes :q!

28

Page 29: MrRsPiManualGuide-KernelPanic

Get general help :help

Get help on a command (eg. :set) :help set

Using GREP Properly.

Grep is a very powerful tool. I can be used to find things with a file, a lot of files, or severaldirectories of files.

Basic syntaxgrep <something> <in file>e.g.

grep 'string' *.txt

Useful for finding the word string in all .txt files in a folder, but could be made better.

Additional Arguments­­color=auto = Makes it easy to read pretty colours!­R : Recursive (look at all the folders inside your folder too!)­i : ignore case, so will find all occurences of ‘string’ ‘STRING’ ‘String’ or variants.­n : Prefix each line of output with the 1­based line number within its input file.­H Print the file name for each match. This is the default when there is more than one file to search.

so... usinggrep ­­color=auto ­iRnH ‘string’ *.txt

Will return everything in all your folders (drilled down from current location), tell you the file it came from,the line number and be prettily coloured!

A nice simple guide with more examples here

29

Page 30: MrRsPiManualGuide-KernelPanic

SYSTEM 30

Setting a Static IP (network address)# Find out what address your router assigned to your RPi.

ifconfig

# Edit the network settings to use a STATIC IP address.# NOTE: To make it easy use the same settings your router assigned to your RPi.

sudo nano /etc/network/interfaces

# Comment out the DHCP entry. Make the STATIC entry look something like this:# NOTE: Tweak the address for your STATIC IP address.

auto eth0iface eth0 inet static

address 192.168.1.xxxnetmask 255.255.255.0broadcast 192.168.1.0network 192.168.1.255gateway 192.168.1.xxx

# Reboot the RPireboot

How to Change Your Raspberry Pi (or Other Linux Device’s) Hostname

The default hostname for the Raspberry Pi is, creatively enough, “raspberrypi“. What if you want adifferent hostname or you want to avoid hostname conflicts on your local network? Read on as we showyou how to quickly change the hostname of a Linux­based device.

Why Do I Want to Do This?There are two primary reasons why you would want to take a few minutes to edit the local hostname of aLinux device on your network. The most common reason would simply be customization–it’s fun topersonalize things. Rather than leave your Raspberry Pi music station as plain old “raspberrypi“, forexample, you could rename it to “jukebox“.The other reason you would want to customize the local host is to avoid name conflicts. If you, forexample, have purchased and set up three Raspberry Pi units, all three of them (assuming a defaultRaspbian installation) will attempt to claim the local hostname “raspberrypi“.

30

Page 31: MrRsPiManualGuide-KernelPanic

The first one will succeed and the next two will fail to resolve their hostnames, leaving them blank in yourrouter’s device list (as seen in the screenshot above) and unreachable via hostname­based protocols likeSamba file sharing.Fortunately it’s super simple, assuming you know where to perform a few quick edits, to change thehostname of your Raspberry Pi (and most other Linux­based devices you have full access to). Fordemonstration purposes we’ll be performing the change on a stock Raspbian installation, but the samefile edits will work on Debian, Ubuntu, and most other Linux platforms.

Changing the Host on your PiWe have so many Raspberry Pi units around the office that a bunch of them are now in conflict. Todaywe’re going to fix that by assigning unique names to each Pi unit based on their current function. A perfectcandidate for this renaming is our awesome Raspberry Pi weather station; it will be much easier toidentify it on the network once we change the hostname to “weatherstation“.The first step is to either open up the terminal on the device or to SSH into the device and open up aremote terminal. Our device is headless and currently running, so we’ll take the remote terminal routeand connect to it via SSH.At the terminal, type the following command to open the hosts file:

sudo nano /etc/hosts

Your hosts file will look like so:

Leave all of the entries alone except for the very last entry labeled 127.0.1.1 with the hostname“raspberrypi“. This is the only line you want to edit. Replace “raspberrypi” with whatever hostname youdesire. We replaced it on our device with “weatherstation“. Press CTRL+X to close the editor; agree tooverwrite the existing file and save it.Back at the terminal, type the following command to open the hostname file:

sudo nano /etc/hostname

This file only contains your current hostname:

31

Page 32: MrRsPiManualGuide-KernelPanic

Replace the default “raspberrypi” with the same hostname you put in the previous step (e.g.“weatherstation“). Again, press CTRL+X to close the editor, agree to overwrite the existing file and save it.Finally, we need to commit the changes to the system and reboot the system for the changes to takeeffect. At the terminal, enter the following command to commit the changes:

sudo /etc/init.d/hostname.sh

Follow that command with:

sudo reboot

Once the system comes back online, you can check the device list in your router to see if the newhostname has properly resolved:

Success! Now instead of wandering the network without a name, our little Raspberry Pi weather stationhas a hostname all its own.

Setting up Wi­Fi http://pingbin.com/2012/12/setup­wifi­raspberry­pi/

Setting up ad­hoc wifiTo actually be able to use wi­fi outdoors, I followed debian's documentation on setting up an ad­hocnetwork:RASPBERRY PIsudo nano /etc/network/interfaces:

auto wlan0iface wlan0 inet static

address 192.168.1.1netmask 255.255.255.0gateway 192.168.1.2wireless­channel 1wireless­essid MYNETWORKwireless­mode ad­hoc

32

Page 33: MrRsPiManualGuide-KernelPanic

On the linux laptop: use gnome network manager to connect to MYNETWORK, but set a manual IPaddress of 192.168.1.2, with a gateway of 192.168.1.1. Take note that ad­hoc is NOT supported in all oflinux wifi drivers. (Ralink 2500 does not support it, neither do most Realtek chips)

School Site Proxy Info (to remember)

Edit this file to set Permanently Across All Profiles.sudo nano /etc/apt/apt.conf

Add the following lines:Acquire::http::proxy “http://10.173.0.28:9090/”;Acquire::ftp::proxy “http://10.173.0.28:9090/”;Acquire::https::proxy “http://10.173.0.28:9090/”;

(if you copy and paste, check the “ go across properly!)save in Nano using ctrl+o, enter, then quit ctrl+x)

Allow programs other than Bash access to a (school) network under Proxy.In additoin to enable in things like Midori etc (not just the bash use this), is suspect Git Clone will not workwithout this addition too!

Edit the following file with NANO (N.B. I think this is needed to used git clone behind a proxy!)sudo nano /etc/bash.bashrc

add to the bottomexport http_proxy=http://10.173.0.28:9090/export https_proxy=http://10.173.0.28:9090/export ftp_proxy=http://10.173.0.28:9090/

Temporarily from the LXTerminal (not ideal and only works for ROOT!)

export http_proxy=http://10.173.0.28:9090export ftp_proxy=http://10.173.0.28:9090export https_proxy=http://10.173.0.28:9090

Use ifconfig to check on your Pi’s current network status and then try a sudo apt­get update to see if it canconnect and update!.

Changing the Font Size of the Terminal TextRun this command and then step through the menus. I can recommend ‘Terminus Font’16x12 makes it a bit easier to read! (thanks to Lloyd for this one!)

33

Page 34: MrRsPiManualGuide-KernelPanic

sudo dpkg­reconfigure console­setup

­ UTF­8­ Guess Optimal Character Set­ Choose Terminus­ 16x32

Choosing which programs run when the Pi boots

/etc/rc.local is a script on the Raspberry Pi which runs when Linux first boots. To edit it, you will need rootprivileges:

sudo nano /etc/rc.local

If you want to run one of your Python scripts at start­up, add this to the end of rc.local:

python <yourscriptname>.py

To stop a script running, either delete the line it is on, or comment it out (add a # at the beginning of theline).

34

Page 35: MrRsPiManualGuide-KernelPanic

Setting up VNC

VNC ­ http://myraspberrypiexperience.blogspot.co.uk/p/setting­up­vnc.htmlsudo apt­get install tightvncservervncserver :1 ­geometry 1280x800 ­depth 16 ­pixelformat rgb565

­ use Advanced IP Scanner to find the IP address (although is listed before you login!)­ Use SSH to run the VNC command.­ Use UltraVLC (set to ultramode with the IP followed by :1 (this is the connection number you setup)

Running VNCServer at Startuphttp://learn.adafruit.com/adafruit­raspberry­pi­lesson­7­remote­control­with­vnc/running­vncserver­at­startup

Step 1.Open a Terminal session on the Pi, or connect using SSH. A new terminal or SSH session willautomatically start you off in your home directory of /home/pi. If you are not in this directory, change to itby typing:

cd /home/piThen cd to the .config directory by typing:

cd .configNote the '.' at the start of the folder name. This makes it a hidden folder that will not show up when youtype 'ls'.

Step 2.Issue the command below to create a new directory inside .config called 'autostart'.

mkdir autostartcd into that new directory by typing:

cd autostart

Step 3.All that remains is to edit a new configuration file. So type the following command to open the nano editoron the new file:

nano tightvnc.desktopEdit the contents of the file with the following text.

[Desktop Entry]Type=ApplicationName=TightVNCExec=vncserver :1StartupNotify=false

Type ctrl­X and then Y to save the changes to the file.Thats all there is to it. The next time you reboot the VNC server will restart automatically.

35

Page 36: MrRsPiManualGuide-KernelPanic

Sound on the Pi. Sound on the Pi is a funny, funny thing. The ALSA support isn’t great, but it seems to work *sometimes*

Check Alsa & remove Pulse!First ensure the latest Alsa stuff is installed.sudo apt­get install alsa­tools alsa­utils mpg321sudo apt­get ­­purge remove pulseaudio

Test the sound usingsudo aplay /usr/share/sounds/alsa/Front_Center.wav

Force HDMI sound usingsudo amixer cset numid=3 <n>

where n=2 HDMI, n=1 Headphones, n=0 AUTO!

Making the Pi Speak It is possible to make the Pi speak to you (think MS Voice) Simply install espeak

sudo apt­get updatesudo apt­get install espeak

the call the command usingespeak “Hello World”

You can find more info about using espeak, the various voices etc here.

There are other more complicated programs you can use e.g. Festival (reasons why are listed here ­http://www.element14.com/community/blogs/mirandasoft/2013/04/13/raspberry­pi­project­dedicated­speech­synthesizer­without­gui

SOX ­ The Swiss Knife of WAV / Raw audio on Linuxsudo apt­get install sox.This program will allow you to convert / trim chop etc WAV or RAW audio files.I found this useful in the PiRateRadio project listed later where I needed to convert audio to 22050 andsingle (mono) channel for broadcasting over the FM!

36

Page 37: MrRsPiManualGuide-KernelPanic

sox <input file> ­r 22050 <output file>

or you could import sound from espeak (see above) then PIPE this into sox

sudo espeak ­­stdout “Stick anything in here” | sox ­t wav ­ ­r 22050 test.wav channel 1

The sox tool needs to know what it is receiving, hence the ‘­t wav’, the next innoculous ‘­’ is actually theinput from the PIPE, ‘­r 22050’ resamples the audio.further instuctions can be found here ­ http://billposer.org/Linguistics/Computation/SoxTutorial.html

imporing sound from a micsox ­t alsa hw:1,0 ­r 22050 testmic.wav silence 1 0 0.5% ­1 1.0 1% &

MPG321This handy tool lets you convert MP3s into WAVs for use with programs like SOX

sudo apt­get install mpg321sudo mpg321 ­w <output file> <input file>

I don’t know why the arguments seem backwards!

37

Page 38: MrRsPiManualGuide-KernelPanic

Turning your Raspberry Pi into an FM Transmitterhttp://www.daveconroy.com/how­to­turn­your­raspberry­pi­into­a­fm­transmitter/

Grab the codewget http://www.daveconroy.com/SampleCode/Pifm.tar.gztar ­zxvf Pifm.tar.gz

Attach the AntennaeFind an 8 inch piece of plain wire, and attach it to the GPIO4port on your Pi. Technically the is step is optional, but mytransmission range went from 200ft to 8 inches without it.Use the picture below as a reference.

At school this made a difference of edge of myroom to the entire building!!!!

Step 3 – Run the Code

Usage: sudo ./pifm wavfile.wav [freq] [sample rate]

The second command line argument is thefrequency to transmit on, as a number in Mhz. Forexample, this will transmit on 100.1 FM

sudo ./pifm sound.wav 100.1

You can use whatever frequency you'd like (88­>108).

If you’re making your woen audio to bew palyed back out of theis, then you need to use 22050 sampling,and make it mono. I’m not sure if that’s limitation of the pifm program? But a quick convert using SOXwill do the job!

sox <input file> ­r 22050 <output file>Or if you want to play back an mp3… then mpg321 then pipe into Sox.

sudo mpg321 ­w <output file> <input file>

sudo mpg321 ­s <input file> | sox ­ ­r 22050 <output file>sudo ./pifm <outfputfile> 101

Writing a Script to Monitor Mic Input

while [ true ]do #espeak ­­stdout "test 1234567890"|sox ­t wav ­ ­r 22050 test3.wav && ./pif$ #espeak ­­stdout "this is just another test to see if this little program w$ sudo sox ­t alsa hw:1,0 ­r 22050 testmic.wav silence 1 0 0.5% ­1 1.0 1% & ./pifm testmic.wav 101# rm testmic.wav

38

Page 39: MrRsPiManualGuide-KernelPanic

done

A Better Live Mic Solutionhttp://www.raspberrypi.org/phpBB3/viewtopic.php?t=33526

arecord ­fS16_LE ­r 22050 ­Dplughw:1,0 ­ | sudo ./pifm ­ 101 22050

Alright so:arecord

Program we are using to record audio.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

­fS16_LE

Output 16­bit data. Needed this way for PiFM to read it.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

­r 22050

This specifies sampling rate to output recording. 22,050 is a good balance for speed and quality.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

­Dplughw:1,0

This is where you may need to modify. The '1' specifies card number and '0' is the device number I think. To find thisout for your device, use

arecord ­l

to see all of the audio devices connected.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

­

Here it means to print output to standard out.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

|

Pipe the standard out from previous command to next command's standard input.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

sudo ./pifm ­ 100.1 22050

This is explained in the link at the top. '­' means use standard input for "file"(Remember we piped it). '100.1' is thefrequency in Mhz to transmit and '22050' is the sampling rate of the input. Actually if you change the sampling ratelower it will output a low pitch sound and higher will do a high pitch sound, kind of a voice changer.

39

Page 40: MrRsPiManualGuide-KernelPanic

Voice Recognition on the Pi using Google Voice API

http://blog.oscarliang.net/raspberry­pi­voice­recognition­works­like­siri/

sudo apt­get install ffmpeg

Create a script called Speech2text.sh

And to make it executable.

chmod +x speech2text.sh

To run it

./speech2text.sh

#!/bin/bash

echo "Recording... Press Ctrl+C to Stop."arecord ­D "plughw:1,0" ­q ­f cd ­t wav | ffmpeg ­loglevelpanic ­y ­i ­ ­ar 16000 ­acodec flac file.flac > /dev/null 2>&1

echo "Processing..."wget ­q ­U "Mozilla/5.0" ­­post­file file.flac ­­header"Content­Type: audio/x­flac; rate=16000" ­O ­"http://www.google.com/speech­api/v1/recognize?lang=en­us&client=chromium" | cut ­d\" ­f12 >stt.txt

echo ­n "You Said: "cat stt.txt

rm file.flac > /dev/null 2>&1

Asking Wolfram Alpha Questions

wget https://pypi.python.org/packages/source/w/wolframalpha/wolframalpha­1.0.2.zip

unzip wolframalpha­1.0.2.zip

sudo apt­get install python­setuptools easy_install pip

sudo python setup.py build

sudo python setup.py install

Getting the APP_IDTo get a unique Wolfram Alpha AppID, signup here for a Wolfram Alpha Application ID.

You should now be signed in to the Wolfram Alpha Developer Portal and, on the My Apps tab, clickthe “Get an AppID” button and fill out the “Get a New AppID” form. Use any Application name anddescription you like. Click the “Get AppID” button.

40

Page 41: MrRsPiManualGuide-KernelPanic

41

Page 42: MrRsPiManualGuide-KernelPanic

Save as queryprocess.pyYou may have to chmod 775 it.

#!/usr/bin/python

import wolframalphaimport sys

# Get a free API key here http://products.wolframalpha.com/api/# This is a fake ID, go and get your own, instructions on my blog.app_id='6GG85Y­HGPWRKTG2L'

client = wolframalpha.Client(app_id)

query = ' '.join(sys.argv[1:])res = client.query(query)

if len(res.pods) > 0: texts = "" pod = res.pods[1] if pod.text: texts = pod.text else: texts = "I have no answer for that" # to skip ascii character in case of error texts = texts.encode('ascii', 'ignore') print textselse: print "Sorry, I am not sure."

test the script using

sudo ./queryprocess.py “What is the capital city of Germany”

Text To SpeechFrom the processed query, we are returned with an answer in text format. What we need to do nowis turning the text to audio speech. There are a few options available like Cepstral or Festival, but Ichose Google’s speech service due to its excellent quality. Here is a good introductions of thesesoftware mentioned.

First of all, to play audio we need to install mplayer:sudo apt­get install mplayer

We have this simple bash script. It downloads the MP3 file via the URL and plays it. Copy and call it

text2speech.sh #!/bin/bashsay() local IFS=+;/usr/bin/mplayer ­ao alsa­really­quiet ­noconsolecontrols"http://translate.google.com/translate_tts?tl=en&q=$*"; say $*

42

Page 43: MrRsPiManualGuide-KernelPanic

And to make it executable.sudo chmod +x text2speech.sh

To test it, you can try./text2speech.sh "My name is Oscar and I am testing the audio."

If it errors trysudo nano /etc/mplayer/mplayer.conf

And put in the line at the end:

nolirc=yes

Extended script for longer pieces of text.Save over the top of text2speech.sh

#!/bin/bash

INPUT=$*STRINGNUM=0ary=($INPUT)for key in "$!ary[@]"doSHORTTMP[$STRINGNUM]="$SHORTTMP[$STRINGNUM]$ary[$key]"LENGTH=$(echo $#SHORTTMP[$STRINGNUM])

if [[ "$LENGTH" ­lt "100" ]]; then

SHORT[$STRINGNUM]=$SHORTTMP[$STRINGNUM]elseSTRINGNUM=$(($STRINGNUM+1))SHORTTMP[$STRINGNUM]="$ary[$key]"SHORT[$STRINGNUM]="$ary[$key]"fidonefor key in "$!SHORT[@]"dosay() local IFS=+;/usr/bin/mplayer ­ao alsa ­really­quiet­noconsolecontrols"http://translate.google.com/translate_tts?tl=en&q=$SHORT[$key]"; say $*done

Combining Speech to Text and Text to Speech.

Save the script as main.sh

#!/bin/bash

echo "Recording... Press Ctrl+C to Stop."

./speech2text.sh

QUESTION=$(cat stt.txt)echo "Me: ", $QUESTION

ANSWER=$(python queryprocess.py $QUESTION)echo "Robot: ", $ANSWER

./text2speech.sh $ANSWER

43

Page 44: MrRsPiManualGuide-KernelPanic

sudo chmod 775 text2speech.sh

./main.sh

Alternative Google Voice Settings / Script

http://www.daveconroy.com/turn­raspberry­pi­translator­speech­recognition­playback­60­languages/

echo "Recording your Speech (Ctrl+C to Transcribe)"arecord ­D plughw:0,0 ­q ­f cd ­t wav ­d 0 ­r 16000 | flac ­ ­f ­­best ­­sample­rate 16000 ­s ­o daveconroy.flac;

echo "Converting Speech to Text..."wget ­q ­U "Mozilla/5.0" ­­post­file daveconroy.flac ­­header "Content­Type: audio/x­flac; rate=16000" ­O ­"http://www.google.com/speech­api/v1/recognize?lang=en­us&client=chromium" | cut ­d\" ­f12 > stt.txt

echo "You Said:"value=`cat stt.txt`echo "$value"

Microsoft Translation and Google Text to SpeechNow that we can record our voice and convert it into text, we need to translate it to our desired foreign language. I would loveto be able to use Google’s Translate tool for this, but unfortunately there is a20$ sign up fee for use of this API. I plan onpurchasing this for myself, but I wanted to make this project free so every one had an opportunity to try it.As an alternative, we will be using Microsoft’s translate service which currently is still free for public use. The list of supportedlanguages and their corresponding codes can be found here. In our previous example we used a simple shell script, but forthe translation and playback process – I’ve written a more powerful python script.All of this code can be found on my github repository (contributions welcome!).Lets first create the file:

sudo nano PiTranslate.pyand add the following contents

44

Page 45: MrRsPiManualGuide-KernelPanic

import jsonimport requestsimport urllibimport subprocessimport argparse

parser = argparse.ArgumentParser(description='This is a demo script by DaveConroy.com.')parser.add_argument('­o','­­origin_language', help='Origin Language',required=True)parser.add_argument('­d','­­destination_language', help='Destination Language', required=True)parser.add_argument('­t','­­text_to_translate', help='Text to Translate', required=True)args = parser.parse_args()

## show values ##print ("Origin: %s" % args.origin_language )print ("Destination: %s" % args.destination_language )print ("Text: %s" % args.text_to_translate )

text = args.text_to_translateorigin_language=args.origin_languagedestination_language=args.destination_language

def speakOriginText(phrase): googleSpeechURL = "http://translate.google.com/translate_tts?tl="+ origin_language +"&q=" + phrase subprocess.call(["mplayer",googleSpeechURL], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

def speakDestinationText(phrase): googleSpeechURL = "http://translate.google.com/translate_tts?tl=" + destination_language +"&q=" + phrase print googleSpeechURL subprocess.call(["mplayer",googleSpeechURL], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

args = 'client_id': '',#your client id here 'client_secret': '',#your azure secret here 'scope': 'http://api.microsofttranslator.com', 'grant_type': 'client_credentials'

oauth_url = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2­13'oauth_junk = json.loads(requests.post(oauth_url,data=urllib.urlencode(args)).content)translation_args = 'text': text, 'to': destination_language, 'from': origin_language

headers='Authorization': 'Bearer '+oauth_junk['access_token']translation_url = 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate?'translation_result = requests.get(translation_url+urllib.urlencode(translation_args),headers=headers)translation=translation_result.text[2:­1]

speakOriginText('Translating ' + translation_args["text"])speakDestinationText(translation)

45

Page 46: MrRsPiManualGuide-KernelPanic

For the script to run we need to import a few python libraries and a media player.

sudo apt­get install python­pip mplayer

sudo pip install requests

The last thing we need to do before we can run the script is sign up for a Microsoft Azure Marketplace API key. To do so,

simply visit the marketplace, register an application, and then enter your client id and secret passcode into the script above.

Now we can run the script:

sudo python PiTranslate.py ­o en ­d es ­t "hello my name is david conroy"

The script has 3 required inputs:

­o orignation language

­d destination language

­t “text to translate”

Putting it all TogetherIt is actually very easy to combine the two scripts we created in this tutorial. In fact, it only takes one line of code to be added to

the bottom of stt.sh shell script we created earlier (assuming PiTranslate.py and stt.sh are in the same directory).

sudo nano stt.sh

python PiTranslate.py ­o en ­d es ­t "$value"

For those of you who skipped around in this tutorial, here is the entire script again with that line added:

echo "Recording your Speech (Ctrl+C to Transcribe)"arecord ­D plughw:0,0 ­f cd ­t wav ­d 0 ­q ­r 16000 | flac ­ ­s ­f ­­best ­­sample­rate 16000 ­o daveconroy.flac;

echo "Converting Speech to Text..."wget ­q ­U "Mozilla/5.0" ­­post­file daveconroy.flac ­­header "Content­Type: audio/x­flac; rate=16000" ­O ­"http://www.google.com/speech­api/v1/recognize?lang=en­us&client=chromium" | cut ­d\" ­f12 > stt.txt

echo "You Said:"value=`cat stt.txt`echo "$value"

#translate from English to Spanish and play over speakerspython PiTranslate.py ­o en ­d es ­t "$value"

Now, run the Speech To Text script again, and it will translate it from English to Spanish by default.

./stt.sh

Both the origin and destination languages have to be supported by Microsoft Translate and Google Translate in order for this

script to work.

Language Codes:

Microsoft

Google

46

Page 47: MrRsPiManualGuide-KernelPanic

Mounting a USB the Easy Way! Install a little app called USBMount,

sudo apt­get install usbmount

The USB HDD or Pendrive should then appear as /media/usb[num] starting from zero.

Type ‘df’ to find the exact path.

...Or the hard way

http://elinux.org/RPi_Adding_USB_Drives

Printing on a Pi.

GuideFirst install CUPS ­ Linux Print Drivers

sudo apt­get install cups

Add the Pi user to the lpadmin group (for administrating printers!)

sudo usermod ­a ­G lpadmin pi

Use an internet browser to browse tohttp://127.0.0.1:631

You will be prompted for a username and password ­ enter your normal pi username and password

Setting up an AirServer (for Printing) ­ See Here

N.B. When I did this the print margins were all to cock, might be worth checking this.

Making a Program LOOP FOREVEROn the Raspberry Pi master just create a simple bash script (you could save it as "forever") ...

47

Page 48: MrRsPiManualGuide-KernelPanic

while truedo #Put anything you like in here!!!! #avconv ­re ­i movie.avi ­vcodec copy ­an ­f avi udp://239.0.1.23:1234done

Don't forget to either make the script executable or run it by prepending the name of the bash script with sh, eg "shforever".

Making a program repeat every so often (CRON Jobs!) CRON is a very cool way of making a process, program, or script run at set times. The Pi comes setupwith no CRON task running, however you can edit what you want it to do on a regular basis using

sudo crontab ­eIt is very important to ensure the sudo command is used!Once you are in the file you can then add the following line, just change the directory to point to whereyour file is saved. (this example is set to repeat every 60 minutes, it then runs the command ‘python<path of script>)

*/60 * * * * python /home/pi/twitter/TweetTemp.py

The Cron job takes the form of.1 2 3 4 5 /root/backup.sh

Where, 1: Minute (0­59) 2: Hours (0­23) 3: Day (0­31) 4: Month (0­12 [12 == December]) 5: Day of the week(0­7 [7 or 0 == sunday]) /path/to/command ­ Script or command name to schedule

48

Page 49: MrRsPiManualGuide-KernelPanic

HARDWARE 45

Cases

Sometimes you’ll want to put your Pi in a case.For schools try something like the

http://www.skpang.co.uk/catalog/cover­with­breadboard­area­for­raspberry­pi­large­p­1101.htmlwhich is clear and has space / includedbreadboard if you’re going to do some electronics.

or the Pi Bow is very popular and makes it easy toget to your Pi!http://shop.pimoroni.com/ (they now do a coupleof addons if you have the camera module!) Iprefer TOXIC to rainbow!

or if you have plenty of lego then build your own,full PDF instructions here! ­https://sites.google.com/a/mandell.org/raspberrypi/pimacYou don’t have to be too careful, use what you’vegot, it just gives you a rough idea!

49

Page 50: MrRsPiManualGuide-KernelPanic

For media centres I like just plain black!

50

Page 52: MrRsPiManualGuide-KernelPanic

Connecting a Pi to the outside world

For this I recommend using a Pi Cobbler Kit and a breadboard, bell (single strand) wire. Some gummiesweet! (tested with JellyBabies!)

PIN BasicsFirst thing is first, there are ton of ways to connect up a Pi to breadboards etc. I would recommend usinga Cobbler Kit or similar. When addressing GPIOs in the later scripts you are not addressing the PINnumber, but you’re using these pinouts. (GPIO.BOARD) the first diagram or GPIO.

More here ­ http://elinux.org/RPi_Low­level_peripherals

52

Page 53: MrRsPiManualGuide-KernelPanic

Making an LED FlashTo make a single simple LED Flash, you wire a resistor to +3.3v (pin 1), then connect the resistor to theLED (curved side), then connect the flat side to whichever pin you want to use GPIO7 is an easy one.This is the 7th Pin as they go 1,2 along the top, 3,4 then 5,6 then 7. The only WEIRD bit is that you’returning the LED ON when you set this pin to FALSE (0)

This python script should do it.

from time import sleepimport RPi.GPIO as GPIOGPIO.setmode(GPIO.BOARD)#Set your pins as either inputs or outputs! (IN or OUT)GPIO.setup(11, GPIO.OUT)while 1:

#Turn the LED ON!GPIO.output(11, False)sleep(1)#Turn the LED OFF!GPIO.output(11, True)sleep(1)

Now try creating a three coloured LED setup.

53

Page 54: MrRsPiManualGuide-KernelPanic

LedBORG ­ http://www.piborg.org/ledborg

Rev 2, 2013-09-10 or 3.6.11+ build #538

mkdir ~/ledborg­setupcd ~/ledborg­setupwget ­O setup.ziphttp://www.piborg.org/downloads/ledborg/raspbian­2013­09­10­rev2.zipunzip setup.zipchmod +x install.sh./install.sh

Usage

Colour optionsThe colours on an LedBorg are set as levels of red, green and blue; referred to as RGB

The available levels are:

0 ­> Means channel is off 1 ­> Means channel is at 50% 2 ­> Means channel is at 100%

For example:

RGB of 200 means that red is on full, green is off and blue is off, producing REDRGB of 210 means that red is on full, green is on half and blue is off, producing ORANGERGB of 202 means that red is on full, green is off and blue is on full, producing MAGENTARGB of 021 means that red is off, green is on full and blue is on half, producing SPRING GREENRGB of 222 means that red is on full, green is on full and blue is on full, producing WHITERGB of 000 means that red is off, green is off and blue is off, since all are off this turns LedBorg off (pseudo black)All colours against numbers:

100 200 211 110 220 221 000 111 222

010 020 121 011 022 122 120 021 210

001 002 112 101 202 212 012 102 201

For tables with names and HTML codes see here

Controlling LedBorg

To set the colour from the GUI:

Find the GUI icon on the desktop where it will be called LedBorg with a PiBorg logoAlternatively it can be found by browsing to /home/pi where it will be called ledborg_guiRun the GUI by double­clicking on itIf a dialog box appears asking you what to do select ExecuteClick on a box to change to the colour it showsYou can click on Demo Mode to run example sequences, including turning LedBorg into a CPU usage meter!

54

Page 55: MrRsPiManualGuide-KernelPanic

To set the colour from a Python script:LedBorg = open('/dev/ledborg', 'w')LedBorg.write('RGB')del LedBorgreplacing RGB with the desired levels (see above)

To set the colour from a terminal type:echo "RGB" > /dev/ledborgreplacing RGB with the desired levels (see above)

To set the colour from a terminal with the basic driver type:~/ledborg­basic RGBreplacing RGB with the desired levels (see above), note that 50% options are not available to the basic driver and100% will be used instead (only 8 colours including off)

To disable LedBorg from a terminal type:sudo /etc/init.d/ledborg.sh stopNote that this will free the GPIO pins for use, but will not affect if the LedBorg driver is started at boot time

To enable LedBorg from a terminal type:sudo /etc/init.d/ledborg.sh startNote that this will start using the GPIO pins, but will not affect if the LedBorg driver is started at boot time

Managing boot optionsTo set the boot­up colour from a terminal type:echo "RGB" > /home/pi/ledborg_bootcolourreplacing RGB with the desired levels (see above)To stop LedBorg from auto­loading from a terminal type:sudo update­rc.d ledborg.sh removeNote that this will stop LedBorg using the GPIO pins during boot, however the enable LedBorg instructions above willbe need to be used before trying to set a colourTo enable LedBorg auto­loading from a terminal type:sudo update­rc.d ledborg.sh defaults 100Note that this will start using the GPIO pins during boot, loading the colour specified by /home/pi/ledborg_bootcolour

55

Page 56: MrRsPiManualGuide-KernelPanic

Singing / Screaming Jelly Baby (Probably works with Fruit Pastels too!)http://www.ocr.org.uk/Images/125881­recipe­card­singing­jelly­baby.pdfOnce connected, strip a pair of decent length wires and connect to pins 3 and 25. Strip the other end ofthe wires (about 2 cm) and stick into the Jelly Baby to make the switch. The guide suggests youdownload mpg321 and an MP3, this was blocked at school, so I just got it to write whatever messagethey liked on the end. I also found the 1 second time delay was FAR too long. Set to a tenth of the timefor more accuracy!

wget https://github.com/Rob­Bishop/RaspberryPiRecipes/raw/master/la.mp3

Original Script Revised Script

# First we need to import the libraries that# we need# Import the time library so that we can make# the program pause for a fixed amount of timeimport time# Import the Raspberry Pi GPIO libraries that# allow us to connect the Raspberry Pi to# other physical devices via the General# Purpose Input­Output (GPIO) pinsimport RPi.GPIO as GPIO# Import the os library so that we can make# our program call other programs that run on# the Raspberry Piimport os# Now we need to set­up the General Purpose# Input­Ouput (GPIO) pins# Clear the current set­up so that we can# start from scratchGPIO.cleanup()# Set up the GPIO library to# use Raspberry Pi board pin# numbersGPIO.setmode(GPIO.BOARD)# Set pin 3 on the GPIO header to be an inputGPIO.setup(3,GPIO.IN)# This loop runs forever and plays the mp3# file when the two wires are touchingwhile True:

# Check to see if pin 3 on the GPIO# header is connected to the ground pinif GPIO.input(3) == False:

# If it’s connected to ground# then play the mp3 fileos.system(‘mpg321 la.mp3 &’)

# Wait for a second before repeating# the loop time.sleep(1)

import timeimport RPi.GPIO as GPIOimport osGPIO.cleanup()GPIO.setmode(GPIO.BOARD)# Set pin 3 on the GPIO header to be an inputGPIO.setup(3,GPIO.IN)while True: if GPIO.input(3) == False: #os.system(‘mpg321 la.mp3 &’) print ‘Ouch! Stop it!’ time.sleep(0.1)

56

Page 57: MrRsPiManualGuide-KernelPanic

It’s worth noting though that the commandos.system(‘<something>’)

Allows you to run any command or program you can from the terminal (we launched quake3)os.system(‘./quake3/ioquake3.arm’)

If you do want to get the MP3 working, you might have to force the sound through the headphone socket.

Also on one Pi I thought the GPIO Python libraries weren’t installed, however in hindsight I think this mayhave been a typo that caused it, not as it was actually missing. However just in case you can always usean

apt­cache search GPIO

I believe the python library is called Python­GPIO or similar (use the search!). Just do an

apt­get install

using the result you found!.

Make sound playback through the headphone socketBy default the output is set to automatically select the interface (HDMI if available otherwise analog). You can force itto use a specific interface using :sudo amixer cset numid=3 <n>

Where <n> is the required interface : 0=auto, 1=analog, 2=hdmi. To force the Raspberry Pi to use the analog output :

sudo amixer cset numid=3 1

You will need to run the modprobe command again when your Pi is rebooted/restarted.Playing A WAV FileIn order to play a WAV file we need a file to play. Type the following command to download a test WAV file :sudo wget http://www.freespecialeffects.co.uk/soundfx/sirens/police_s.wavNow we can play it :

sudo aplay police_s.wavsudo alsamixer

#Check Audio Volume.

57

Page 58: MrRsPiManualGuide-KernelPanic

Pi Camera ModuleInitial installation and setup.http://www.youtube.com/watch?feature=player_embedded&v=GImeVqHQzsEhttp://www.linuxuser.co.uk/tutorials/pi­camera­quick­installation­guide

How to use the Raspberry Pi camera softwareraspivid is a command line application that allows you to capture video with the camera module, while the applicationraspistill allows you to capture images.

­o or –output specifies the output filename and ­t or –timeout specifies the amount of time that the preview will bedisplayed in milliseconds. Note that this set to 5s by default and that raspistill will capture the final frame of thepreview period.

­d or –demo runs the demo mode that will cycle through the various image effects that are available.

Example commandsCapture an image in jpeg format:

raspistill ­o image.jpg

To quickly view the image from the command prompt install fbi and use the simple commandsudo apt­get install fbifbi image.jpg

This will display the image on the screen and you will be able to use the + and ­ keys to zoom in and out.

Capture a 5s video in h264 format:raspivid ­o video.h264

Capture a 10s video:raspivid ­o video.h264 ­t 10000

Capture a 10s video in demo mode:raspivid ­o video.h264 ­t 10000 ­d

To see a list of possible options for running raspivid or raspistill, you can run:raspivid | lessraspistill | less

Use the arrow keys to scroll and type q to exit.

To shoot video with the Raspberry Pi CameraFrom the command line, type…

raspivid ­o filename.h264 ­t 20000

…where filename is a file name of your choice.

This will store the output .h264 stream in a file called “filename.h264″ and will stop recording after 20000milliseconds (20s). (It defaults to 1080p @ 30 frames per second).

58

Page 59: MrRsPiManualGuide-KernelPanic

There are a couple of other useful little options you might want to know about. By default, the image isflipped vertically, meaning you see a mirror image of what you filmed.

Depending on which way round you hold the camera, you might want to flip it either horizontally, verticallyor both. You can do that by adding ­vf and/or ­hf to the command, like this…

raspivid ­o filename.h264 ­t 20000 ­vf ­hf orraspivid ­o filename.h264 ­t 20000 ­vf orraspivid ­o filename.h264 ­t 20000 ­hf

59

Page 60: MrRsPiManualGuide-KernelPanic

Berrycam Photos (Tested)http://www.fotosyn.com/berrycam­support/?app

Save all thisasBerrycam.py

then runusing

sudo pythonberrycam.py &

so it runs inthebackground.

#!/usr/bin/env python## BerryCam.py# BerryCam ­ Raspberry Pi Camera Controller for use with iOS devices## Created by James Moore on 22/05/2013.# Copyright (c) 2013 Fotosyn. All rights reserved.## Raspberry Pi is a trademark of the Raspberry Pi Foundation.# IOS is a trademark or registered trademark of Cisco in the U.S. and other countries and is used by Apple Inc.under license.

import SimpleHTTPServer, SocketServerimport urlparseimport os

PORT = 8000 # CHange this if you wish to listen on a different port

class BerryCamHandler (SimpleHTTPServer.SimpleHTTPRequestHandler):

def do_GET(self):

# Parse query data parsedParams = urlparse.urlparse(self.path) queryParsed = urlparse.parse_qs(parsedParams.query)

# Add 'berrycam' prefix to URL to perform query if parsedParams.path == "/berrycam":

awb = "'" + queryParsed['awb'][0] + "'" # Set AWB mode mm = "'" + queryParsed['mm'][0] + "'" # Set metering mode ev = queryParsed['ev'][0] # Set EV compensation ex = "'" + queryParsed['ex'][0] + "'" # Set exposure mode sh = queryParsed['sh'][0] # Set image sharpness br = queryParsed['br'][0] # Set image brightness co = queryParsed['co'][0] # Set image contrast sa = queryParsed['sa'][0] # Set image saturation #iso = queryParsed['iso'][0] # Set capture ISO ­ NOT YET IMPLEMENTED ifx = "'" + queryParsed['ifx'][0] + "'" # Set image effect #cfx = "'" + queryParsed['cfx'][0] + "'" # Set colour effect ­ NOT YET IMPLEMENTED IN BERRYCAM #rot = queryParsed['rot'][0] # Set image rotation ­ NOT YET IMPLEMENTED IN BERRYCAM filequality = queryParsed['fquality'][0] filewidth = queryParsed['fwidth'][0] fileheight = queryParsed['fheight'][0] filefolder = queryParsed['ffolder'][0] fileseq = queryParsed['fseq'][0] hflip = queryParsed['hf'][0] #exifmake = queryParsed['exifmake'][0]

#filewidth = 2592 #­ ((2592/4)*filesize) # Take the values passed, divide by 4 and multiply to get new size #fileheight = 1944 #­ ((1944/4)*filesize) # Take the values passed, divide by 4 and multiply to get new size

#Exposure mode options : #off,auto,night,nightpreview,backlight,spotlight,sports,snow,beach,verylong,fixedfps,antishake,fireworks

#AWB mode options : #off,auto,sun,cloud,shade,tungsten,fluorescent,incandescent,flash,horizon

#Image Effect mode options :

#none,negative,solarise,sketch,denoise,emboss,oilpaint,hatch,gpen,pastel,watercolour,film,blur,saturation,colourswap,washedout,posterise,colourpoint,colourbalance,cartoon

#Metering Mode options : #average,spot,backlit,matrix

directory = 'berrycam/' + str(filefolder) if not os.path.exists(directory): os.makedirs(directory)

60

Page 61: MrRsPiManualGuide-KernelPanic

# Build up a raspistill command line string command = "raspistill ­v" # Initiate command for Raspicam command += " ­awb " + str(awb) # Define WB command += " ­mm " + str(mm) # Define Metering Mode command += " ­ev " + str(ev) # Define the Exposure Adjustment command += " ­ex " + str(ex) # Define Exposure Mode command += " ­sh " + str(sh) # Define Image Sharpness command += " ­br " + str(br) # Define Image Brightness command += " ­co " + str(co) # Define Image Contrast command += " ­sa " + str(sa) # Define Image Saturation #command += " ­ISO " + str(iso) # Define Image ISO ­ NOT YET IMPLEMENTED command += " ­ifx " + str(ifx) # Define Image Effect #command += " ­cfx " + str(cfx) # Define Colour Effect ­ NOT YET IMPLEMENTED IN BERRYCAM #command += " ­rot " + str(rot) # Define Image Rotation ­ NOT YET IMPLEMENTED IN BERRYCAM command += " ­q " + str(filequality) # Define Image Quality command += " ­w " + str(filewidth) # Define output image width command += " ­h " + str(fileheight) # Define output image height #command += " ­o /berrycam/" + str(filefolder) + "/IMG­" + str(fileseq) +".jpg" command += " ­o berrycam/" + str(filefolder) + "/IMG­" + str(fileseq) +".jpg" #command += " ­x IFD1.Make=" + str(exifmake) #Define Make for ESIF Data 'Raspberry Pi'

if hflip == "1": command += " ­hf " else: command += ""

os.system(command) self.processRequest(queryParsed)

else: # Default to serve up a local file SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self);

def processRequest(self, query):

self.send_response(200)

httpd = SocketServer.TCPServer(("", PORT), BerryCamHandler)

print "B E R R Y C A M ­­ Listening on port", PORTprint "Please ensure your BerryCam App is installed and running on your iOS Device"

httpd.serve_forever()

61

Page 62: MrRsPiManualGuide-KernelPanic

Time Lapse PhotosAnother great feature of the utility is the easy capture of a series of images over a specifiedperiod of time. You could write your own software to do this but for speed you can’t beat thetime lapse options provided :

raspistill ­o myimage_%d.jpg ­tl 2000 ­t 25000The ­tl option sets the time between photos (in milliseconds) and the ­t option sets the total timethe sequence will last. So in this example a photo will be taken every two seconds (2000ms) for atotal time of twenty five seconds (25000ms).

In this example we take a photo every minute (60000 milliseconds) for a total time of 2 hours (2 x60 x 60 x 1000 milliseconds) :

raspistill ­o myimage_%d.jpg ­tl 60000 ­t 7200000The “%d” results in a sequence of numbered images being produced. In this case you would getimages named :

myimage_1.jpgmyimage_2.jpgmyimage_3.jpgmyimage_4.jpg...If you change the “%d” to “%04d” you can pad the numbers with zeroes to always give fourdigits. I much prefer this as it gives you a sequence that looks like :

myimage_0001.jpgmyimage_0002.jpgmyimage_0003.jpgmyimage_0004.jpg...

Time Lapse Video from Stills.http://www.raspberrypi­spy.co.uk/2013/05/creating­timelapse­videos­with­the­raspberry­pi­camera/Step 1 – Taking the time­lapsed photos

This command will take a photo every 60 seconds (60000 milliseconds) for 2 hours (7200000 milliseconds) resulting ina sequence of 120 images.

raspistill ­o myimage_%04d.jpg ­tl 60000 ­t 7200000

The “%04d” will result in a four digit number appearing in each filename.

myimage_0001.jpgmyimage_0002.jpg...myimage_0119.jpgmyimage_0120.jpg

62

Page 63: MrRsPiManualGuide-KernelPanic

Step 2 – Combine images into MP4 video

Once you’ve got your image sequence you will need a method to stitch them together. I decided to use “avconv”. Youcan install this useful library with the following command :

sudo apt­get ­y install libav­tools

To construct the video file from your image sequence you use the command shown below. Although it appears onmultiple lines for readability it should be entered as a single line on the command line :

avconv ­r 10 ­i myimage_%04d.jpg ­r 10 ­vcodec libx264 ­crf 20 ­g 15 timelapse.mp4

The video will be the full resolution of the default image size (2592×1944).

To crop the images and create a more standard 1280×720 resolution video you can use the following command :

avconv ­r 10 ­i timelapse_%04d.jpg ­r 10 ­vcodec libx264 ­crf 20 ­g 15 ­vfcrop=2592:1458,scale=1280:720 timelapse.mp4

The “vf” option defines a video filter. In this case two filters which crop the incoming image to 2592×1458 and thenscale them to 1280×720.

The “r” option tells avconv to create a video with a frames per second of 10. It appears twice to prevent avconv droppingframes that it thinks are similar.

The “crf” option tells avconv to aim for a quality level of “20″ which is a good starting point. Lowers values are better butwill increase the file size.

The “­g” option sets the GOP value. The YouTube Advanced Encoding Settings page recommends that the GOPshould be set to half the frame rate so this is set to 15.

The conversion process is very slow on the Pi compared to doing the same thing on a desktop PC. For longsequences with hundreds of frames I would recommend downloading an appropriate version of Libav on your desktopor laptop and build your MP4 files much faster!

63

Page 64: MrRsPiManualGuide-KernelPanic

Converting the Video outputhttp://raspi.tv/2013/how­to­shoot­video­and­convert­it­to­something­you­can­edit­in­pinnacle­and­other­programs

ffmpeg ­r 30 ­i video_in.h264 ­vcodec copy video_out.mp4

Extra Tricks by Bill TideyBill posted these tips in the Pi forums and they were too good not to share…ffmpeg ­f lavfi ­i aevalsrc=0 ­r 30 ­i test.h264 ­shortest ­c:v copy ­c:a aac ­strict experimental testo.mp4

…adds a silent audio channel as some video editors don’t work without this.

ffmpeg ­i test.mp3 ­r 30 ­i test.h264 ­shortest ­c:v copy ­c:a aac ­strict experimental testo.mp4…adds a real audio track where the test.mp3 should normally be longer than the video as the output isthe shortest.

64

Page 65: MrRsPiManualGuide-KernelPanic

Watermarking with another Graphic!

Firstly install a wonderful gem piece of software calledimagemagick, if it works in the GIMP or Photoshop youcan probably do something similar with imagemagickfrom the command line. This is a VERY complexbeasty! With more arugments than I’d care to guess.But I thought hell, let’s dive in.

sudo apt­get install imagemagick

Full manual for ImageMagick here.

I created a nice little MRO Pi logo in cooltext (and saved it!), didn’t try this on the Pi, but used WinSCP toget it on the Pi.

I already had some stock images on the Pi (in a folder!), I put the logo in there too!

First I found I had to resize the logo as the captured images from the Pi camera are 2592x1944 pixels

I used the command

convert CT_Pi_Logo.png 1000% CTI_Pi_Big.png

Which converted the image (I could go from JPG to PNG if I wanted!), but also increased the size tenfold(1000%) I found this a bit massive and went for (500% in the end!) The ­adaptive­resize gave me muchbetter quality!

convert CT_Pi_Logo.png ­adaptive­resize 500% CTI_Pi_Big.png

I then tried various commands to move the logo round. (notice the logo is called first, to put on top of theother image, if you do it the other way round it crops down the large image to small! I used the compositecommand to put them together. I found you could use ­gravity south to define how low on the page (Iassume North is at the top!)

composite CTI_Pi_Big.png myimage_11.jpg ­gravity south test.png

A much better way of doing this was to use exact pixel co­ordinates (starting 0,0 in the top left!)

So finally I used

composite ­geometry +100+1700 CTI_Pi_Big.png myimage_11.jpg test.png

to put the image in the bottom left corner!

Using the Pi Camera module with MotionSee my guide for setting up motion for the PS3 camer for further details. However to use the raspberry pi

65

Page 66: MrRsPiManualGuide-KernelPanic

camera you need a modified version of Motion (motion­mmal) and a custom config file. I tried compiling itfrom source but could not get it work (configure/make/make install). Not only would it not work it refusedto detect the special config file required. So I used

sudo apt­get purge motion

To clean it from the system, then used the binary available here (Dropbox blocked at school) but you candownload the tarball.

I copied the files to the Pi (in their own folder) and had some success using

sudo ./motion ­n ­c motion­mmal.conf

where the ­n means you SHOULD be able to stop the camera from the command prompt rather thanrunning it as a service and ­c lets you choose the custom config file. I had some success with this,however it did seem to crash the Pi on several occasions (the keyboard stopped working!) Will do furthertests, it was also unresponsive across my local network (where I wish to view the camera results via thebrowser!)

The key command in the .conf file to access the Pi camera ismmalcam_name vc.ril.camera

.... not/dev/video0

66

Page 67: MrRsPiManualGuide-KernelPanic

Creepy Face Tracking (Partly Tested)http://learn.adafruit.com/downloads/pdf/creepy­face­tracking­portrait.pdfhttp://learn.adafruit.com/creepy­face­tracking­portrait/software

https://www.youtube.com/watch?v=3rhnfBSjj6w

Binary InstallationExecute the following commands to get thebinaries:

mkdir ~/creepyportraitcd ~/creepyportraitwgethttps://github.com/tdicola/creepyportrait/raw/master/creepyportrait_1.0_raspberrypi.tar.gztar xvf creepyportrait_1.0_raspberrypi.tar.gzsudo ./install_dependencies.sh

Answer yes to the questions about updating and installing packages that come up whentheinstall_dependencies.sh script is run. This script is provided in openFrameworks and will install all thenecessary libraries for running openFrameworks applications like the creepy portrait.

UsageTo run the program first make sure either the Raspberry Pi camera or a webcam is attached to yourRaspberry Pi.

Note: If you're using the Raspberry Pi camera for the first time, make sure to follow these instructions toenable it with the raspi­config command.

First run the program with no command line parameters by executing: ./creepyportrait

You should see the program usage and an error message about no video device being selected. If you'reusing a webcam, note the device ID number of the webcam you want to use.

To run the program with the Raspberry Pi camera execute: ./creepyportrait pi

Or to run the program with a webcam execute: ./creepyportrait (video device ID)

Where (video device ID) is the ID of the webcam from above. For example if you're using device ID 0 youwould execute './creepyportrait 0' (without quotes).

It should take about 30­60 seconds for the program to start and display the skull. You should also see videofrom your camera in the upper left corner, and every ~2 seconds a green box appear over the largestdetected face in the video. Make sure you have a decent amount of light on your face or else the detectionwon't be very reliable.

67

Page 68: MrRsPiManualGuide-KernelPanic

You can press the following buttons on the Raspberry Pi's keyboard to control the application:

V ­ Hide or show the video in the upper left corner. M ­ If you're running with more than one 3D model (see further below), change between

rendering different models. On the Raspberry Pi, for now only one model can be loaded inmemory at a time.

Escape or Ctrl­C ­ Close the application.

You can run the program with a different 3D model by specifying it in a second command line parameter.The possible values are:

skull jackevil jackhappy all

Skull is the default model. Unfortunately even on the Raspberry Pi model B there isn't enough memory toload all models at once, so pick your favorite one and use it when you run on the Pi.

For example to run with the evil jack­o­lantern using the Raspberry Pi camera you would execute:./creepyportrait pi jackevil

Continue on if you want to download and compile openFrameworks and the code for the creepy portrait. Ifyou just want to run the creepy portrait you can stop here, you're done!

Fixing RaspVid / RaspImage for Headless streaminghttp://www.darkoperator.com/blog/2013/5/23/fixin­raspistill­and­raspivid­for­headless­streaming­on­the.html

68

Page 69: MrRsPiManualGuide-KernelPanic

Cheap PIR Sensors and the Raspberry Pi – Part 1 (untested)

http://www.raspberrypi­spy.co.uk/2013/01/cheap­pir­sensors­and­the­raspberry­pi­part­1/

A great little sensor you can add to your Raspberry Pi projects is a PIR module. These 5V “Passive InfraRed” sensors are available for a few pounds from eBay. They can be powered from 5V and output 3V socan be connected directly to pins on the Pi’s GPIO header without any other components.The module sets a single output pin high whenever it detects movement within its field of view. It holdsthis pin High (3.3V) for a minimum period of time. If continuous movement is detected the output pin willstay High. When the time has elapsed and no more movement is detected the output pin returns Low(0V).I am currently using one in an alarm system and it works great for such a small and cheap device.

PIR ConnectionsHere is a diagram showing the pin­out on the PIR module and how I connected it to my Raspberry Pi :

PIR ModuleThe device has two variable resistors that you can adjust to tweak the performance of the module.

Trimming Controls

69

Page 70: MrRsPiManualGuide-KernelPanic

The first one (left­hand side on the photo)determines the sensitivity of the device. Thedefault setting is usually 50%.The second control (right­hand side on the photoand usually marked “time” on the PCB) allows youto adjust the amount of time the output pin staysat 3V (high) when it is triggered by movement.This can be set from a few seconds to 200seconds. The default setting is usually a fewseconds.The units available on eBay vary in specificationbut they are all very similar.Python Example ScriptIf you connect your module as shown in thediagram above the following Python script willallow you to get started. Cut and paste the scriptbelow into a text file and transfer to the Pi ordownload the script directly using this link.

#!/usr/bin/python#+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+#|R|a|s|p|b|e|r|r|y|P|i|­|S|p|y|.|c|o|.|u|k|#+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+## pir_1.py# Detect movement using a PIR module## Author : Matt Hawkins# Date : 21/01/2013

# Import required Python librariesimport RPi.GPIO as GPIOimport time

# Use BCM GPIO references# instead of physical pin numbersGPIO.setmode(GPIO.BCM)

# Define GPIO to use on PiGPIO_PIR = 7

print "PIR Module Test (CTRL­C to exit)"

# Set pin as inputGPIO.setup(GPIO_PIR,GPIO.IN) # Echo

Current_State = 0Previous_State = 0

try:

print "Waiting for PIR to settle ..."

# Loop until PIR output is 0 while GPIO.input(GPIO_PIR)==1: Current_State = 0

print " Ready"

# Loop until users quits with CTRL­C while True :

# Read PIR state Current_State = GPIO.input(GPIO_PIR)

if Current_State==1 and Previous_State==0: # PIR is triggered print " Motion detected!" # Record previous state Previous_State=1 elif Current_State==0 and Previous_State==1: # PIR has returned to ready state print " Ready" Previous_State=0

# Wait for 10 milliseconds time.sleep(0.01)

except KeyboardInterrupt: print " Quit" # Reset GPIO settings GPIO.cleanup()

70

Page 71: MrRsPiManualGuide-KernelPanic

This script can also be downloaded onto your Pi directly using this command line:

1 wget http://www.raspberrypi­spy.co.uk/archive/python/pir_1.py

This can then be run using :

1 sudo python pir_1.py

When run the script waits for the output pin to go Low. It then prints a message to the screen every timethe output state changes. This is either when movement is detected (output changes to High) or thedevice sees no movement (outout changes to Low).Try changing the reset time by turning the “time” resistor clockwise by a few degrees. Run the scriptagain, trigger the device and then wait to see how long it takes to go back to the ready state.

PhotosHere some more detailed photos of the PIR pins and two trimming controls :

71

Page 73: MrRsPiManualGuide-KernelPanic

Robot Arm Basicshttp://www.wikihow.com/Use­a­USB­Robotic­Arm­with­a­Raspberry­Pi­(Maplin)

Save the followingcode in arm.py thenrun using sudo pythonarm.py

#ROBOT ARM CONTROL PROGRAM#import the USB and Time librarys into Pythonimport usb.core, usb.util, time#Allocate the name 'RoboArm' to the USB deviceRoboArm = usb.core.find(idVendor=0x1267, idProduct=0x000)#Check if the arm is detected and warn if notif RoboArm is None: raise ValueError("Arm not found")#Create a variable for durationDuration=1#Define a procedure to execute each movementdef MoveArm(Duration, ArmCmd): #Start the movement RoboArm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,3) #Stop the movement after waiting a specified duration time.sleep(Duration) ArmCmd=[0,0,0] RoboArm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,3)

#Do a quick test of all the joints.MoveArm(1,[0,2,0]) #Rotate base clockwiseMoveArm(1,[64,0,0]) #Shoulder upMoveArm(1,[128,0,0]) #Shoulder downMoveArm(1,[16,0,0]) #Elbow upMoveArm(1,[32,0,0]) #Elbow downMoveArm(1,[4,0,0]) #Wrist upMoveArm(1,[8,0,0]) # Wrist downMoveArm(1,[2,0,0]) #Grip openMoveArm(1,[1,0,0]) #Grip closeMoveArm(1,[0,0,1]) #Light onMoveArm(1,[0,0,0]) #Light off

73

Page 74: MrRsPiManualGuide-KernelPanic

Robot Arm with PS3 Pad

#!/usr/bin/env python

import pygameimport usb.coreimport time

pygame.init()

# Wait for a joystickwhile pygame.joystick.get_count() == 0: print 'waiting for joystick count = %i' % pygame.joystick.get_count() time.sleep(10) pygame.joystick.quit() pygame.joystick.init()

j = pygame.joystick.Joystick(0)j.init()

print 'Initialized Joystick : %s' % j.get_name()

armFound = False

while not armFound: dev = usb.core.find(idVendor=0x1267, idProduct=0x0000)

if dev is None: print 'Arm not found. Waiting' time.sleep(10) else: armFound = True

#this arm should just have one configuration...dev.set_configuration()

# How far to move the JoyStick before it has an effect (0.60 = 60%)threshold = 0.60

# Key mappingsPS3_BUTTON_SELECT = 0

PS3_AXIS_LEFT_HORIZONTAL = 0PS3_AXIS_LEFT_VERTICAL = 1PS3_AXIS_RIGHT_HORIZONTAL = 2PS3_AXIS_RIGHT_VERTICAL = 3PS3_AXIS_X = 17PS3_AXIS_CIRCLE = 18PS3_AXIS_R1 = 15PS3_AXIS_R2 = 13

# Robot Arm defaultscommand = (0,0,0)lc = 0shoulder = 0base = 0elbow = 0wristup = 0wristdown = 0grip_open = 0grip_close = 0grip_command = 0wrist_command = 0shoulder_command = 0base_command = 0elbow_command = 0

# ARM control related stuffdef setcommand(axis_val): if axis_val > threshold: return 1 elif axis_val < ­threshold:

I use to drive a USB RobotARM from my RaspberryPi using a PlayStation 3controller. I got the ARMfrom Maplins in the UK(Code:A37JN) and its aOWI EDGE 535 Robotickit.Most of the tools requiredto control the Robot ARMfrom a Raspberry Picome pre­installed on thelatest images, howeveryou will need to installPyUSB to sendcommands to the ARM.

sudo apt­get installpython libusb­0.1­4

git clonehttps://github.com/walac/pyusb.git

cd pyusbsudo python

setup.py install

With the PyUSB moduleinstalled and a PS3controller attached its justa simple case of runningthe following script tocontrol its movements.The analogue stickscontrol the ARMmovement, with theR1/R2 buttons moving thewrist and the X and Circlekeys operating the gripper.

This assumes the PS3Pad is wired.

74

Page 75: MrRsPiManualGuide-KernelPanic

return 2 elif abs(axis_val) < threshold: return 0

def buildcommand(shoulc,basec,elbowc,wristc,gripc,lightc): byte1 = shoulc + elbowc + wristc + gripc comm_bytes = (byte1, basec, lightc) return comm_bytes

def processArm(event): global command, lc, shoulder, base, elbow, wristup, wristdown, grip_open, grip_close,grip_command, wrist_command, shoulder_command, base_command, elbow_command

if event.type == pygame.JOYBUTTONDOWN: if event.button == PS3_BUTTON_SELECT: if lc == 0: lc = 1 else: lc = 0 elif event.type == pygame.JOYAXISMOTION: if event.axis == PS3_AXIS_LEFT_VERTICAL: shoulder = event.value elif event.axis == PS3_AXIS_LEFT_HORIZONTAL: base = event.value elif event.axis == PS3_AXIS_RIGHT_VERTICAL: elbow = event.value elif event.axis == PS3_AXIS_R1: wristup = event.value elif event.axis == PS3_AXIS_R2: wristdown = event.value elif event.axis == PS3_AXIS_X: grip_open = event.value elif event.axis == PS3_AXIS_CIRCLE: grip_close = event.value

# Are we opening or closing the gripper? if grip_open> threshold: grip_command = 1 elif grip_close> threshold: grip_command = 2 else: grip_command = 0

# And the same for the wrist, are we moving up or down? if wristup > threshold: wrist_command = 1*4 elif wristdown > threshold: wrist_command = 2*4 else: wrist_command = 0 shoulder_command = setcommand(shoulder)*64 base_command = setcommand(base) elbow_command = setcommand(elbow)*16

# Work out what to send out to the robot newcommand = buildcommand(shoulder_command,base_command, elbow_command, wrist_command, grip_command,lc)

# If the command has changed, send out the new one if newcommand != command: dev.ctrl_transfer(0x40, 6, 0x100, 0, newcommand, 1000) command = newcommand

try: # Loop forwever while True: # Sleep so we don't eat up all the CPU time time.sleep(0.1)

# read in events events = pygame.event.get()

# and process them

75

Page 76: MrRsPiManualGuide-KernelPanic

for event in events: processArm(event)

except KeyboardInterrupt: j.quit()

76

Page 77: MrRsPiManualGuide-KernelPanic

Robot Arm With Wii­Motesudo apt­get install libusb­devsudo apt­get install python­pipsudo pip install pyusbsudo apt­get install bluez python­cwii

# +­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+# |T|A|Y|L|O|R| |B|O|A|R|D|M|A|N| | | |R|P|I| |A|R|M|# +­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+

'''First we need to import some files (These files contain all the commands needed for our program)We have usb.core and usb.util ­ these are used to control the usb port for our armNext we have cwiid which communicates with the wiimoteAnd we have the time libary which allows us to slow or pause things'''

import usb.core, usb.util, cwiid, time

#Give our robot arm an easy name so that we only need to specify all the junk required for the usb connection onceprint 'Make sure the arm is ready to go.'print ''Armc = 1750Arm = Nonewhile (Arm == None):

#This connects to the usbArm = usb.core.find(idVendor=0x1267, idProduct=0x0000)#This will wait for a second, and then if the program could not connect, it tells us and tries againArmc = Armc + 1if (Armc == 2000):print 'Could not connect to Arm, double check its connections.'print 'Program will continue when connection is established...'print ' 'Armc = Armc/2000continue

#Set up our arm transfer protocol through the usb and define a Value we can change to control the armDuration = 1ArmLight = 0

#Create delay variable that we can use (Seconds)Delay = .1Counter = 9999def ArmMove(Duration, ArmCmd):

#Start MovementArm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,1000)time.sleep(Duration)

#Stop MovementArmCmd=[0,0,ArmLight]Arm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,1000)

#Establish a connection with the wiimoteprint 'Connected to arm successfully.'print ' 'print 'Press 1 and 2 on the wiimote at the same time.'#Connect to mote and if it doesn't connect then it tells us and tries againtime.sleep(3)print ''print 'Establishing Connection... 5'time.sleep(1)

77

Page 78: MrRsPiManualGuide-KernelPanic

print 'Establishing Connection... 4'time.sleep(1)print 'Establishing Connection... 3'Wii = Nonewhile (Wii==None):

try:Wii = cwiid.Wiimote()except RuntimeError:print 'Error connecting to the wiimote, press 1 and 2.'

print 'Establishing Connection... 2'time.sleep(1)print 'Establishing Connection... 1'time.sleep(1)print ''

#Once a connection has been established with the two devices the rest of the program will continue; otherwise, it will keep on trying toconnect to the two devices

#Rumble to indicate connection and turn on the LEDWii.rumble = 1 #1 = on, 0 = offprint 'Connection Established.'print 'Press any button to continue...'print ''

''' Each number turns on different leds on the wiimoteex) if Wii.led = 1, then LED 1 is on2 = LED 2 3 = LED 3 4 = LED 45 = LED 1, 3 6 = LED 2, 3 7 = LED 1,2,38 = LED 4 9 = LED 1, 4 10 = LED 2,411 = LED 1,2,4 12 = LED 3,4 13 = LED 1,3,414 = LED 2,3,4 15 = LED 1,2,3,4It counts up in binary to 15'''

time.sleep(1)Wii.rumble = 0Wii.led = 15

# Set it so that we can tell when and what buttons are pushed, and make it so that the accelerometer input can be readWii.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC | cwiid.RPT_EXTWii.state

while True:

#This deals with the accelerometer'''create a variable containing the x accelerometer value(changes if mote is turned or flicked left or right)flat or upside down = 120, if turned: 90 degrees cc = 95, 90 degrees c = 145'''Accx = (Wii.state['acc'][cwiid.X])

'''create a variable containing the y accelerometer value(changes when mote is pointed or flicked up or down)flat = 120, IR pointing up = 95, IR pointing down = 145'''Accy = (Wii.state['acc'][cwiid.Y])

'''create a variable containing the z accelerometer value(Changes with the motes rotation, or when pulled back or flicked up/down)flat = 145, 90 degrees cc or c, or 90 degrees up and down = 120, upside down = 95'''Accz = (Wii.state['acc'][cwiid.Z])

#This deals with the buttons, we tell every button what we want it to dobuttons = Wii.state['buttons']#Get battery life (as a percent of 100):

78

Page 79: MrRsPiManualGuide-KernelPanic

#Just delete the nunber sign inn front#print Wii.state['battery']*100/cwiid.BATTERY_MAX

# If the home button is pressed then rumble and quit, plus close programif (buttons & cwiid.BTN_HOME):print ''print 'Closing Connection...'ArmLight = 0ArmMove(.1,[0,0,0])Wii.rumble = 1time.sleep(.5)Wii.rumble = 0Wii.led = 0exit(Wii)

''' Arm Commands Defined by ArmMove are[0,1,0] Rotate Base Clockwise[0,2,0] Rotate Base C­Clockwise[64,0,0] Shoulder Up[128,0,0] Shoulder Down[16,0,0] Elbow Up[32,0,0] Elbow Down[4,0,0] Wrist Up[8,0,0] Wrist Down[2,0,0] Grip Open[1,0,0] Grip Close[0,0,1] Light On[0,0,0] Light Off

ex) ArmMove(Duration in seconds,[0,0,0])This example would stop all movement and turn off the LED'''

#Check to see if other buttons are pressedif (buttons & cwiid.BTN_A):print 'A pressed'time.sleep(Delay)ArmMove(.1,[1,0,ArmLight])if (buttons & cwiid.BTN_B):print 'B pressed'time.sleep(Delay)ArmMove(.1,[2,0,ArmLight])if (buttons & cwiid.BTN_1):print '1 pressed'ArmMove(.1,[16,0,ArmLight])if (buttons & cwiid.BTN_2):print '2 pressed'ArmMove(.1,[32,0,ArmLight])if (buttons & cwiid.BTN_MINUS):print 'Minus pressed'ArmMove(.1,[8,0,ArmLight])if (buttons & cwiid.BTN_PLUS):print 'Plus pressed'ArmMove(.1,[4,0,ArmLight])if (buttons & cwiid.BTN_UP):print 'Up pressed'ArmMove(.1,[64,0,ArmLight])if (buttons & cwiid.BTN_DOWN):print 'Down pressed'ArmMove(.1,[128,0,ArmLight])if (buttons & cwiid.BTN_LEFT):print 'Left pressed'ArmMove(.1,[0,2,ArmLight])

79

Page 80: MrRsPiManualGuide-KernelPanic

if (buttons & cwiid.BTN_RIGHT):print 'Right pressed'ArmMove(.1,[0,1,ArmLight])

#Here we handle the nunchuk, along with the joystick and the buttonswhile(1):if Wii.state.has_key('nunchuk'):try:#Here is the data for the nunchuk stick:#X axis:LeftMax = 25, Middle = 125, RightMax = 225NunchukStickX = (Wii.state['nunchuk']['stick'][cwiid.X])#Y axis:DownMax = 30, Middle = 125, UpMax = 225NunchukStickY = (Wii.state['nunchuk']['stick'][cwiid.Y])#The 'NunchukStickX' and the 'NunchukStickY' variables now store the stick values

#Here we take care of all of our data for the accelerometer

#The nunchuk has an accelerometer that records in a similar manner to the wiimote, but the number range is different#The X range is: 70 if tilted 90 degrees to the left and 175 if tilted 90 degrees to the rightNAccx = Wii.state['nunchuk']['acc'][cwiid.X]#The Y range is: 70 if tilted 90 degrees down (the buttons pointing down), and 175 if tilted 90 degrees up (buttons pointing up)NAccy = Wii.state['nunchuk']['acc'][cwiid.Y]#I still don't understand the z axis completely (on the wiimote and nunchuk), but as far as I can tell it's main change comes

from directly pulling up the mote without tilting itNAccz = Wii.state['nunchuk']['acc'][cwiid.Z]

#Make it so that we can control the arm with the joystickif (NunchukStickX < 60):

ArmMove(.1,[0,2,ArmLight])print 'Moving Left'

if (NunchukStickX > 190):ArmMove(.1,[0,1,ArmLight])print 'Moving Right'

if (NunchukStickY < 60):ArmMove(.1,[128,0,ArmLight])print 'Moving Down'

if (NunchukStickY > 190):ArmMove(.1,[64,0,ArmLight])print 'Moving Up'

#Make it so that we can control the arm with tilt Functions#Left to Rightif (Accx < 100 and NAccx < 90 ):

ArmMove(.1,[0,2,ArmLight])print 'Moving Left'

if (Accx > 135 and NAccx > 150):ArmMove(.1,[0,1,ArmLight])print 'Moving Right'

#Up and Downif (Accy < 100 and NAccy < 90):

ArmMove(.1,[64,0,0])print 'Moving Up'

if (Accy > 135 and NAccy > 150):ArmMove(.1,[128,0,0])print 'Moving Down'

#Here we create a variable to store the nunchuck button data#0 = no buttons pressed#1 = Z is pressed#2 = C is pressed#3 = Both C and Z are pressed

80

Page 81: MrRsPiManualGuide-KernelPanic

ChukBtn = Wii.state['nunchuk']['buttons']if (ChukBtn == 1):

print 'Z pressed'ArmLight = 0ArmMove(.1,[0,0,ArmLight])

if (ChukBtn == 2):

print 'No nunchuk detected.'else:if (ArmLight == 0):if (Accz > 179 or Accz < 50):print 'C pressed'

ArmLight = 1ArmMove(.1,[0,0,ArmLight])

#If both are pressed the led blinksif (ChukBtn == 3):

print 'C and Z pressed'ArmMove(.1,[0,0,0])time.sleep(.25)ArmMove(.1,[0,0,1])time.sleep(.25)ArmMove(.1,[0,0,0])time.sleep(.25)ArmMove(.1,[0,0,1])time.sleep(.25)ArmMove(.1,[0,0,0])time.sleep(.25)ArmMove(.1,[0,0,1])time.sleep(.25)ArmMove(.1,[0,0,0])

#Any other actions that require the use of the nunchuk in any way must be put here for the error handling to function properlybreak

#This part down below is the part that tells us if no nunchuk is connected to the wiimoteexcept KeyError:

ArmLight = 1ArmMove(.1,[0,0,ArmLight])time.sleep(.5)

elif (ArmLight == 1):if (Accz > 179 or Accz < 50):

ArmLight = 0ArmMove(.1,[0,0,ArmLight])time.sleep(.5)

if (Counter == 10000):print 'No nunchuk detected.'Counter = Counter/10000breakCounter = Counter + 1break

Robot Arm GUI (in Python) ­ WIP

Hmpf, still working this out.

You need the image of the robot arm, 600x600(the controls use the co­ordinates for positioning

from tkinter import *from tkinter import ttkimport time#import usb.core, usb.util,

81

Page 82: MrRsPiManualGuide-KernelPanic

buttons!)

Still not sure what lambda does!!!!

#Code got from here ­ http://pythondictionary.code­it.co.uk/tkinter#& here ­http://www.tutorialspoint.com/python/python_gui_programming.htm

#Set up our arm transfer protocol through the usb and define aValue we can change to control the armDuration = 1

#Create delay variable that we can use (Seconds)Delay = .1Counter = 9999

#INSERT CODE TO TEST FOR ARM HERE (untested)

#This routine byhttp://www.instructables.com/member/Boardmaster/def ArmMove(Duration, ArmCmd):

#Arm Commands Defined by ArmMove are if ArmCmd==[0,1,0]: status='Rotate Base Clockwise' elif ArmCmd==[0,2,0]: status='Rotate Base C­Clockwise' elif ArmCmd==[64,0,0]: status='Shoulder Up' elif ArmCmd==[128,0,0]: status='Shoulder Down' elif ArmCmd==[16,0,0]: status='Elbow Up' elif ArmCmd==[32,0,0]: status='Elbow Down' elif ArmCmd==[4,0,0]: status='Wrist Up' elif ArmCmd==[8,0,0]: status='Wrist Down' elif ArmCmd==[2,0,0]: status='Grip Open' elif ArmCmd==[1,0,0]: status='Grip Close' elif ArmCmd==[0,0,1]: status='Light On' else: status='ALL OFF'

print (str(ArmCmd) + ' ' + status) text.insert("@1,1", str(ArmCmd)+ ' ' + status +'\n')

#Start Movement #Arm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,1000) time.sleep(Duration) #Stop Movement ArmCmd=[0,0,0] #Arm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,1000)

#Define an instance of TK for the window.root = Tk()#Give the window a title.root.title("MRO Robot Arm Controller")#Setup the Canvas, this is based on the Robot Arm image, 600x600can1=Canvas(root, width=600, height=600)can1.pack() #Places the canvas#Define where the image is for the robot arm.filename = PhotoImage(file = "robot.gif")#Put the image on the Canvase, the first 2 args are co­ords...#the anchor says which part of the image these are relative to, NW(top left!)image = can1.create_image(0, 0, anchor=NW, image=filename)

#Define base buttonsbut_baseleft = Button(root, text="BASE \n LEFT",command=lambda: ArmMove(0.1,[0,2,0]))but_baseleft.pack()but_baseleft.place(bordermode=OUTSIDE, height=50, width=50,x=450,y=450)

82

Page 83: MrRsPiManualGuide-KernelPanic

but_baseright = Button(root, text="BASE \n RIGHT",command=lambda: ArmMove(0.1,[0,1,0]))but_baseright.pack()but_baseright.place(bordermode=OUTSIDE, height=50, width=50,x=500,y=450)

#Define shoulder buttonsbut_shoulderup = Button(root, text="SHOULDER \n UP", font='Ariel6',command=lambda: ArmMove(0.1,[64,0,0]))but_shoulderup.pack()but_shoulderup.place(bordermode=OUTSIDE, height=50, width=50,x=100,y=300)

but_shoulderdown = Button(root, text="SHOULDER \n DOWN",font='Ariel 6', command=lambda: ArmMove(0.1,[128,0,0]))but_shoulderdown.pack()but_shoulderdown.place(bordermode=OUTSIDE, height=50,width=50, x=150,y=300)

#Define elbow buttonsbut_elbowup = Button(root, text="ELBOW \n LEFT", font='Ariel8',command=lambda: ArmMove(0.1,[16,0,0]))but_elbowup.pack()but_elbowup.place(bordermode=OUTSIDE, height=50, width=50,x=475,y=180)

but_elbowdown = Button(root, text="ELBOW \n RIGHT", font='Ariel8',command=lambda: ArmMove(0.1,[32,0,0]))but_elbowdown.pack()but_elbowdown.place(bordermode=OUTSIDE, height=50,width=50, x=525,y=180)

#Define wrist buttonsbut_wristup = Button(root, text="WRIST \n UP", font='Ariel8',command=lambda: ArmMove(0.1,[4,0,0]))but_wristup.pack()but_wristup.place(bordermode=OUTSIDE, height=50, width=50,x=250,y=70)

but_wristdown = Button(root, text="WRIST \n DOWN", font='Ariel8',command=lambda: ArmMove(0.1,[8,0,0]))but_wristdown.pack()but_wristdown.place(bordermode=OUTSIDE, height=50, width=50,x=300,y=70)

#Define gripbut_gripopen = Button(root, text="GRIP \n OPEN", font='Ariel8',command=lambda: ArmMove(0.1,[2,0,0]))but_gripopen.pack()but_gripopen.place(bordermode=OUTSIDE, height=50, width=50,x=20,y=80)

but_gripclose = Button(root, text="GRIP \n CLOSE", font='Ariel8',command=lambda: ArmMove(0.1,[1,0,0]))but_gripclose.pack()but_gripclose.place(bordermode=OUTSIDE, height=50, width=50,x=70,y=80)

text = Text(root, x=20, y=20)text.insert(INSERT, "Hello.....")text.pack()text.place(bordermode=OUTSIDE, height=50, width =300, x=20,y=20)

#This always needs to be at the END!root.mainloop()

83

Page 84: MrRsPiManualGuide-KernelPanic

7 Segment Display Project (One of my first!)Using 4543 BCD (Binary Coded Decimal) Chips (x2 for 10s and Units Display) ­ Feed the same data toboth chips DA,DB,DC,DD, different Latches (LD and LD2 on other chip!).

84

Page 85: MrRsPiManualGuide-KernelPanic

For this chose common Catchode.

85

Page 86: MrRsPiManualGuide-KernelPanic

Chips for driving motorshttp://www.hobbytronics.co.uk/motor­control/h­bridge­driver­sn754410http://www.fanjita.org/serendipity/archives/61­Raspberry­Rover­part­2­The­Hardware.html#extended

LCD SetupUsing standard LCD displays to get output from the Pi (Cheap Displays Ordered from Ebay / China)

http://www.raspberrypi­spy.co.uk/2012/07/16x2­lcd­module­control­using­python/http://www.raspberrypi­spy.co.uk/2012/08/16x2­lcd­module­control­with­backlight­switch/

86

Page 87: MrRsPiManualGuide-KernelPanic

Cheap 3.5 LCD Display.

http://www.raspberrypi­spy.co.uk/2012/11/cheap­miniature­lcd­screen/http://www.raspberrypi.org/phpBB3/viewtopic.php?f=64&t=17651

Works a treat, used a funkylittle PSU I bought fromWilkinsons (for around £5 Ithink that switches DCVoltages upto 12 volts.Bargain.

Used the standard setup to change the FONT to something more readable.

sudo dpkg­reconfigure console­setup

Making it run off a USB??? ­ http://www.raspberrypi.org/phpBB3/viewtopic.php?f=64&t=17651

87

Page 88: MrRsPiManualGuide-KernelPanic

HARDWARE ­ Controllers 84

Graphics Testing / Visual Joystick Testsudo apt­get install jstest­gtk

This will then appear in X under one of the menus. Works quite well for visual testing.

Wiimote Basics

Getting the drivers / setupEnsure Bluetooth is installed ­

sudo apt­get install bluetooth

Run 'bluetooth status' fromservice bluetooth status

Should say 'started'

Install CWiiD & WMInputsudo apt­get install python­cwiid wminput wmgui

Run the hcitoolsudo hcitool dev

This should show a device (hci summat... if it doesn't try plugging bluetooth into PI not hub! or a reboot!)

Run a scansudo hcitool scan

This should list your wiimote as Nintendo RVL

Use this script to testget the script ­ wget http://www.raspberrypi­spy.co.uk/archive/python/wii_remote_1.pyRun the script ­ python wii_remote_1.py

88

Page 89: MrRsPiManualGuide-KernelPanic

Running WiiMote as a Mouse.First you need to edit a file so that it detects the Gyros etc.

sudo nano /etc/cwiid/wminput/ir_ptrFind Find these lines:

Plugin.ir_ptr.X = ~ABS_XPlugin.ir_ptr.Y = ~ABS_Y

and replace them with:Plugin.ir_ptr.X = ABS_XPlugin.ir_ptr.Y = ABS_Y

(ensure your sensor bar is plugged in!)

Finally run this (the ­d means it runs as a daemon, daemons good, demons bad!)wminput ­d ­c <config filename from /etc/cwiid/wminput>

or this one for no output.nohup wminput ­d

Wii­Mote Button MappingsNote the RIGHT button should be 512!!!

A Better Diagram

89

Page 90: MrRsPiManualGuide-KernelPanic

WIIMote Infohttps://help.ubuntu.com/community/CWiiDhttp://www.raspberrypi.org/phpBB3/viewtopic.php?f=9&t=1233Using the Wiimote ­ http://talk.maemo.org/showthread.php?t=60178http://www.brianhensley.net/2012/08/wii­controller­raspberry­pi­python.htmlhttp://linux.die.net/man/1/wminputhttp://abstrakraft.org/cwiid/wiki/ConfigScriptEtc ­ Scripts to install. (need to know the MAC address of WIIMote)

http://www.raspberrypi­spy.co.uk/2013/02/nintendo­wii­remote­python­and­the­raspberry­pi/

90

Page 91: MrRsPiManualGuide-KernelPanic

Creating Custom WiiMote Configscd /etc/cwiid/wminput/

Edit / Copy / Mess with the scripts (sudo nano default) ­ default

sudo nano fps_config ­ allows for nunchuck, just save your config as something different.

Daemons allow you to run stuff on start.You can edit the Bluetooth Daemon (runs on start)

sudo nano /etc/init.d/bluetooth(do ctrl+W and search for wminput, add ­c <config> for it to run a specific config.

https://github.com/rpl/python­wiimote­hacks

Using Wii­Motes in Python ProjectsFor a few step by step guideshttp://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/robot/getting_started/

­ this script is a great place to start.wget http://www.raspberrypi­spy.co.uk/archive/python/wii_remote_1.py

#!/usr/bin/python#+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+#|R|a|s|p|b|e|r|r|y|P|i|­|S|p|y|.|c|o|.|u|k|#+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+­+## wii_remote_1.py# Connect a Nintendo Wii Remote via Bluetooth# and read the button states in Python.## Project URL :# http://www.raspberrypi­spy.co.uk/?p=1101## Author : Matt Hawkins# Date : 30/01/2013

# ­­­­­­­­­­­­­­­­­­­­­­­# Import required Python libraries# ­­­­­­­­­­­­­­­­­­­­­­­import cwiidimport time

button_delay = 0.1

print 'Press 1 + 2 on your Wii Remote now ...'time.sleep(1)

# Connect to the Wii Remote. If it times out

91

Page 92: MrRsPiManualGuide-KernelPanic

# then quit.try: wii=cwiid.Wiimote()except RuntimeError: print "Error opening wiimote connection" quit()

print 'Wii Remote connected...\n'

print 'Press some buttons!\n'print 'Press PLUS and MINUS together to disconnect and quit.\n'

wii.rpt_mode = cwiid.RPT_BTN

while True:

buttons = wii.state['buttons']

# If Plus and Minus buttons pressed # together then rumble and quit. if (buttons ­ cwiid.BTN_PLUS ­ cwiid.BTN_MINUS == 0): print '\nClosing connection ...' wii.rumble = 1 time.sleep(1) wii.rumble = 0 exit(wii)

# Check if other buttons are pressed by # doing a bitwise AND of the buttons number # and the predefined constant for that button. if (buttons & cwiid.BTN_LEFT): print 'Left pressed' time.sleep(button_delay)

if(buttons & cwiid.BTN_RIGHT): print 'Right pressed' time.sleep(button_delay)

if (buttons & cwiid.BTN_UP): print 'Up pressed' time.sleep(button_delay)

if (buttons & cwiid.BTN_DOWN):

print 'Down pressed' time.sleep(button_delay)

if (buttons & cwiid.BTN_1): print 'Button 1 pressed' time.sleep(button_delay)

92

Page 93: MrRsPiManualGuide-KernelPanic

if (buttons & cwiid.BTN_2): print 'Button 2 pressed' time.sleep(button_delay)

if (buttons & cwiid.BTN_A): print 'Button A pressed' time.sleep(button_delay)

if (buttons & cwiid.BTN_B): print 'Button B pressed' time.sleep(button_delay)

if (buttons & cwiid.BTN_HOME): print 'Home Button pressed' time.sleep(button_delay)

if (buttons & cwiid.BTN_MINUS): print 'Minus Button pressed' time.sleep(button_delay)

if (buttons & cwiid.BTN_PLUS): print 'Plus Button pressed' time.sleep(button_delay)

93

Page 94: MrRsPiManualGuide-KernelPanic

XBox 360 Pad

Install the XBox Pad Drivers.sudo apt­get install xboxdrv

http://pingus.seul.org/~grumbel/xboxdrv/xboxdrv.html

Create a mapping file

(create a directory to put the mappings in)cd ~mkdir Xboxcd Xboxsudo nano basic_config

An example mapping file can look something likethis...(Left Stick acts like Keys, WASD)(Right Stick acts like mouse ­ x2,y2)(copy and paste the following!)

[xboxdrv]silent=truedeadzone=6000dpad­as­button=truetrigger­as­button=true

[ui­axismap]#Map the Right stick like a mouse.x2=REL_X:10y2=REL_Y:­10#Map the left stick as keysx1=KEY_A:KEY_Dy1=KEY_W:KEY_S

#Map the 4 coloured buttons[ui­buttonmap]a=KEY_LEFTSHIFTb=BTN_Cx=BTN_EXTRAy=KEY_C

#Map the Bumper Buttons[ui­buttonmap]lb=BTN_RIGHTrb=KEY_SPACE

#Map the Triggers.[ui­buttonmap]lt=KEY_Zrt=BTN_LEFT

#Map the D­PAD[ui­buttonmap]dl=KEY_4dr=KEY_2du=REL_WHEEL:­1:150dd=REL_WHEEL:1:150

[ui­buttonmap]back=KEY_TABstart=KEY_ESCGUIDE=BTN_HOME

94

Page 95: MrRsPiManualGuide-KernelPanic

Alternative Joystick Setup.

For an alternative (for use with pygame etc) useABS Values (not REL)

[ui­axismap]#Right stick to ABSx2=ABS_Xy2=ABS_Y#Left stick to Mousex1=REL_X:10y1=REL_Y:­10

[ui­buttonmap]a=BTN_Ab=BTN_Bx=BTN_Xy=BTN_Y

Alternative Setup For XBMC.# XBMC Configuration# ==================## This configuration file that with XBMC by emulating a wireless# Xbox360 controller connected to the xpad kernel driver. It uses the# configuration files that come with XBMC, so it should work out of# the box without any further configuration of XBMC.##[xboxdrv]ui­clear = trueextra­devices=falseextra­events=falsedeadzone=6000device­name = "Xbox 360 Wireless Receiver"

[ui­buttonmap]#A=BTN_AA=KEY_ENTER#B=BTN_BB=KEY_BACKSPACEX=KEY_XY=KEY_ESC

#Steuerkreuz Links macht A, Steuerkreuz Rechts macht B

#DU=BTN_0DU=KEY_UP#DD=BTN_1DD=KEY_DOWN#DL=BTN_LEFTDL=KEY_LEFT#DR=BTN_RIGHT

95

Page 96: MrRsPiManualGuide-KernelPanic

DR=KEY_RIGHT

START=BTN_STARTGUIDE=BTN_MODEBACK=BTN_BACK

LB=BTN_TLRB=BTN_TR

#TL=BTN_THUMBLTL=BTN_RIGHT#TR=BTN_THUMBRTR=BTN_LEFTRT=KEY_EQUALLT=KEY_MINUS

[ui­axismap]#x2=REL_RX:10#y2=REL_RY:­10

x1=REL_X:10y1=REL_Y:10

# The resp filter moves the neutral position to zero to work around a# bug in XBMC, that causes bogus events when neutral position is# elsewhere. It loses a bit of precision in the trigger as result, but# that isn't noticable.LT^resp:127:255=ABS_ZRT^resp:127:255=ABS_RZ

# EOF #

Call the mapping usingsudo xboxdrv ­­config basic_config

Run it in the backgroun using the above with an ‘&’ at the end.

Alternative calling1) Start xboxdrv via ­ for example ­ (im my case for 2 controllers):sudo xboxdrv ­­wid 0 ­­silent ­­deadzone 4500 ­­ui­buttonmap guide=KEY_ESC ­­led 8 ­­priority realtime­­four­way­restrictor ­­ui­axismap x1^resp:­32000:­4000:0:4000:32000,y1^resp:­32000:­4000:0:4000:32000 &sudo xboxdrv ­­wid 1 ­­silent ­­deadzone 4500 ­­ui­buttonmap guide=KEY_ESC ­­led 9 ­­priority realtime­­four­way­restrictor ­­ui­axismap x1^resp:­32000:­4000:0:4000:32000,y1^resp:­32000:­4000:0:4000:32000 &

"­­led ...", "­­four­way­restrictor", "­­ui­axismap..." should not be needed, but I played a LOT with nearly allsettings, because of another problem. I found out, that "­­deadzone" is in fact needed for some gameswhen playing with the analog stick.

Kill all running versions using the killall command.sudo killall xboxdrv

96

Page 97: MrRsPiManualGuide-KernelPanic

97

Page 98: MrRsPiManualGuide-KernelPanic

Using a PS3 controllerIn one of my earlier posts, I enabled control of a robotic arm through a PS3 sixaxis controller. To dothis, we need to install the qtsixa package.

sudo apt­get updatesudo apt­get install qtsixa

http://booting­rpi.blogspot.co.uk/2012/08/dualshock­3­and­raspberry­pi.htmlhttp://www.raspians.com/Knowledgebase/ps3­dualshock­controller­install­on­the­raspberry­pi/https://help.ubuntu.com/community/Sixaxis

Dualshock 3 and Raspberry PIGetting Sony Dualshock 3 gamepad to work in Raspberry Pi on Raspbian (Debian Wheezy).

First of all, I'll need a bluetooth dongle, since Raspbery Pi doesn't have built­in one, listing of compatibledongle you can find here.

So, install dependencies first

sudo apt­get install bluez­utils bluez­compat bluez­hcidump checkinstall libusb­dev libbluetooth­dev joystick

It takes a while.

After all type "hciconfig" in console, you should see something like this.

pi@raspberrypi ~ $ hciconfighci0: Type: BR/EDR Bus: USBBD Address: 00:1F:81:00:06:20 ACL MTU: 1021:4 SCO MTU: 180:1UP RUNNING PSCANRX bytes:1260 acl:0 sco:0 events:46 errors:0TX bytes:452 acl:0 sco:0 commands:45 errors:0

if not, your dongle seems not to be recognized by system.

So now, we need to pairing the dongle with the gamepad using this tool.

download and compile it.

sudo apt­get install pyqt4­dev­toolssudo wget http://www.pabr.org/sixlinux/sixpair.cgcc ­o sixpair sixpair.c ­lusb

98

Page 99: MrRsPiManualGuide-KernelPanic

After this you should have a executable file "sixpair".Now connect your Dualshock via a USB cable to Raspberry Pi and launch this file with sudo.

sudo ./sixpair

Current Bluetooth master: DE:AD:BE:EF:00:00Setting master bd_addr to: 00:1F:81:00:06:20

If you see this, it was successful.

Install a Sixaxis Joystick Manager. Download a last archive and compile only important for us part.

sudo wget http://sourceforge.net/projects/qtsixa/files/QtSixA%201.5.1/QtSixA­1.5.1­src.tar.gz

sudo tar xfvz QtSixA­1.5.1­src.tar.gz

cd QtSixA­1.5.1/sixad

make

sudo mkdir ­p /var/lib/sixad/profilessudo make install

the last command make automatically a package for you, so you can later simple uninstall it, if you won'tit or use a different system, type "sudo make install" instead of "sudo checkinstall"

Now test it, for this launch temporary a sixad daemon.

sudo sixad ­­start

Then press a "PS" button on Dualshock gamepad, if you feel a vibration, it works, congratulations!

After all you can make "sixad" daemon starting at boot time.

sudo update­rc.d sixad defaultsreboot

If you have any trouble with recognition, you can debug your Dualshock controller with "jstest".sudo jstest /dev/input/js0

PS3 Move???http://www.pabr.org/linmctool/linmctool.en.html

PS3 Joystick Buttons and Axes

99

Page 100: MrRsPiManualGuide-KernelPanic

Buttons 4-15 are reported as axes as wellas buttons. The axis corresponding to abutton can be used to determine how hardthe user is pressing on the button, rangingfrom 0 when there is no press, to -1 for ahard press. For these buttons, the axisnumber is the same as the button number.

ps3joy.py also exposes the joystick's three­axis accelerometer and the single­axis gyroscope:Axis Description

16 Right-Left (positive is left)

17 Forward-Backward (positive is forward)

18 Up-Down (positive is up)

19 Yaw axis (positive is clockwise)

QJoyPad ­ Turning Joystick Commands into Keypresses.­ #I thinkt he liqt4­dev is VERY important here!

Download the QJoyPad filessudo apt­get install libxtst­dev libqt4­dev build­essential wget http://downloads.sourceforge.net/qjoypad/qjoypad­4.1.0.tar.gz tar xvf qjoypad­4.1.0.tar.gz cd qjoypad­4.1.0.tar.gz/src../configuremakesudo make install

100

Page 101: MrRsPiManualGuide-KernelPanic

Just runqjoypad

(should show up in the system tray with a little gamepad icon.)Manual Here ­ http://qjoypad.sourceforge.net/doc/doc_index.html

101

Page 102: MrRsPiManualGuide-KernelPanic

HARDWARE ­ USB Devices 98

WIFI ADAPTER???

TP Link wn725n (V2)http://www.raspberrypi.org/phpBB3/viewtopic.php?f=26&t=29752http://blog.elevendroids.com/2012/12/precompiled­tp­link­wl­725n­driver­for­3­2­27­kernel/

1. copy 8188eu.ko to/lib/modules/3.6.11+/kernel/driver/net/wireless2. sudo depmod ­a3. modprobe 8188eu4. ifconfig

Roll your own driver from this source.https://github.com/lwfinger/rtl8188eu

Clone the Githubgit clone http://github.com/lwfinger/rtl8188eu (Note I took the ‘s’ off the http)

RASPBMC Version here ­ https://dl.dropboxusercontent.com/u/99979776/8188eu.kohttp://smhaziq.blogspot.co.uk/2013/06/compiling­tp­link­wn725n­v2­driver­in.html

Edimax Donglehttp://www.savagehomeautomation.com/projects/raspberry­pi­installing­the­edimax­ew­7811un­usb­wifi­adapte.html

Quick Webcam Monitor Guide via Motionsudo apt­get install motionsudo nano /etc/motion/motion.confChange Daemon off TO Daemon onChange webcam_localhost = on TO webcam_localhost = offThen ctrl+x , Y and then enter to saveThen do : sudo nano /etc/default/motionChange start_daemon_motion=no TO start_darmon_motion=yesThen ctrl+x, Y and then enter to save.

Then type: sudo service motion start

Then type ifconfig and pick out the number that will look like 192.168.x.xxx. This is your local IP address ofthe PI.

Go to a browser and type it in i.e. 192.168.1.101 then put :8081. so it will look like192.168.1.101:8081. Then you will see what your webcam sees.

102

Page 103: MrRsPiManualGuide-KernelPanic

PS3 Camera Test under XDE.You can use Guvcview, (this will only work when using the Pi, not via SSH!)

sudo apt­get install guvcview

Once installed start up X (if you haven’t already) you should now find a link under menu (sound andvideo), run the app, should come up with a preview window and a settings window. I found this moreresponsive than MOTION (see below) and a great way to test the eyetoy. (only seemed to work 320x240but for £2 who cares!)

PS3 Eyetoy Camera Streaming

N.B. This ONLY worked for me with the camera plugged into the PI, not the HUB!You may also have to do Hexxeh’s rpi­update (to get the latest firmware!)

Just managed to get my PS3 Eye camera working with the Pi, so thought I'd share how it's done in Debian. Thefollowing steps will get the camera and Pi working together as a simple motion detection device with a web streamthat you can view on your local network:

1. Install the 'motion' package (http://www.lavrsen.dk/foswiki/bin/view/Motion/WebHome):

sudo apt­get install motion

2. Install the ffmpeg package:

sudo apt­get install ffmpeg

3. Edit the /etc/motion/motion.conf file and change the following setting from 'on' to 'off'. This is optional, but willallow the camera to be viewed using another PC on your local network:

webcam_localhost off

4. If you wish to have basic control over the camera from a web browser (see step 11) then you can change thefollowing setting in the same file to 'off':

control_localhost off

5. Since the PS3 Eye camera is capable of capturing at a resolution of 640x480, we can make the following furtherchanges to the /etc/motion.conf file:

ffmpeg_video_codec msmpeg4width 640height 480

# Text is placed in lower left cornertext_left SECURITY CAMERA %t ­ Office

Install wput so can FTP files.# Command to be executed when a picture (.ppm|.jpg) is saved (default: none)# The filename of thepicture is appended as an argument for the command.on_picture_save wputftp://USERNAME:PASSWORD@REMOTE SERVER %f

103

Page 104: MrRsPiManualGuide-KernelPanic

6. Plug your PS3 Eye camera into a USB port on the Pi.

7. Find out the IP Address of your Pi and make a note of it for step 10:

ifconfig

This will give the following output:

eth0 Link encap:Ethernet HWaddr xx:xx:xx:xx:xx:xx inet addr:192.168.32.47 Bcast:192.168.32.255 Mask:255.255.255.0 inet6 addr: fe80::ba27:ebff:fe40:357a/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:31800 errors:0 dropped:0 overruns:0 frame:0 TX packets:27108 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:20174919 (19.2 MiB) TX bytes:29838750 (28.4 MiB)

The address in the above example is 192.168.32.47.

8. Start up the motion application. Note that it has no GUI and can be run from the command line when you first startup the Pi. It doesn't need to run within startx:

sudo motion ­n

9. This will run the software in command­line mode, displaying startup information and errors directly to the console. Italso allows it to be stopped using Ctrl­C. If you want to run the software in the background as a 'daemon', simply type'motion' without the ­n switch.

10. If everything has worked okay, you should be able to go to another computer on your network and browse to yourPi's address to see the camera output:

http://192.168.32.47:8081

Using your Pi's address of course!11. You can also browse to the feed on the Pi itself, although this will only work in Chrome and not Midori.

12. If you browse to the 'control port' address below, you also get rudimentary control over the motion software:

http://192.168.32.47:8080

13. Since this is a motion detection package, it automatically detects movement on the camera and creates '.jpg'image and '.swf' video snapshots each time it sees movement on the camera. These are stored in the followingdirectory:

/tmp/motion

14. Note that these files will build up quite quickly if the camera is pointed at something that moves a lot, so makesure you have plenty of space on your sd card. Also, since the files are stored in /tmp, they will be deleted each timeyou reboot your Pi.

Further Reading here ­ http://chris.gg/2012/07/using­a­ps3­eyetoy­with­the­raspberry­pi/(running as a daemon!)A great way to view your images / swf videos is to use WinSCP and dig them out of the/root/tmp/motion folder (unless you changed it!)

104

Page 105: MrRsPiManualGuide-KernelPanic

Face Recognition on the Pi.Tutorial and guide found hereIt’s a bit disjointed in places, some of the code is a bit unclear (in the wrong place) or not quite there, thishas a difficulty of HARD! But I have learn lots along the way! :)

GUVCVIEWFirst get the webcam working with guvcview (see above

sudo apt­get install update && apt­get install update ­ysudo apt­get install guvcview

CMAKENext install CMAKE (this allows you to compile c code on the pi!)

sudo apt­get updatesudo apt­get install cmake

OPENCVInstall the code to run OpenCV once compiled from Python

sudo apt­get updatesudo apt­get install libopencv­devsudo apt­get install python­opencv

Testing this installed is a little more complicated! First go here to find the code for OpenCV

Make a new folder call it OpenCV

mkdir OpenCVsudo nano display image.cpp

paste the following code in (don’t use the link, some of the code is missing CV parts!)

#include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <iostream>

using namespace cv;using namespace std;

int main( int argc, char** argv ) if( argc != 2) cout <<" Usage: display_image ImageToLoadAndDisplay" << endl; return ­1;

Mat image; image = imread(argv[1], CV_LOAD_IMAGE_COLOR); // Read the file

if(! image.data ) // Check for invalid input cout << "Could not open or find the image" << std::endl ;

105

Page 106: MrRsPiManualGuide-KernelPanic

return ­1;

namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display. imshow( "Display window", image ); // Show our image inside it.

waitKey(0); // Wait for a keystroke in the window return 0;

Make another file for make instructions.

sudo nano CMakeLists.txt

paste the following code into it.

cmake_minimum_required(VERSION 2.8)project( displayimage )find_package( OpenCV REQUIRED )add_executable( displayimage display_image.cpp )target_link_libraries( displayimage $OpenCV_LIBS )

Save it (this is the file that give the compiler the settings to use, you’ll be chaning this several times)

Find a reasonable sized image on the net (a jpg image around 300x300), I used

wget <url>

to grab the file, then rename it using

mv <filename.jpg> sample.jpg

to put it all together finally, compile the c, make the instruction file (executable) and run the code.

cmake .make./displayimage sample.jpg

If all has worked your picture *should* appear on the screen!

Install the face recognition APIDownload the libfacerec file, unzip, compile and make.

wget https://github.com/bytefish/libfacerec/zipball/v0.04unzip v0.04rm v0.04cd libfacereccmake .make

This sounds bonkers but to test if it’s all installed ok we go back to your display image example. Edit themakefile to include the libfacerec libraries. (Look something like this!)

cmake_minimum_required(VERSION 2.8)project( reco )

106

Page 107: MrRsPiManualGuide-KernelPanic

find_package( OpenCV REQUIRED )add_executable( displayimage display_image.cpp )target_link_libraries( displayimage /home/pi/libfacerec/bytefish­libfacerec­e1b143d/libopencv_facerec.a$OpenCV_LIBS )

Compile and make again to test it works.cmake .make./displayimage sample.jpg

Hopefully this will work, if it does things are going well.

Gathering PhotosYou have to train the Pi to ‘KNOW’ who it’s looking at. To do this it needs a set of portrait photos (30 suggested).They should be headshots, face on. However you can just save a large selection of photos and then get the Pi tosort, prep and preen them. Dump the initial photos in the OpenCV folder. (ensure they’re all called a1.jpg, a2.jpg etc.)­ Time for another C Program, ‘Prepare’

Edit the CMakeLists.txt file again withcmake_minimum_required(VERSION 2.8)project( prepare )find_package( OpenCV REQUIRED )add_executable( prepare preparePhoto.cpp )target_link_libraries( prepare $OpenCV_LIBS )

use wget to gather the program.wget http://raufast.org/download/preparePhoto.cpp

cmake .make./prepare 0.3 100 hs 800 1

This will probably crash out a few times, just delete the offending file and re-run. It saved all of myfiles as hsX.jpg. You’ll have to do this for each FACE you want to recognise (upto 4 apparently!)Move all of these files into a Faces Folder then a subfolder for each person.

-OpenCv-OpenCv/Faces/S1

This is difficult to get right, but you need to generate a CSV file that will be used later by the reco (recognitionsoftware). I tried doing this manually but couldn’t get it work. There’s a script you can run. (available from here)

N.B. ­ (You can do this just using WinSCP, highlight all the files, use copy to clipboard, use nano tocreate a new .csv file, paste in, use ‘;0’ as the delimiter on each line!) But the script will probablywork better for most folk.

#!/usr/bin/env python

import sysimport os.path

# This is a tiny script to help you creating a CSV file from a face# database with a similar hierarchie:#

107

Page 108: MrRsPiManualGuide-KernelPanic

# philipp@mango:~/facerec/data/at$ tree# .# |­­ README# |­­ s1# | |­­ 1.pgm# | |­­ ...# | |­­ 10.pgm# |­­ s2# | |­­ 1.pgm# | |­­ ...# | |­­ 10.pgm# ...# |­­ s40# | |­­ 1.pgm# | |­­ ...# | |­­ 10.pgm#

if __name__ == "__main__":

if len(sys.argv) != 2: print "usage: create_csv <base_path>" sys.exit(1)

BASE_PATH=sys.argv[1] SEPARATOR=";"

label = 0 for dirname, dirnames, filenames in os.walk(BASE_PATH): for subdirname in dirnames: subject_path = os.path.join(dirname, subdirname) for filename in os.listdir(subject_path): abs_path = "%s/%s" % (subject_path, filename) print "%s%s%d" % (abs_path, SEPARATOR, label) label = label + 1

I dumped this in the Faces folder, then ran using

python create_csv.py /home/pi/OpenCv/Faces > faces.csv

I later moved this csv back out into the OpenCv Folder (easier)

Install the Reco ProgramEdit our old friend the CMakeLists.txt.cmake_minimum_required(VERSION 2.8)project( reco)find_package( OpenCV REQUIRED )add_executable( reco faceReco.cpp )link_directories( /home/pi/libfacerec/bytefish­libfacerec­e1b143d)target_link_libraries( reco /home/pi/libfacerec/bytefish­libfacerec­e1b143d/libopencv_facerec.a $OpenCV_LIBS )

wget http://raufast.org/download/faceReco.cppcmake .make.

108

Page 109: MrRsPiManualGuide-KernelPanic

FINALLY...

Run the damn thing from X (on the PI)

./reco faces.csv 1 5500

I will do some further testing on this and get some photos of myself and perhaps another individual and see what I canget working. An interesting idea / concept though! It was able to recognise at least one picture of Angelina Jolie Iused! Further testing with ipad to follow!

Removing the IR Filter on The Eyetoyhttp://createdigitalmotion.com/2009/08/trick­out­your­ps3­eye­webcam­best­cam­for­vision­augmented­reality/

This video demonstrates how to disassemble, remove IR Filter and re­assemble!)

Using Multiple Cameras with MotionTo do this you need to add a thread per camera.

sudo nano /etc/motion/motion.confthen at the bottom add...

thread /etc/motion/thread1.confthread /etc/motion/thread2.conf

etc...You need a config (conf) for each camera you intend to use.

create the thread1.conf file usingsudo nano /etc/motion/thread1.conf

It only really needs the following code.

videodevice /dev/video0text_left USBWebcam­1target_dir /home/ndmaque/motion/images/webcam2webcam_port 8081

Similarly create thread2.confsudo nano /etc/motion/thread2.conf

videodevice /dev/video1text_left USBWebcam­2target_dir /home/ndmaque/motion/images/webcam2webcam_port 8082

Notice how they have different ports so you can access them seperately, (note the separte devices!)

109

Page 110: MrRsPiManualGuide-KernelPanic

http://www.lavrsen.dk/foswiki/bin/view/Motion/MotionGuideOneLargeDocumenthttp://through­the­interface.typepad.com/through_the_interface/2012/09/creating­a­motion­detecting­security­cam­with­a­raspberry­pi­part­2.html

Retaliation (USB Rocket MOD!)

Rocket Launcher ­ http://itr8r.tumblr.com/post/31840231144/raspberry­pi­retaliationRetaliation ­ https://github.com/codedance/Retaliation#readme

Retaliation in Scratch http://itr8r.tumblr.com/post/40413865818/scratch­retaliation

N.B. You can plug the rocket launcher into the Pi, but it will probably error, or try a HUB, but it will needsome power going to it. 1 amp? Fire FAILS on my setup (I suspect due to it being knackered or lack ofpower!) Will test at school when get chance!

The python­usb yum module is not new enough to work with the retaliation code. Instead download thesource for 1.0 from pyusb.

Untar into a directory, then install pyusb with:sudo apt­get install python libusb­0.1­4git clone https://github.com/walac/pyusb.gitcd pyusbsudo python setup.py install

Step 2 ­ Download retaliation:sudo wget https://raw.github.com/codedance/Retaliation/master/retaliation.pysudo chmod +x retaliation.py

Step 3 ­ Connect and testConnect the missile launcher (I used a powered USB hub) and test with a command such as

sudo ./retaliation.py zerosudo ./retaliation.py left 1000

Step 4 ­ Modify the script as needed for your office & enjoy

Retaliation Modification to Script. (TO REDO to use KEYBOARD!)

110

Page 111: MrRsPiManualGuide-KernelPanic

TVHead Test for XBMC

I got a August DVB­T205 TV Capture USB Stick / Dongle. Heard they are compatible with RPietc, and fancied giving LiveTV / PVR / Streaming a go.

I did some general reading around these links.https://github.com/ambrosa/DVB­Realtek­RTL2832U­2.2.2­10tuner­mod_kernel­3.0.0http://www.raspberrypi.org/phpBB3/viewtopic.php?t=18090http://forum.stmlabs.com/showthread.php?tid=2912http://www.raspberrypi.org/phpBB3/viewtopic.php?t=18090http://www.packtpub.com/article/using­pvr­with­raspbmc

Getting the device recognised in Linux.

First ensure some dependants are installed (in case of compiling etc)sudo apt­get install make gcc pkg­config libavahi­client­dev libssl­dev build­essential

Get the August DVB­T205 ­ Driver

https://mega.co.nz/#!nZNkRJzS!Mx3BSGwU6BQLFUVkuY4ce0h7IDtKSELDc5USfKsyg3k

I was unable to WGET this file as it’s a MEGA load (one you have to click through on and supply acatchpa.

I then WinSCP’d Driver to Pi.

Untar it.sudo tar ­xvf <filename>

Copy to correct folder (you can use mv </path/filename> </newpath/filename>), but I think I did in inWinSCP (moved the .ko file)

/lib/modules/3.6.11/kernel/drivers/media/dvb/dvb­usb/

Refresh the drivers in Linux to pick up this change usingsudo depmod ­a (to update all the drivers etc)

reboot.

NOTE: This Dongle ONLY seemed to work if plugged into the PI!!!

TVHead backend ­ http://wiki.xbmc.org/index.php?title=PVR/Backend/Tvheadend

Access TVHead using ­ http://<Pi IP Address>:9981 111

Page 112: MrRsPiManualGuide-KernelPanic

So far managed to get TV channels tuned, EPG working (via web browser) and then record aprogram in ts(standard format) or MKV that seems better!

Some detail here about watching LiveTV that does not seem to work.http://forum.xbmc.org/showthread.php?tid=148646&page=34

Stuff still to do, get wireless working with Lloyds USB Dongle?Add a HDD and try recording to it, set this up as a Samba Share!!!

112

Page 113: MrRsPiManualGuide-KernelPanic

SOFTWARE 109

GitHubs ­ Why They Rock!

GitHubs are repositories of files / software that are created / used when serveral people are working on /updating a single software project. Other times this can just be a collection of file, e.g. Python scripts of aparticular type / collection. Some times you might want to get / collect / grab the GIT so that you cancompile your own version, or use the collection.

Firstly install the drivers and software to deal with GitHubs

sudo apt­get install git­core

It can often be handy to CLONE an entire GitHub!!!

How to clone your repo to your local machine ?(in git terminology it’s called “checkout“)First you need to find your repo address. It can be find on your GitHub repo page:

Copy the address in the box ([email protected]……/….git)

Open the terminal and go to the folder where you want to have your git to be located.

Type command:git clone ADDRESS YOU COPIED

to update navigate to the right folder and use.

git pull

When you see a new script posted on the blog, to get it on your raspberry pi all you need to do is run thefollowing command to get the latest updates:

1. Run “git fetch origin” to download the latest updates2. Run “git merge origin/master” to update the files in your current directory with them.

git clone git://github.com/??????????

113

Page 114: MrRsPiManualGuide-KernelPanic

Compiling Your Own Version of Software (Roll your own!)

GrabFirstly Grab the software package you want (often Tar.gz, a Tar file (tape archive) that has beencompressed using Gzip)use the command wget <filepath> to grab the Tar.gz

wget <full filepath inc http://>

extract the tar.gz to a path usingtar ­xvf <filename>

delete the original filerm <filename.tar.gz>

enter the extracted foldercd <filename>

ConfigureNow to Configure your package use

sudo ./configure

MakeNow MAKE the package (this often takes ages!)

sudo make

Make Install

Now do a MAKE INSTALL, this installs the software for your usages?sudo make install.

114

Page 115: MrRsPiManualGuide-KernelPanic

SOFTWARE ­ Interfacing 111

Pi­Wall (WORKING!)http://www.piwall.co.uk/information/10­create­your­own­gpl­movie­piwall

This codes should allow you to play back a video on a video wall of seveal screens!(start with x4!)

The setup must consist of a Master that effectively broadcasts to the slave ‘tiles’41 is top left42 top right43 bottom left44 bottom right

I assume the first 4 refers to the fact it’s a x4 screens. The each one is addressed individually.

Setting up the units.

install libav­tools on each pi.

sudo apt­get install libav­tools

Copy pwlibs1_1.1armhf.deb and pwomxplayer_20130815_armhf.deb to the home directory.

extract dpkg the both.

sudo dpkg ­i /home/pi/pwlibs1_1.1_armhf.deb

sudo dpkg ­i /home/pi/pwomxplayer_20130815_armhf.deb

Network configuration

Each Pi needs to have a different IP address (obviously!) and you almost certainly want these to bestatically assigned. For this Guide we'll assume a private address range of 192.168.0.* if you need to useanother set of addresses, then adjust accordingly.

In a production environment, you may want to connect the master Pi to an existing network ­ this is bestachieved by adding a USB ethernet or WiFi adapter as a second interface to the master. Configuring thissecond network interface is beyond the scope of this document.

In order for the master to communicate efficiently with the tiles, it uses multicast addressing (where eachpacket sent by the master is received by all the tiles). The rules and guidelines for using multicastaddresses are complex; if the network is completely private then it doesn't really matter, but in this Guide

115

Page 116: MrRsPiManualGuide-KernelPanic

we'll use one of the "administratively scoped" addresses, 239.0.1.23. If you plan to use a real, sharednetwork, then speak to your network administrator to agree an address.

If you are using a Linux PC as your master and don’t want to permanently alter your network configurationthen execute the following commands after you have connected to the private PiWall network.

“sudo ifconfig eth0 192.168.0.??? netmask 255.255.255.0 up”“sudo route add ­net 224.0.0.0 netmask 240.0.0.0 eth0”

Note that this enables the full multicast address range, even though we'll only be using a single addresswithin that range.

To make this routing permanent on a Raspberry Pi master or tile, edit the network interface stanza in "/etc/network/interfaces", e.g. iface eth0 inet static

address 192.168.0.??? netmask 255.255.255.0 up route add ­net 224.0.0.0 netmask 240.0.0.0 eth0

We usually use an address of 100 for the master and number the tiles from 1, upwards.

Testing the software

First test a tile to ensure that it is working correctly. Start by connecting a keyboard to the tile and

attaching a USB pen drive that contains a movie that the standard omxplayer can display. Find the path of

the USB pen drive, from the command line type "df" this will list all the file systems on your Pi. In the right

hand column, look for the entry that has a path that starts with "/media/", on my system it is

"/media/18DA­7CE4". Prepend this path to the "movie.avi" argument in the following commands. Confirm

that the movie can be played by the standard omxplayer provided with the Raspbian image by typing

"omxplayer movie.avi" at the command prompt. Next verify that pwomxplayer can play the movie by

typing "pwomxplayer movie.avi". Finally check that pwomxplayer can show a section of the video by

typing "pwomxplayer ­­tile­code=42 movie.avi" which should display just the top right corner of the original

movie, but magnified to fill the whole screen.

Now you're ready to test the master in conjunction with one or more tiles. On each Raspberry Pi tile type

"pwomxplayer ­­tile­code=$n udp://239.0.1.23:1234?buffer=1200000B" (where $n=41 is the top left, 42 is

the top right, 43 is the bottom left and 44 is the bottom right for a 4 screen PiWall). On the master type

"avconv ­re ­i movie.avi ­vcodec copy ­f avi ­an udp://239.0.1.23:1234"

(possible with output sound?

avconv ­re ­i movie.avi ­vcodec copy ­f avi ­an udp://239.0.1.23:1234 –enable­outdev=ALSA

116

Page 117: MrRsPiManualGuide-KernelPanic

The "­­tile­code" configuration doesn't provide bezel compensation, for that you will need to provide a

detailed PiWall configuration file. That will be the subject of a further guide to be published later this week.

Looping an Video on the screens.On the Raspberry Pi master just create a simple bash script (you could save it as "forever") ...

while truedo avconv ­re ­i movie.avi ­vcodec copy ­an ­f avi udp://239.0.1.23:1234done

Don't forget to either make the script executable or run it by prepending the name of the bash script with sh, eg "shforever".

Multicasting Input from the Pi Camera (untested!)In theory it should be possible to PIPE the output of the Pi Camera to display on your video wall usingsomething like this.

raspivid ­o ­ ­t 10000 ­vf | avconv ­re ­r ­ ­vcodec copy ­f avi ­an udp://239.0.1.23:1234

The ­t 10000 might not be needed (until tested!)The ­vf is the vertical flip of the camera output.

117

Page 118: MrRsPiManualGuide-KernelPanic

Fritzinghttp://fritzing.org/forum/thread/1338/

PI­CarThe Pi­Car project like many others now seem to be doing controls a remote controlled car using theremote hacked to work with the GPIO pins on the RPi. There’s even a python script that can be run sothat you can control the car through Scratch.

http://pi­cars.com/http://pi­cars.com/under­the­bonnet/http://pi­cars.com/2012/12/23/pi­cars­and­scratch­driving­lesson­1/­ this page guides you on how to create the Python file needed to hook intoScratch.

118

Page 119: MrRsPiManualGuide-KernelPanic

Using Twitter

http://blog.kugelfish.com/2012/08/kugelbot­or­what­to­do­with­raspberry­pi.htmlhttps://pypi.python.org/pypi/twitter/

The projects listed here all require you to have a twitter account. I setup a seperate account soI could do Pi Testing.

@AMC_PIletmein (with a few numbers) ­ Add this to keepass and remove.

Once you have signed up you need to log into https://dev.twitter.com, this will allow you access tocreating apps around / using twitter. You’ll need to create a new APP.

You will need to then carry out the following steps in order to get access keys and consumer keys whichwill allow us to authenticate the twitter account and application without having to keep entering in logindata. This uses the OAuth protocol which you can find out more about using google!

1. Select create a new application2. Enter name, description, website3. Select Yes I agree to the terms and conditions4. Enter captcha information and click submit

You will see that by default the access level is set to read only. We will need to change this to read/writeto enable us to push tweets out to the world. To change this settings carry out the following steps.

1. Select settings along top menu tabs2. Under application type select Read and Write3. Ensure that “Allow this application to be used to Sign in with Twitter” is checked4. Click the update this twitter applications settings button at the bottom of the page

If you now return to the Details tab you will see a number of special keys which include, consumerkey/secret and access token/secret. Leave the webpage open as we will need all of this information in aminute to start tweeting.

Once you have done so there are 4 keys bits of info you need for most of these projects.

Consumer KeyConsumer SecretAccess TokenAccess Token Secret

These are just random strings of letters / numbers, but you will need them to do any twitter work.Also once you have created your APP (on the twitter site) you’ll have to change the settings ofthe app to either ‘read only’ or ‘read / write’. If you change the settings of the app the accesstoken and access token secret will change. I found this out! You can use the same app setup inmost of your Pi Projects.

119

Page 120: MrRsPiManualGuide-KernelPanic

Creating An Array of Followers (Partly Tested)http://raspi.tv/2013/how­to­create­a­twitter­app­on­the­raspberry­pi­with­python­tweepy­part­1

This script will justlook at youraccount, work outall your followersand select one atrandom!!!

#!/usr/bin/env python2.7# twitterwin.py by Alex Eames http://raspi.tv/?p=5281import tweepyimport random

# Consumer keys and access tokens, used for OAuthconsumer_key = 'copy your consumer key here'consumer_secret = 'copy your consumer secret here'access_token = 'copy your access token here'access_token_secret = 'copy your access token secret here'

# OAuth process, using the keys and tokensauth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)

# Creation of the actual interface, using authenticationapi = tweepy.API(auth)

follow2 = api.followers_ids() # gives a list of followers idsprint "you have %d followers" % len(follow2)

show_list = str(raw_input("Do you want to list the followers array?"))if show_list == ('y' or 'yes' or 'Y' or 'Yes' or 'YES'): print follow2

def pick_winner(): random_number = random.randint(0, len(follow2)­1) winner = api.get_user(follow2[random_number]) print winner.screen_name, random_number

while True: pick = raw_input("Press Enter to pick a winner, Q to quit.") if pick == ('q' or 'Q' or 'quit' or 'QUIT' or 'Quit'): break pick_winner()

120

Page 121: MrRsPiManualGuide-KernelPanic

Creating a Python Script that can Tweet (Tested)

Create a simple python script calledSillyTweeter.py.

Use sudo chmod +x to make itexecutable.

Run usingpython SillyTweeter.py ‘This text willbe output to twitter’

N.B. the …... are to keep my tokens safe!Copy and paste your own from Twitter!

#!/usr/bin/env pythonimport sysfrom twython import TwythonCONSUMER_KEY = 'tRrx71zfMENmCV1t......'CONSUMER_SECRET = 'eMoBaVi8OkoC3j6aDszc4VjXzeuddxV577......'ACCESS_KEY = '2161868077­KlG5aiRfLuWrweKMpPPO7RFxapWzdHeEV......'ACCESS_SECRET = '4HinfnCRL74IRG09c3JCWcy2gcl5QwiBJmbNqbD......'

api =Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)

api.update_status(status=sys.argv[1])

Creating a Python Script that can Tweet Images (Tested)

Call the program like you did thelast example,

python TweetPhoto.py‘/home/pi/twitter/test.jpg’ ‘AnyText you want here’

only instead of a message addthe path to file you with to output!

#!/usr/bin/env pythonimport sysfrom twython import Twythonimport os

CONSUMER_KEY = 'tRrx71zfMENmCV1t…...'CONSUMER_SECRET = 'eMoBaVi8OkoC3j6aDszc4VjXzeuddxV577…...'ACCESS_KEY = '2161868077­KlG5aiRfLuWrweKMpPPO7RFxapWzdHeEV…...'ACCESS_SECRET = '4HinfnCRL74IRG09c3JCWcy2gcl5QwiBJmbNqbD…...'

photo = open(sys.argv[1],'rb')api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)

#api.update_status(status=sys.argv[1])api.update_status_with_media(media=photo, status=sys.argv[2])

121

Page 122: MrRsPiManualGuide-KernelPanic

Create a Python Script that can Tweet Images Via Raspicam, watermark them and TweetThem

sudo apt­get install python­pip

…and then enter:

sudo pip installhttps://github.com/ashtons/picam/zipball/master#egg=picam

import picami = picam.takePhoto()i.save(‘/home/pi/test.jpg’)

You can use this command, but Icould not work out how to flip theimage, so instead I canlled the bashcommands within the script. Thisallowed the use of imagemagick tooto watermark it!

More on Time in Python

http://www.cyberciti.biz/faq/howto­get­current­date­time­in­python/

#!/usr/bin/env pythonimport sysimport timeimport picamfrom twython import Twythonimport os

CONSUMER_KEY = 'tRrx71zfMENmCV1tkvVT4Q'CONSUMER_SECRET = 'eMoBaVi8OkoC3j6aDszc4VjXzeuddxV5776BApo4'ACCESS_KEY = '2161868077­KlG5aiRfLuWrweKMpPPO7RFxapWzdHeEV7Sqx75'ACCESS_SECRET = '4HinfnCRL74IRG09c3JCWcy2gcl5QwiBJmbNqbD7wXoRx'

date_bit=time.strftime("%Y_%m_%d")

photopath = '/home/pi/twitter/'+ date_bit + '_photo.jpg'print ('Going to save file as: ' + photopath)

os.system('raspistill ­o temp.jpg ­vf')print ('About to convert photo!')

os.system('composite CTI_Pi_Big.png temp.jpg ­gravity south '+ photopath)print ('Just added a watermark')

uploadphoto = open(photopath,'rb')api =Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)##api.update_status(status=sys.argv[1])api.update_status_with_media(media=uploadphoto, status='PiCam Test Final')

Creating a Python Script to Output System Infohttp://c­mobberley.com/wordpress/index.php/2013/04/26/raspberry­pi­connect­to­twitter­account­using­tweepy­installation­and­tweet­cpu­temperature­example/

It is possible to adapt this script tooutput just about anything via theapi! Could be interesting.

#!/usr/bin/env pythonimport osimport sysimport tweepy

CONSUMER_KEY = '*****YOUR DATA******'CONSUMER_SECRET = '*****YOUR DATA******'ACCESS_KEY = '*****YOUR DATA******'ACCESS_SECRET = '*****YOUR DATA******'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)api = tweepy.API(auth)

cmd = '/opt/vc/bin/vcgencmd measure_temp'line = os.popen(cmd).readline().strip()temp = line.split('=')[1].split("'")[0]

122

Page 123: MrRsPiManualGuide-KernelPanic

api.update_status('My Current Processor Temperature: '+ temp + ' C')

Tweeting on a Set Interval(Using the above example)To edit the root cron file you must run the following command.

sudo crontab ­eIt is very important to ensure the sudo command is used!Once you are in the file you can then add the following line, just change the directory to point to whereyour file is saved.

*/60 * * * * python /home/pi/Twitter/TweetTemp.py

Read Out Tweets (Untested)http://www.stuffaboutcode.com/2012/10/raspberry­pi­python­talking­twitter.html

This process uses Google’s API to read out Tweetsout loud!

Install python­oauthI used leah's python oauth module to authenticate withtwitter.

Install distributeIf you have never installed python modules before you aregoing to need to install the python setup tools, module,distribute, see blog post, python ­ installing modules, forinfo on how to do this.

Install git­coreIn order to get the code from github you need to installgit­core tools.

sudo apt­get install git­coreGet the code from git

git clonehttps://github.com/leah/python­oauth.gitInstall the module

cd python­oauthsudo python setup.py installInstall pycurlpycurl is used to connect to the twitter streams.

sudo apt­get install python­pycurlInstall mplayermplayer is used to output the audio stream.

sudo apt­get install mplayerCreate talking twitter client program

nano ttc.py

#!/usr/bin/env python# An experimental talking twitter client forthe Raspberry Pi# written in Python, by Martin O'Hanlon# www.stuffaboutcode.comfrom oauth.oauth import OAuthRequest,OAuthSignatureMethod_HMAC_SHA1from hashlib import md5import json, time, random, math, urllib,urllib2, pycurl, subprocess, sys# twitter oauth keys, get your fromdev.twitter.comCONSUMER_KEY = 'consumer key'CONSUMER_SECRET = 'consumer secret'ACCESS_TOKEN = 'access token'ACCESS_TOKEN_SECRET = 'access token secret'# function to download a file from a url, usedfor testingdef downloadFile(url, fileName): fp = open(fileName, "wb") curl = pycurl.Curl() curl.setopt(pycurl.URL, url) curl.setopt(pycurl.WRITEDATA, fp) curl.perform() curl.close() fp.close()# returns the appropriate google speech urlfor a particular phrasedef getGoogleSpeechURL(phrase): googleTranslateURL ="http://translate.google.com/translate_tts?tl=en&" parameters = 'q': phrase data = urllib.urlencode(parameters) googleTranslateURL = "%s%s" %(googleTranslateURL,data) return googleTranslateURL# function to download an mp3 file for aparticular phrase, used for testingdef downloadSpeechFromText(phrase, fileName): googleSpeechURL =getGoogleSpeechURL(phrase)

123

Page 124: MrRsPiManualGuide-KernelPanic

print googleSpeechURL downloadFile(googleSpeechURL, fileName)# output phrase to audio using mplayerdef speakSpeechFromText(phrase): googleSpeechURL =getGoogleSpeechURL(phrase)subprocess.call(["mplayer",googleSpeechURL],shell=False, stdout=subprocess.PIPE,stderr=subprocess.PIPE)# class for managing tokensclass Token(object): def __init__(self,key,secret): self.key = key self.secret = secret def _generate_nonce(self): random_number =''.join(str(random.randint(0, 9)) for i inrange(40)) m = md5(str(time.time()) +str(random_number)) return m.hexdigest()# talking twitter clientclass TalkingTwitterStreamClient: def __init__(self, streamURL): self.streamURL = streamURL self.buffer = "" self.conn = pycurl.Curl() self.conn.setopt(pycurl.URL,self.streamURL) self.conn.setopt(pycurl.WRITEFUNCTION,self.on_receive) self.conn.perform() def on_receive(self, data): sys.stdout.write(".") self.buffer += data if data.endswith("\n") andself.buffer.strip(): content = json.loads(self.buffer) self.buffer = "" #debug ­ output json from buffer #print content if "friends" in content: self.friends =content["friends"] if "text" in content: print u"0[user][name]:0[text]".format(content).encode('utf­8') speakSpeechFromText(u"A tweetfrom 0[user][name]".format(content)) #downloadSpeechFromText(u"A tweet from0[user][name]".format(content),"./tweet.mp3")speakSpeechFromText(u"0[text]".format(content))#downloadSpeechFromText(u"0[text]".format(content), "./tweet.mp3")# get the url needed to open the twitter userstream, including signature afterauthenticationdef getTwitterUserStreamURL(): STREAM_URL ="https://userstream.twitter.com/2/user.json" access_token =Token(ACCESS_TOKEN,ACCESS_TOKEN_SECRET)

124

Page 125: MrRsPiManualGuide-KernelPanic

consumer =Token(CONSUMER_KEY,CONSUMER_SECRET) parameters = 'oauth_consumer_key': CONSUMER_KEY, 'oauth_token': access_token.key, 'oauth_signature_method': 'HMAC­SHA1', 'oauth_timestamp':str(int(time.time())), 'oauth_nonce':access_token._generate_nonce(), 'oauth_version': '1.0', oauth_request =OAuthRequest.from_token_and_callback(access_token, http_url=STREAM_URL, parameters=parameters) signature_method =OAuthSignatureMethod_HMAC_SHA1() signature =signature_method.build_signature(oauth_request, consumer, access_token) parameters['oauth_signature'] = signature data = urllib.urlencode(parameters) return "%s?%s" % (STREAM_URL,data)# Run Talking Twitter Clientclient =TalkingTwitterStreamClient(getTwitterUserStreamURL())#some useful debug commands, comment outrunning the client and uncomment the command#get twitter stream url, including oauthsignature#print getTwitterUserStreamURL()#download a speech file from google#downloadSpeechFromText("hello, how are youtoday", "./downloadedFile.mp3")#output phrase to audio#speakSpeechFromText("hello, how are youtoday")#start talking twitter client

Tweeting Webcam Pics (Part Tested)http://www.makeuseof.com/tag/how­to­build­a­raspberry­pi­twitter­bot/

Now let’s make something really useful; we’re going tweet webcam pics. Thankfully, Twython supportsthe API function update_status_with_media, which makes things rather simple.

Plug a USB webcam into your device and check ifit’s been recognised with the command: sudo ls /dev/video*

if you see video0, you’re in luck. I used aPlaystation 3 PSEye cam and it worked just finewithout any additional legwork.

We’re also going to use the pygame libraries to

#!/usr/bin/env pythonimport sysfrom twython import Twythonimport os

import pygameimport pygame.camerafrom pygame.locals import *

pygame.init()pygame.camera.init()cam = pygame.camera.Camera("/dev/video0",(640,480))cam.start()image = cam.get_image()

125

Page 126: MrRsPiManualGuide-KernelPanic

take a picture

Initialise the camera, then call using cam (setup touse /dev/video0, set res to 640x480)

In short, you’ve initialised the webcam at aspecific resolution (you may need to adjust this isit’s a really old cam), snapped a picture, andsaved it as a jpg. We’re just going to overwrite thesame webcam.jpg each time the app is run.Finally, adjust the update_status line to read:

photo = open('webcam.jpg','rb')api.update_status_with_media(media=photo,status='My RPi be tweeting images now => ')

Similar to the SillyTweeter example, this jus usesthe api to post a picture. Complete code for thisexample is here.

pygame.image.save(image,'webcam.jpg')

CONSUMER_KEY = 'jmyBuGoaMKS05x85qFCNRw'CONSUMER_SECRET ='U2Ay9nv0CxdopruNk4DR9aRDyhry98ML7mYMCStdaI'ACCESS_KEY ='354540970­nMZVfXJqTbEP8ddj3jwRNs8UMXlZapZpbxiaLg0v'ACCESS_SECRET ='L9MnMvXLROx76CT9NzjR7PFrtMcIb1U9venQwK1ygY'

photo = open('webcam.jpg','rb')api =Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)api.update_status_with_media(media=photo, status='My RPi betweeting images now => ')

­ Reading Tweets from a #Taghttp://fuenteabierta.teubi.co/2013/01/controlling­raspberry­pi­via­twitter.html

­Creating a TweetBothttp://www.makeuseof.com/tag/how­to­build­a­raspberry­pi­twitter­bot/

126

Page 127: MrRsPiManualGuide-KernelPanic

SOFTWARE ­ GAMES 123

A good list of Games that run on the Pihttp://www.raspberryconnect.com/raspbian­packages­list/item/65­raspbian­games

SDL DispManxThis will give you best emulation and graphics blitting around, it’s not a standard version of SDL, but isenhanced, works with Q3, DGen and SNES (not sure about emulation station though!)

Grab copy of the GitHub ­git clone git://github.com/vanfanel/SDL12­kms­dispmanx.gitcd SDL<tab>./autogen.sh

run the MAC_ConfigureDISPMANX.sh scriptsudo ./MAC_ConfigureDISPMANX.sh

Edit the Makefilesudo nano Makefile

and add to CFLAGS)­I/opt/vc/include/interface/vmcs_host/linux

Finally Make and Install.

sudo makesudo make install

(Just re­install default libsdl1.2 and everything should be back to normal)

sudo apt­get install ­­reinstall libsdl1.2debian

127

Page 128: MrRsPiManualGuide-KernelPanic

Q3 Arena on RASP PI (Build)Compile away (this will take over an hour!)http://www.raspbian.org/RaspbianQuake3

1. Make sure you're up-to-date:

2. sudo apt­get update sudo apt­get dist­upgrade

Reboot.

3. Install required packages: sudo apt­get install git gcc build­essential libsdl1.2­dev

4. Download the Quake 3 source code:

5. mkdir ~/src cd ~/src git clone https://github.com/raspberrypi/quake3.git cd quake3

6. Edit build.sh in quake3 directory:

7. change line 8 to this: ARM_LIBS=/opt/vc/lib change line 16 to this: INCLUDES="­I/opt/vc/include ­I/opt/vc/include/interface/vcos/pthreads" comment out line 19: #CROSS_COMPILE=bcm2708­

8. Do a ./build.sh9. Wait for compilation to finish, takes about 1 hour on RasPi.

10. Find copies of the following somewhere (other guides will show you) and place inbuild/release­linux­arm/baseq3:

pak0.pk3, pak1.pk3, pak2.pk3, pak3.pk3, pak4.pk3, pak5.pk3, pak6.pk3, pak7.pk3, pak8.pk3i. Update your permissions for directFB access:

ii. sudo usermod ­a ­G video [your_username]1. Log out, log back in. This will allow you to run game as non-root. Works with other

directFB/SDL based stuff, too.

11. If you do not intend to keep Quake 3 source code, you may reorganize files as suggested bythis thread on RasPi Forum.

Copy the contents of/home/src/quake3/build/release­linux­arm/

to/home/pi/quake3

12. Run ./ioquake3.arm. Shoot things.

Assuming you're still root, start the game with `./ioquake3.arm`. Start a game, run around see how it feels. Hopefullyit all works, and it created the correct directories for you. Navigate to `/root/.q3a/baseq3` and run

Start the game again, and the autoexec.cfg should execute automatically. If you'd like to try the other configs, dropdown the console with the tilde key `~ and type `exec low.cfg` or any of the others.

128

Page 129: MrRsPiManualGuide-KernelPanic

Quake 3 Quick Install ­ School Build(estimated install time around 5 minutes!)ensure have apt­get update && apt­get upgrade and upgraded firmware???cd ~wget http://www.raspians.com/uploads/quake3.zipunzip quake3.ziprm quake3.zipcd quake3

#This will not work at school as DROPBOX is blocked!!! GRRR.... AMAZING USB AGAIN!wget http://dl.dropbox.com/u/1816557/Q3%20Demo%20Paks.zipunzip Q3\ Demo\ Paks.ziprm Q3\ Demo\ Paks.zipcd ~sudo chmod +x /home/pi/quake3/ioquake3.arm

School Build Error solutions

if quake3 bombs out with an error message like 'SDL_Init()' 'Unable to open mouse'. This will effect otherDirectFB applications/games that need a mouse.

Work around either to run with no mouse.CODE: SELECT ALL

export SDL_NOMOUSE=1

OR fix the permissions so non­root uses can access /dev/input/mice and /dev/input/mouse0 as follows.Create new file in "/etc/udev/rules.d/99­input.rules"CODE: SELECT ALL

# file /etc/udev/rules.d/99­input.rules

KERNEL=="mice", NAME="input/%k", MODE="664", GROUP="input"

KERNEL=="mouse*", NAME="input/%k", MODE="664", GROUP="input"

Add a new group and add your user(s) to it (my login is just 'pi')CODE: SELECT ALL

groupadd input

usermod ­a ­G input piRestart the sound­ Update: If you are getting static try bringing down the console (tilde by default) and entering"snd_restart" (no quotes) and press enter. It will re­init the sound subsystem and can clear it up in my build.

Sound through headphonessudo amixer cset numid=3 1

129

Page 130: MrRsPiManualGuide-KernelPanic

Show FPS in Game#To show FPS use ~ on the menu and typecg_drawFPS "1"

Quake 3 Config File Guidehttp://www.gamesurge.com/pc/hardware/tweaks/q3atweak.shtml

Full version of Quake 3.Yes, if you copy pak0.pk3 from your cd to the base3q directory on the Pi, you will unlock the full game providing youenter the CD key. Multiplayer works a treat! (around 480 MB). Ensure when you copy that you rename / overwrite theexisting pak0.pak3 file, you might need to rename the old one (for backup) and make the other one lower caps!

Openaren on the Pi (Not via Pi Store)cd ~sudo apt­get install openarenasudo apt­get install libcurl3­gnutls

Q3 ­ Models, Levels, Maps and Extrashttp://ioquake3.org/extras/models/ ­ Modelshttp://lvlworld.com/ ­ Levelshttp://www.quakeunity.com ­ Mod Packs / Skins / Textures etc.http://www.moddb.com/games/quake­iii­arena ­ Quake 3 Info.

130

Page 131: MrRsPiManualGuide-KernelPanic

Q3 Console ManualConsole Basics

First things first: to access the console, press the tilde ("~") key at any time (even from the main menus).

From there, put a "/" in front of any command you want to execute, or Q3 will interpret it as a simple chat message.

<TAB COMPLETE WORKS!>

Cheats

A few select commands are considered "cheats", and can only be activated under certain conditions. To activate

cheats, type:

/sv_cheats 1

from the console. From there, load any map using the /devmap command. For instance:

/devmap q3dm15

will load "Demon Keep" with cheats enabled. You can only use cheats when using the "/devmap" command -- using

the standard "/map" command will not allow cheats.

Once you've got cheats enabled, some other useful commands:

/god - "God" mode. You are invincible and cannot be hurt by weapons.

/noclip - "no clip" mode. You can fly through walls and floors, and basically go anywhere you want in the level. (Great

for taking screenshots.)

Console Commands

There are a LOT of commands and variable you can play with in Quake III. These only begin to scratch the surface,

but are some of the more useful and interesting ones. Keep in mind that some of these can only be used while in

"cheat" mode, and other settings may be locked on certain servers, in the interest of keeping al players equal.

If you want to see the complete lists:

/cmdlist - will produce a list of commands

/cvarlist - will produce a list of console variables

You can also output this to a text file by typing

/condump filename.txt

This will output the contents of the console to a text file in the Quake3/baseq3 directory.

/reconnect

Will reconnect you to the last server you were connected to. Useful if Q3 dumps you to the main menu during a map

change for no apparent reason.

/bindlist

Will produce a list of all currently bound commands.

/bind

One of the most basic commands, this will "bind", or assign a command to a particular key.

Usage: /bind " "

Example: /bind space "+zoom"

/say

Will produce a chat message onscreen. Used with the /bind command, this is an easy way to set up chat messages.

Example: bind F5 say "ouch! that hurt!"

Do NOT abuse this command. Spamming servers with lots of useless chat is an easy way to get kicked off a server.

/say_team

Allows you to send private messages to your teammates. VERY useful for Capture the Flag matches.

Example: bind I say_team "Defense: Incoming Enemy!"

/messagemode 2

Bind this command to a key to enter "team chat" mode. Anything you type after this command will only be sent to

your teammates.

/kill

Will cause you to commit suicide. A handy way to lose a frag.

Viewing Options.

/cg_drawFPS (deafult: 0)

Will display your framerate in the upper right of the screen. (0=off, 1=on)

/cg_drawTimer (default: 0)

Will display elapsed game time in the upper right of the screen. (0=off, 1=on)

/cg_gibs (default: 1)

131

Page 132: MrRsPiManualGuide-KernelPanic

This activates the splatter that is so much a part of shooters these days. Setting to "0" can help keep things clean in

heavily trafficked games. (0=off, 1=on)

/cg_simpleItems (default: 0)

Will turn all items into 2D sprites. Can help improve performance on slower systems. (0=off, 1=on)

/cg_drawTeamOverlay (default: 0) Will toggle the very useful "team overlay" on your HUD, which will allow you to

see the health, armor, and current selected weapon of all your teammates. (0=off, 1=on)

Useful Server Commands

These are some useful commands you might want to use when running a server. Some of the variables require the

map be restarted before taking effect; use the "/map_restart" command to accomplish this.

/serverinfo

Will produce a list of current server settings.

/map

Will load any map with your current server settings.

/map_restart

Will reload current map. You may have to use this command before various server settings can take effect.

/g_gametype

Will display or set the current game type:

"0" - free-for-all DM

"1" - Tournament 1-on-1

"2" - Single-Player

"3" - Team Deathmatch

"4" - Capture the Flag.

Example: /g_gametype "3"

/sv_maxclients

Will display or set the maximum # of players on a

Example: /sv_maxclients "10"

/timelimit

Displays or sets the server time limit.

/fraglimit

Displays or sets the server frag limit.

/bot_minplayers

This command can be used to keep a server populated with random bots when empty. Bots are kicked when players

join.

Example: /bot_minplayers "4"

/addbot

Can be used to manaully add bots to a game.

/kick

Will kick any specified player from the game.

/g_gravity (default: 800)

Set or display the world gravity with this variable. (Lower number is less gravity.)

/g_speed (default: 320)

Set or display player running speed with this variable. Setting to 1000 will produce highly interesting results.

If you're looking for more detailed information on what you can do with your config or the console commands, then

head over to The Bind: Arena -- they have everything you're looking for in console and config commands!

132

Page 133: MrRsPiManualGuide-KernelPanic

Quake 2 on the Pi.Need a fresh install of Wheezy not Squeeze//Get the latest build ­ http://deponie.yamagi.org/quake2/debs/source/ (the tar.gz)Extract it.Go get the Quake2 demo (Unzip the EXE, rescue the following files and put onto USB)ftp://ftp.idsoftware.com/idstuff/quake2/q2­314­demo­x86.exe

­ Unzip this file (again, it's a self­extracting zip file).­ Create a new "quake2/" directory with a "baseq2/" sub­directory and put the "pak0.pak" and the"players/" sub directory, you can find them within the unzipped files (in Install/Data/baseq2/), in your"baseq2/" directory. Nopatching is needed for the demo, in fact it would break it.

Install the following using apt­get install ... libsdl1.2­dev libvorbis­dev libogg­dev zlib1g­dev libjpeg8­dev

MAKE ­ Goto the GITHUB, find the updated version, save the RAW over the top ­https://github.com/reefab/yquake2yq2.cfg ­ Goto https://github.com/reefab/yquake2 then stuff, again save the RAW in the base2q folderready for later.

133

Page 134: MrRsPiManualGuide-KernelPanic

Installing Quake 2 on PiQuake 2 -https://github.com/reefab/yquake2/blob/a07e3a605a9f1765b5950da5271df33653245c6b/README.mdMust run Quake 2 as Root.cd /home/pi/quake2./quake2Quake 2 FIX???sudo ln ­fs /opt/vc/lib/libEGL.so /usr/lib/libEGL.sosudo ln -fs /opt/vc/lib/libEGL.so /usr/lib/libEGL.so.1sudo ln -fs /opt/vc/lib/libEGL_static.a /usr/lib/libEGL_static.asudo ln ­fs /opt/vc/lib/libGLESv2.so /usr/lib/libGLESv2.sosudo ln -fs /opt/vc/lib/libGLESv2.so /usr/lib/libGLESv2.so.2sudo ln ­fs /opt/vc/lib/libGLESv2_static.a /usr/lib/libGLESv2_static.asudo ln ­fs /opt/vc/lib/libbcm_host.so /usr/lib/libbcm_host.sosudo ln ­fs /opt/vc/lib/libvchiq_arm.a /usr/lib/libvchiq_arm.asudo ln ­fs /opt/vc/lib/libvchiq_arm.so /usr/lib/libvchiq_arm.sosudo ln ­fs /opt/vc/lib/libvcos.a /usr/lib/libvcos.asudo ln ­fs /opt/vc/lib/libvcos.so /usr/lib/libvcos.so

OFTEN USE ­ apt-get update && apt-get dist-upgradeapt-get install ntpdatentpdate uk.pool.ntp.org

arm128_start.elf : 128M ARM, 128M GPU splitarm192_start.elf : 192M ARM, 64M GPU splitarm224_start.elf : 224M ARM, 32M GPU split

134

Page 135: MrRsPiManualGuide-KernelPanic

Installing DOOM 1 / 2First off, we need to prepare a folder for the source code. I have a folder called Sources in my homedirectory where I direct all my source code and compiling related needs. So, let's start by creating one:

cd ~mkdir Sourcescd Sources

Next, we will download the .tar.gz archive from SourceForge either with Midori or NetSurf or download iton your computer and use SSH to transfer it to the Sources folder:

sudo wgethttp://downloads.sourceforge.net/project/chocolate­doom/chocolate­doom/1.7.0/chocolate­doom­1.7.0.tar.gz

Then unpack it, delete the archive and navigate into the new folder:tar ­xvf chocolate­doom­1.7.0.tar.gzrm chocolate­doom­1.7.0.tar.gzcd chocolate­doom­1.7.0

Before we start configuring and compiling, we need to download a pretty huge list of packages, they aremainly SDL related so they should be useful to you on your next compiling adventures.

sudo apt­get updatesudo apt­get install gcc build­essential libsdl1.2­dev libsdl1.2debian libsdl­image1.2libsdl­image1.2­dev libsdl­mixer1.2 libsdl­mixer1.2­dev libsdl­net1.2 libsdl­net1.2­devtimidity

When everything is installed, we can finally run the configuration script./configure

(NOTE: If this gives you an error, it is most likely due to a part of your compiling masquerade is missing.Try googling the error and you will most likely find what you need to apt­get in order to fix it.)Finally, we can start compiling. This will take some time but not nearly as long as Q3A.

makeAfter compiling finishes, we will install our new binaries with the followning command:

sudo make install

NOTE: You need to run this using sudo or as root, because the installing script copies binaries, icons and.desktop files to the /usr/share folder. On the bright side, this means that everything gets neatlyembedded in your LXDE menu. Due to the way chocolate­doom is launched this is a bit unneeded, butwe will talk about that later (at least we have the icon).To configure Chocolate Doom, you need to run the following command from the terminal:

chocolate­setup

This will bring you up a nice DOS­looking window where you can configure our new software. Underdisplay configuration, you can either choose the full screen, but if you have a Full HD LCD like me, Ireccomend hitting A, disabling "Fix aspect ratio" and then selecting 1280x800, since it tends to be quitelaggy on full 1920x1080. Hit the escape key to return to the original menu. Since there is no joystick to beconfigured, we will head right to thekeyboard configuration. If you want controls similar to more modernFPS games, set Move Forward to W, Move Backward to S, Strafe Left to A, Strafe Right to D and youcan set Turn Left to Q and Turn Right to E or whatever you like and leave Speed On on Shift and StrafeOn on Alt. Press escape to return and you can skip the Mouse configuration, since everything there is setby default to the "average" levels. You can fiddle around there yourself later. Go to Sound configurationand make sure Sound Effects is set to Digital and that Music playback is set to Native MIDI. Once youchecked that, return to the main menu and select Save parameters and launch DOOM. Now, since thereare no WAD files yet, the game will not lauch but the settings will be saved.

135

Page 136: MrRsPiManualGuide-KernelPanic

Now, we need to get the WAD files. A little google search will tell you how to *cough* *cough* extractthese files from your original Doom CD. Alternatively, you can use Doom 2, Ultimate Doom, TNT: Eviluionor Plutonia. Log into your Raspberry Pi through SSH as root (for example using WinSCP) and makecreate a folder called doom in /usr/share and put your doom.wad, doom2.wad, tnt.wad or plutonia.wad. Ihave tried Strife and Hexen as well, but for some strange reason they don't work for me.

Then you can finally start the game using the terminal with the following command:chocolate­doom ­iwad /usr/share/(name of your file).wadCongratulations! You have now got Doom running on your Raspberry Pi.

OPTIONAL: Create a WAD­specific launcher(so you don't have to use the terminal all the time)Open up LeafPad and type the following text in:

[Desktop Entry]Name=Doom 1Exec=chocolate­doom ­iwad /usr/share/doom/doom.wadIcon=chocolate­doomType=ApplicationComment=Conservative Doom source port. Loaded with a Doom1 WAD.Categories=Game;ActionGame;

And save it on your desktop as doom1.desktop. The exact name doesn't really matter, since the namespecified inside the file is the one getting displayed. Bang, you got your easy desktop launcher for Doom.Can you even ask for more? Well... Of course you can. Let me introduce you to the:

OPTIONAL 2: Create a laucher for multiple kinds of DoomSo, let's say you happen to own both Doom 1, Doom 2, and on top of it you also own TNT and Plutonia.And you don't want to have four different icons. Then let us create a launcher with all these options! Usinga little inspiration from the ever­popular Python Games, we will make ourselves a nice little menu usingZenity. Open up LeafPad, or, if you have it, Geany and paste the following script there:

#!/bin/sh

RET=0GAME=$(zenity ­­list ­­width=350 ­­height=250 ­­radiolist ­­title="Choose your game"­­column "Select" ­­column="Game" TRUE "Doom 1/Ultimate Doom" FALSE "Doom 2" FALSE "TNT:Evilution" FALSE "The Plutonia Experiment" )RET=$?echo $GAMEif [ "$GAME" = "Doom 1/Ultimate Doom" ]; then chocolate­doom ­iwad /usr/share/doom/doom.wadelif [ "$GAME" = "Doom 2" ]; then chocolate­doom ­iwad /usr/share/doom/doom2.wadelif [ "$GAME" = "TNT: Evilution" ]; then chocolate­doom ­iwad /usr/share/doom/tnt.wadelif [ "$GAME" = "The Plutonia Experiment" ]; then chocolate­doom ­iwad /usr/share/doom/plutonia.wadelse echo "Cancelled..."fi

And save it somewhere nice, like your home folder, under the name chocolate­doom­launcher (withoutthe extension). Open up terminal, navigate to the file you just saved and issue these two commands:

chmod +x chocolate­doom­launcher

136

Page 137: MrRsPiManualGuide-KernelPanic

sudo cp chocolate­doom­launcher /usr/binFrom now on, you have a new terminal command that brings up a nice little launcher for all your Doomrelated business. Now let's turn it into a pretty little icon, shall we? For the last time, open LeafPad orGeany and create a new file and paste this into it:

[Desktop Entry]Name=Chocolate Doom LauncherExec=chocolate­doom­launcherIcon=chocolate­doomType=ApplicationComment=One launcher for all Doom realted games.Categories=Game

And save it on your desktop as chocolate­doom­launcher.desktop. If you want this launcher to appear inyour menu as well, open up terminal for the last time and type in these two commands:

cd ~/Desktopsudo cp chocolate­doom­launcher.desktop /usr/share/applications

And that's it. You now have a fully working, configured installation of Chocolate Doom 1.7.0 with workingMIDI sound thru Timidity, with a launcher for different games both on your desktop and in yourapplications menu. Time to give yourself a pat on the back, and go play some Doom! Enjoy!

Installing Aliens TC and Aliens Doom 3.0 (AVP) in Chocolate Doom.Download the appropriate files Aliens TChttp://www.doomworld.com/idgames/index.php?id=5739

Download the appropriate files for Aliens Doom 3http://www.doomworld.com/idgames/index.php?id=5254

Extract in the WADs folder.Run Alienst TC usingchocolate­doom ­iwad <path>/DOOM.WAD ­deh <path>/atcud19.deh ­merge <path>/alitcsf.wad ­file <path>/alitcsnd.wad<path>/alitcwad.wad

Run Alens Doom 3 usingchocolate­doom ­iwad <path>/DOOM.WAD ­deh <path>/ad3.deh ­merge <path>/ad3spfl.wad <path>/ad3gfx.wad<path>/ad3snd.wad <path>/ad3mus.wad <path>/ad3lev.wad

Don’t forget these can be added to the custom doom launcher. (chocolate­doom­launcher) see above,set the permissions again, and copy to the usr/share/applications

Instructions for LAN playTo play Chocolate Doom on a local area network is straightforward. Start a server in the same way as for Internetplay:chocolate­doom ­server ­deathmatch

Other players can then automatically join the server with the ­autojoin command line option:chocolate­doom ­autojoin

137

Page 138: MrRsPiManualGuide-KernelPanic

Installing Minecraft on the Pi.Grab the Targa Ball.wget https://s3.amazonaws.com/assets.minecraft.net/pi/minecraft­pi­0.1.1.tar.gz

To decompress it: tar ­zxvf minecraft­pi­0.1.1.tar.gzTo run it: cd mcpiFollowed by minecraft­pi

Custom Textures PacksThese do work. Try DokuCraft, Legopak or Sphax(to install these backup the~/mcpi/data/images folder, then overwrite it with the texture pack. This will overwrite, but should work.Best done in ‘X’ as you can really see what you’re doing!

Python Scripts for Minecraft.Easiest way is to clone the scripts GitHub (see GitHub’s worth cloning!)mkdir /home/pi/mcpi/PythonScriptssudo git clone https://github.com/brooksc/mcpipy.gitcd mcpipysudo mv *.py /home/pi/mcpi/PythonScripts

These can then be run from a seperate command prompt! (just run then as plain python scripts, e.g.

sudo python ~/mcpi/PythonScripts/maze.py

For the clocks etc you have to keep the script running for it to update!

Rendering 3D Models in the Minecraft WorldFromhttp://www.stuffaboutcode.com/

Download and runYou can download the code direct from git­hub, so run minecraft, open/create a world and follow theinstructions:

sudo apt­get install git­corecd ~git clone https://github.com/martinohanlon/minecraft­renderObj.gitcd minecraft­renderObjpython minecraft­renderObj.py

By default the renderObj (v1) script will render the manhatten skyline.v2 will render the Raspberry Pi, V2 works better. To change what is rendered you’ll have to get yourhands dirty!

138

Page 139: MrRsPiManualGuide-KernelPanic

Lots of models available from herehttp://people.sc.fsu.edu/~jburkardt/data/obj/obj.html

Making the OBJ Files.In sketchup get your model sorted (or import one!)Ensure you have the right plugin installed in the plugins folder

Instructions from here.1. Get the free version of Google Sketchup and install this plugin (Put it in the plugin folder on your

Sketchup installation folder).

(https://sites.google.com/site/messiaen64/level-importer/ObjExporter.rb?attredirects=0)

2. Make your SketchUp model.

3. Click on the plugins tab and select OBJ Exporter.

4. Click browse to select where your model is going to.

5. Click on Export .Obj File.

6. This can take a while, so be patient.

Copy the obj files across to the Pi using WinSCP or similar.

Running your New ModelEdit the renderObj.py files your addition should look something like this...

#CthulhuCOORDSSCALE = 2STARTCOORD = minecraft.Vec3(­75, 25, ­60)CLEARAREA1 = minecraft.Vec3(­30, 15, ­30)CLEARAREA2 = minecraft.Vec3(­100, 65, ­90)BLOCKTYPE = block.WOOD_PLANKSSWAPYZ = Falsevertices,textures,normals,faces = load_obj("cthulhu.obj")

Viewing 3D Meshes on a Pi.Trying out various options such as PyObjViewer ­ Doesn’t work well.

wget http://jestermon.weebly.com/uploads/1/6/2/1/1621282/pyobjviewer.zip

Meshlab?

139

Page 140: MrRsPiManualGuide-KernelPanic

List of Minecraft Blockshttp://raspberry­python.blogspot.co.uk/2013/02/minecraft­pi­edition­available.html

AIR = Block(0)STONE = Block(1)GRASS = Block(2)DIRT = Block(3)COBBLESTONE = Block(4)WOOD_PLANKS = Block(5)SAPLING = Block(6)BEDROCK = Block(7)WATER_FLOWING = Block(8)WATER = WATER_FLOWINGWATER_STATIONARY = Block(9)LAVA_FLOWING = Block(10)LAVA = LAVA_FLOWINGLAVA_STATIONARY = Block(11)SAND = Block(12)GRAVEL = Block(13)GOLD_ORE = Block(14)IRON_ORE = Block(15)COAL_ORE = Block(16)WOOD = Block(17)LEAVES = Block(18)GLASS = Block(20)LAPIS_LAZULI_ORE = Block(21)LAPIS_LAZULI_BLOCK = Block(22)SANDSTONE = Block(24)BED = Block(26)COBWEB = Block(30)GRASS_TALL = Block(31)WOOL = Block(35)FLOWER_YELLOW = Block(37)FLOWER_CYAN = Block(38)MUSHROOM_BROWN = Block(39)MUSHROOM_RED = Block(40)GOLD_BLOCK = Block(41)IRON_BLOCK = Block(42)STONE_SLAB_DOUBLE = Block(43)

STONE_SLAB = Block(44)BRICK_BLOCK = Block(45)TNT = Block(46)BOOKSHELF = Block(47)MOSS_STONE = Block(48)OBSIDIAN = Block(49)TORCH = Block(50)FIRE = Block(51)STAIRS_WOOD = Block(53)CHEST = Block(54)DIAMOND_ORE = Block(56)DIAMOND_BLOCK = Block(57)FARMLAND = Block(60)FURNACE_INACTIVE = Block(61)FURNACE_ACTIVE = Block(62)DOOR_WOOD = Block(64)LADDER = Block(65)STAIRS_COBBLESTONE = Block(67)DOOR_IRON = Block(71)REDSTONE_ORE = Block(73)SNOW = Block(78)ICE = Block(79)SNOW_BLOCK = Block(80)CACTUS = Block(81)CLAY = Block(82)SUGAR_CANE = Block(83)FENCE = Block(85)GLOWSTONE_BLOCK = Block(89)BEDROCK_INVISIBLE = Block(95)STONE_BRICK = Block(98)GLASS_PANE = Block(102)MELON = Block(103)FENCE_GATE = Block(107)GLOWING_OBSIDIAN = Block(246)NETHER_REACTOR_CORE = Block(247CRAFTING_TABLE = Block(58)

140

Page 141: MrRsPiManualGuide-KernelPanic

Minecraft Twitter (untested)http://www.stuffaboutcode.com/2013/08/raspberry­pi­minecraft­twitter.html?m=1

InstallCreate a twitter appYou need to create a twitter app using your twitter id, you can do this by visiting dev.twitter.com, signingon, and clicking create app; if you are having problems see a previous blog post of mine, automaticallyposting updates to twitter, which has some in­depth instructions.

Install python oauth & pycurlWe need a couple of python modules to get the twitter feed working. If you have never installed pythonmodules before you are going to need to install the python setup tools module, distribute, see blog post,python ­ installing modules, for info on how to do this.

sudo apt­get install git­coregit clone https://github.com/leah/python­oauth.gitcd python­oauthsudo python setup.py installsudo apt­get install python­pycurl

Download codecd ~git clone https://github.com/martinohanlon/minecraft­twitter.gitcd minecraft­twitter

Update twitter keysYou will need to get the twitter keys you were given when you created your twitter app and put them intominecraft­twitter.py. Open minecraft­twitter.py and scroll down till you find:

# twitter oauth keys, get yours from dev.twitter.comCONSUMER_KEY = '#############'CONSUMER_SECRET = '###############'ACCESS_TOKEN = '###############ACCESS_TOKEN_SECRET = '###############'

And replace the hashes with your access keys.

RunStart up minecraft

python minecraft­twitter.py

CodeIts a bit hacky (as you might expect from a hack weekend), but I've include it for reference below. If youwant to get it running though I would suggest you download it from github using the instructions above.

141

Page 142: MrRsPiManualGuide-KernelPanic

#www.stuffaboutcode.com#Raspberry Pi, Minecraft Twitter

#import the minecraft.py module from the minecraft directoryimport minecraft.minecraft as minecraft#import minecraft block moduleimport minecraft.block as block#import time, so delays can be usedimport time#import oauth for twitter securityfrom oauth.oauth import OAuthRequest, OAuthSignatureMethod_HMAC_SHA1from hashlib import md5#required by twitter stream classimport json, random, math, urllib, urllib2, pycurl

#Letters used in the program, hashes are turned into blocksletters = "a":"###" + "\n" +"# #" + "\n" +"###" + "\n" +"# #" + "\n" +"# #" + "\n","b":"###" + "\n" +"# #" + "\n" +"###" + "\n" +"# #" + "\n" +"###" + "\n","c":"###" + "\n" +"#" + "\n" +"#" + "\n" +"#" + "\n" +"###" + "\n","d":"##" + "\n" +"# #" + "\n" +"# #" + "\n" +"# #" + "\n" +"##" + "\n","e":"###" + "\n" +"#" + "\n" +"###" + "\n" +"#" + "\n" +"###" + "\n","f":"###" + "\n" +"#" + "\n" +"###" + "\n" +"#" + "\n" +"#" + "\n","g":"###" + "\n" +"# #" + "\n" +"###" + "\n" +" #" + "\n" +"###" + "\n","h":"# #" + "\n" +"# #" + "\n" +

142

Page 143: MrRsPiManualGuide-KernelPanic

"###" + "\n" +"# #" + "\n" +"# #" + "\n","i":"###" + "\n" +" #" + "\n" +" #" + "\n" +" #" + "\n" +"###" + "\n","j":"###" + "\n" +" #" + "\n" +" #" + "\n" +" #" + "\n" +"##" + "\n","k":"# #" + "\n" +"##" + "\n" +"#" + "\n" +"##" + "\n" +"# #" + "\n","l":"#" + "\n" +"#" + "\n" +"#" + "\n" +"#" + "\n" +"###" + "\n","m":"# #" + "\n" +"###" + "\n" +"###" + "\n" +"# #" + "\n" +"# #" + "\n","n":"###" + "\n" +"# #" + "\n" +"# #" + "\n" +"# #" + "\n" +"# #" + "\n","o":"###" + "\n" +"# #" + "\n" +"# #" + "\n" +"# #" + "\n" +"###" + "\n","p":"###" + "\n" +"# #" + "\n" +"###" + "\n" +"#" + "\n" +"#" + "\n","q":"###" + "\n" +"# #" + "\n" +"###" + "\n" +" #" + "\n" +" #" + "\n","r":"###" + "\n" +"# #" + "\n" +"##" + "\n" +"# #" + "\n" +"# #" + "\n",

143

Page 144: MrRsPiManualGuide-KernelPanic

"s":"###" + "\n" +"#" + "\n" +"###" + "\n" +" #" + "\n" +"###" + "\n","t":"###" + "\n" +" #" + "\n" +" #" + "\n" +" #" + "\n" +" #" + "\n","u":"# #" + "\n" +"# #" + "\n" +"# #" + "\n" +"# #" + "\n" +"###" + "\n","v":"# #" + "\n" +"# #" + "\n" +"# #" + "\n" +"# #" + "\n" +" #" + "\n","w":"# #" + "\n" +"# #" + "\n" +"# #" + "\n" +"###" + "\n" +"###" + "\n","x":"# #" + "\n" +" #" + "\n" +" #" + "\n" +" #" + "\n" +"# #" + "\n","y":"# #" + "\n" +"# #" + "\n" +"###" + "\n" +" #" + "\n" +"###" + "\n","z":"###" + "\n" +" #" + "\n" +" #" + "\n" +"#" + "\n" +"###" + "\n"," ":" ","1":" #" + "\n" +"##" + "\n" +" #" + "\n" +" #" + "\n" +"###" + "\n","2":"###" + "\n" +" #" + "\n" +"###" + "\n" +"#" + "\n" +"###" + "\n","3":

144

Page 145: MrRsPiManualGuide-KernelPanic

"###" + "\n" +" #" + "\n" +"###" + "\n" +" #" + "\n" +"###" + "\n","4":"#" + "\n" +"#" + "\n" +"# #" + "\n" +"###" + "\n" +" #" + "\n","5":"###" + "\n" +"#" + "\n" +"###" + "\n" +" #" + "\n" +"###" + "\n","6":"###" + "\n" +"#" + "\n" +"###" + "\n" +"# #" + "\n" +"###" + "\n","7":"###" + "\n" +" # " + "\n" +" #" + "\n" +" #" + "\n" +"#" + "\n","8":"###" + "\n" +"# #" + "\n" +"###" + "\n" +"# #" + "\n" +"###" + "\n","9":"###" + "\n" +"# #" + "\n" +"###" + "\n" +" #" + "\n" +"###" + "\n","0":"###" + "\n" +"# #" + "\n" +"# #" + "\n" +"# #" + "\n" +"###" + "\n","!":" # " + "\n" +" # " + "\n" +" # " + "\n" +" " + "\n" +" # " + "\n","?":"###" + "\n" +" #" + "\n" +" ##" + "\n" +" " + "\n" +" # " + "\n",".":" " + "\n" +" " + "\n" +" " + "\n" +

145

Page 146: MrRsPiManualGuide-KernelPanic

" " + "\n" +" # " + "\n",",":" " + "\n" +" " + "\n" +" " + "\n" +" #" + "\n" +" # " + "\n","/":" #" + "\n" +" #" + "\n" +" # " + "\n" +"# " + "\n" +"# " + "\n",":":" " + "\n" +" # " + "\n" +" " + "\n" +" # " + "\n" +" " + "\n","@":"###" + "\n" +"# #" + "\n" +"## " + "\n" +"# " + "\n" +"###" + "\n","'":" # " + "\n" +" # " + "\n" +" " + "\n" +" " + "\n" +" " + "\n","#":" # " + "\n" +"###" + "\n" +" # " + "\n" +"###" + "\n" +" # " + "\n"

# twitter oauth keys, get yours from dev.twitter.comCONSUMER_KEY = '#############'CONSUMER_SECRET = '###############'ACCESS_TOKEN = '###############ACCESS_TOKEN_SECRET = '###############'

# constants to position the text lines in minecraftLETTERBLOCKID = block.COBBLESTONE.idLETTERBLOCKDATA = 0#These are the lines where the tweets will be writtenTEXTLINES = 0:[[minecraft.Vec3(­95, 55, ­95), minecraft.Vec3(+95, 55, ­95)], [minecraft.Vec3(+95, 55, ­95), minecraft.Vec3(+95, 55, +95)], [minecraft.Vec3(+95, 55, +95), minecraft.Vec3(­95, 55, +95)], [minecraft.Vec3(­95, 55, +95), minecraft.Vec3(­95, 55, ­95)]], 1:[[minecraft.Vec3(­95, 47, ­95), minecraft.Vec3(+95, 47, ­95)], [minecraft.Vec3(+95, 47, ­95), minecraft.Vec3(+95, 47, +95)], [minecraft.Vec3(+95, 47, +95), minecraft.Vec3(­95, 47, +95)], [minecraft.Vec3(­95, 47, +95), minecraft.Vec3(­95, 47, ­95)]], 2:[[minecraft.Vec3(­95, 39, ­95), minecraft.Vec3(+95, 39, ­95)], [minecraft.Vec3(+95, 39, ­95), minecraft.Vec3(+95, 39, +95)], [minecraft.Vec3(+95, 39, +95), minecraft.Vec3(­95, 39, +95)], [minecraft.Vec3(­95, 39, +95), minecraft.Vec3(­95, 39, ­95)]]

146

Page 147: MrRsPiManualGuide-KernelPanic

LINEHEIGHT = 5LETTERWIDTH = 3

#Class for creating text in minecraftclass MinecraftText: def __init__(self, mc): self.mc = mc self.currentLine = 0 self.currentTopLeft = LINETOPLEFTS[self.currentLine]

#writes a line to minecraft at the next position def writeNextLine(self, line): #Output message self.clearLine(self.currentLine) self.writeLineToMC(line, self.currentLine) self.currentLine+=1 #if I have reached the top line, reset it if self.currentLine == 4: self.currentLine = 0

#writes a line of text into minecraft def writeLineToMC(self, line, lineNumber): #get the textlines textlines = TEXTLINES[lineNumber] #current testline currentTextLine = 0 #set the cursor position currentCursor = minecraft.Vec3(textlines[currentTextLine][0].x, textlines[currentTextLine][0].y, textlines[currentTextLine][0].z) #setup x and z directions xDirection, zDirection = 1, 0 nextTextLine = False #make line lower case line = line.lower() #write the line to minecraft for character in line: #create the character in minecraft self.writeLetterToMC(character, currentCursor, xDirection, zDirection) #move the 'cursor' on # check if the current cursor pos is outside the textLine, # if so move to the next text line if currentTextLine == 0: currentCursor.x = currentCursor.x + LETTERWIDTH + 1 if currentCursor.x > textlines[currentTextLine][1].x: nextTextLine = True if currentTextLine == 1: currentCursor.z = currentCursor.z + LETTERWIDTH + 14 if currentCursor.z > textlines[currentTextLine][1].z: nextTextLine = True if currentTextLine == 2: currentCursor.x = currentCursor.x ­ LETTERWIDTH + 14 if currentCursor.x < textlines[currentTextLine][1].x: nextTextLine = True if currentTextLine == 3: currentCursor.z = currentCursor.z ­ LETTERWIDTH + 14 #if currentCursor.z < textlines[currentTextLine][1].z: nextTextLine = True if nextTextLine == True: nextTextLine = False #next testline currentTextLine+=1 #set the cursor position currentCursor = minecraft.Vec3(textlines[currentTextLine][0].x, textlines[currentTextLine][0].y, textlines[currentTextLine][0].z)

147

Page 148: MrRsPiManualGuide-KernelPanic

#setup x and z diections if currentTextLine == 1: xDirection, zDirection = 0, 1 if currentTextLine == 2: xDirection, zDirection = ­1, 0 if currentTextLine == 3: xDirection, zDirection = 0, ­1

#create a letter in minecraft def writeLetterToMC(self, character, cursorTopLeft, xDirection, zDirection): # the current position is where we have reached in creating the letter currentPos = minecraft.Vec3(cursorTopLeft.x, cursorTopLeft.y, cursorTopLeft.z)

# is the character in my letter list? if (character in letters.keys()): # get the hashes for the character letterString = letters[character] #loop through all the hashes, creating block for digit in letterString: if digit == "#": #print "create block x = " + str(currentPos.x) + " y = " + str(currentPos.y) self.mc.setBlock(currentPos.x, currentPos.y, currentPos.z, LETTERBLOCKID, LETTERBLOCKDATA) currentPos.x = currentPos.x + xDirection currentPos.z = currentPos.z + zDirection if digit == " ": self.mc.setBlock(currentPos.x, currentPos.y, currentPos.z, block.AIR.id) currentPos.x = currentPos.x + xDirection currentPos.z = currentPos.z + zDirection if digit == "\n": currentPos.y = currentPos.y ­ 1 currentPos.x = cursorTopLeft.x currentPos.z = cursorTopLeft.z

#clears a line of text in minecraft def clearLine(self, lineNumber): for textline in TEXTLINES[lineNumber]: self.mc.setBlocks(textline[0].x, textline[0].y, textline[0].z, textline[1].x, textline[1].y ­ LINEHEIGHT, textline[1].z, block.AIR.id)

# class for managing oauth tokensclass Token(object): def __init__(self,key,secret): self.key = key self.secret = secret

def _generate_nonce(self): random_number = ''.join(str(random.randint(0, 9)) for i in range(40)) m = md5(str(time.time()) + str(random_number)) return m.hexdigest()

# twitter clientclass MinecraftTwitterStreamClient: def __init__(self, streamURL): #Connect to minecraft by creating the minecraft object # ­ minecraft needs to be running and in a game self.mc = minecraft.Minecraft.create() #Post a message to the minecraft chat window self.mc.postToChat("Minecraft twitter stream active") #create my minecraft text screen object self.mcText = MinecraftText(self.mc)

148

Page 149: MrRsPiManualGuide-KernelPanic

#setup connection to twitter stream self.streamURL = streamURL self.buffer = "" self.conn = pycurl.Curl() self.conn.setopt(pycurl.URL, self.streamURL) self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive) self.conn.perform()

#this method is called each time some data arrives on the stream def on_receive(self, data): # debug ­ to see when this is called sys.stdout.write(".") self.buffer += data if data.endswith("\n") and self.buffer.strip(): content = json.loads(self.buffer) self.buffer = "" #debug ­ output json from buffer print content

#friends data ­ store for later if "friends" in content: self.friends = content["friends"]

#text (tweet) arrives if "text" in content: print u"0[user][name]: 0[text]".format(content).encode('utf­8') tweet = u"0[user][name]: 0[text]".format(content).encode('utf­8') self.mcText.writeNextLine(tweet)

# get the url needed to open the twitter user stream, including signature after authenticationdef getTwitterUserStreamURL(): STREAM_URL = "https://userstream.twitter.com/2/user.json"

access_token = Token(ACCESS_TOKEN,ACCESS_TOKEN_SECRET) consumer = Token(CONSUMER_KEY,CONSUMER_SECRET)

parameters = 'oauth_consumer_key': CONSUMER_KEY, 'oauth_token': access_token.key, 'oauth_signature_method': 'HMAC­SHA1', 'oauth_timestamp': str(int(time.time())), 'oauth_nonce': access_token._generate_nonce(), 'oauth_version': '1.0',

oauth_request = OAuthRequest.from_token_and_callback(access_token, http_url=STREAM_URL, parameters=parameters) signature_method = OAuthSignatureMethod_HMAC_SHA1() signature = signature_method.build_signature(oauth_request, consumer, access_token)

parameters['oauth_signature'] = signature data = urllib.urlencode(parameters) return "%s?%s" % (STREAM_URL,data)

if __name__ == "__main__":

#Create minecraft twitter mcTwitter = MinecraftTwitterStreamClient(getTwitterUserStreamURL())

149

Page 150: MrRsPiManualGuide-KernelPanic

Installing Descent on the Pi (untested)http://blog.sheasilverman.com/2012/08/descent­tutorial/

1. Install the required dependancies1. sudo apt­get install libsdl1.2debian libsdl­mixer1.2 libsdl­mixer1.2­dev libsdl­image1.2

libsdl­image1.2­dev libsdl­ttf2.0­0 libsdl­ttf2.0­dev libsdl­net1.2 libsdl­net1.2­dev gcc­4.7scons libphysfs­dev

2. cd ~/3. mkdir descent4. cd descent5. Download the needed source code:

1. wgethttp://sourceforge.net/projects/dxx­rebirth/files/dxx­rebirth/0.57.3/d1x­rebirth_v0.57.3­src.tar.gz

2. wgethttp://sourceforge.net/projects/dxx­rebirth/files/dxx­rebirth/0.57.3/d2x­rebirth_v0.57.3­src.tar.gz

6. Download the needed patches:1. wget http://www­user.tu­chemnitz.de/~heinm/tmp/d1x­rebirth­rpi.diff.gz2. wget http://www­user.tu­chemnitz.de/~heinm/tmp/d2x­rebirth­rpi.diff.gz

7. Unzip the source files and the patches:1. tar xvfz d2x­rebirth_v0.57.3­src.tar.gz2. tar xvfz d1x­rebirth_v0.57.3­src.tar.gz3. gunzip d1x­rebirth­rpi.diff.gz4. gunzip d2x­rebirth­rpi.diff.gz

8. You now have to patch the source code with the diff files.1. cd into the source code directories.

1. Descent 11. cd ~/descent/d1x­rebirth_v0.57.3­src/2. patch ­p1 < ../d1x­rebirth­rpi.diff

2. Descent 21. cd ~/descent/d2x­rebirth_v0.57.3­src/2. patch ­p1 < ../d2x­rebirth­rpi.diff

9. We are now ready to compile!10. On the command line enter these two commands:

1. export CC=gcc­4.72. export CXX=g++­4.7

11. Descent 11. cd ~/descent/d1x­rebirth_v0.57.3­src/2. scons raspberrypi=1

1. Wait around 30 – 40 minutes.2. If there are no errors you should now have a d1x­rebirth executable file in

your directory!12. Descent 2

1. cd ~/descent/d2x­rebirth_v0.57.3­src/2. scons raspberrypi=1

1. Wait around 30 – 40 minutes.2. If there are no errors you should now have a d2x­rebirth executable file in

your directory!13. You now need the data files that holds the actual game levels, sounds, artwork, etc. These are in

.hog, .pig, and .ham (descent 2 only) files. You can get the game content from dxx­rebirth, thecreators of this port. They also have links to the shareware files:

1. http://www.dxx­rebirth.com/game­content/2. http://www.dxx­rebirth.com/download/dxx/content/descent­pc­shareware.zip3. http://www.dxx­rebirth.com/download/dxx/content/descent2­pc­demo.zip

14. Unzip those files by running unzip filename15. copy descent.hog and descent.pig to ~/descent/d1x­rebirth_v0.57.3­src/16. copy D2DEMO.HAM, D2DEMO.HOG and D2DEMO.PIG to ~/descent/d2x­rebirth_v0.57.3­src/17. You are now ready to play!

1. Descent 11. cd ~/descent/d1x­rebirth_v0.57.3­src/

150

Page 151: MrRsPiManualGuide-KernelPanic

2. ./d1x­rebirth ­hogdir . (yes, thats a period at the end that must be there)2. Descent 2

1. cd ~/descent/d2x­rebirth_v0.57.3­src/2. ./d2x­rebirth ­hogdir .

18. ENJOY!!

I realize these are a lot of instructions, but I wanted to make them as verbose as possible.

Below are the precompiled binaries with shareware data files already copied over.

Descent 1 Binaries | Descent 2 Binaries

151

Page 152: MrRsPiManualGuide-KernelPanic

SOFTWARE ­ Games Emulation 148

A Note about ROMSHere’s a quick note about ROMs. ROMs are virtual disk images (Generally of old console / computergames). Now many old companies might argue that ROMs aren’t legal. Espeically if you don’t own theoriginal of the game! Yet for some it makes perfects sense, having a copy of a game they bought yearsago to play on new hardware. When Sonic 2 was first released it cost £45 (that’s around £65 withinflation)!!! which is bonkers expensive. However greedy companies love churning out games collectionsfor modern consoles and charging hansomely for them, probably many of the emulators on the consoleswill be using other peoples work and benefitting from it. (N.B. You’ll notice you can’t get a decentemulator on an iPhone/iPad/iPod due to the closed architecture and nature of the app store, unless youjailbreak, sad really!)

So is it legal to download Gensis (Megadrive), SNES or NES roms from sites like Coolroms,emuparadise or Romination? No, but it’s a somewhat grey area!

I’d also like to take another view on this, bear with me if you will. Who’s archiving and backing up ourillustrious games herritage? These games defined generations and are etched into our history. Butgames are being lost... why? Because no­one cares? Or no one is able to archive entire collections?Copyright restrictions? Take a look on any major torrent tracking site for ‘Console XYZ collection’ andyou’ll find EVERY game ever released on that console (multiple versions from multiple countries),immortalised for posterity! These games have been painstakingly collected, categorized and bundled foryour convenience, designed to be easily shared! Why, lest we forget.

Should I encourage you to go and find these games? Dunno. I will perhaps demonstrate Sonic 2 runningfrom an original cartridge on a Megadrive 2, I’ll then show the same game running on Pi throughemulation! There are a ton of lessons to be learnt here, Filesizes, Compression, Emulation, Virtualisationetc. I will also mention some noteworthy characters and some of my other faves. Will I encourage kidsto go and find out more about these games? Of course! Perhaps it will get a few more parents involvedwith a conversation over the dinner table. Current copyright laws are archaic and desperately needupdating! Many of these games will have slipped out of copyright, others will have not. There was a timewhen Sonic and Mario would not be seen dead with each other. Imagine Sony and Microsoft releasing agame together, crazy. But times change.

Handle, with care, use at your own risk. If you like it, buy it (that is if you can even source an originalcopy!) RANT OVER.

152

Page 153: MrRsPiManualGuide-KernelPanic

RetroPie ­ Emcompassing Most Emulators.This will take a while to build if you compile your own! (you could just use latest Binaries, not tested!)

git clone https://github.com/petrockblog/RetroPie­Setupcd RetroPie­Setup

runsudo apt­get install dialog ­ysudo ./retropie_setup.sh

Choose ‘Source Based Installation’, this will take longer, but will give better results!

To setup the system (which emulators etc) edit the following file.sudo nano ~/.emulationstation/es_systems.cfg

Then check out the config files for controls / details etc.sudo nano ~/RetroPie/config/all/retroarch.cfg

set audio_out_rate = 44100

Enusure that if trying to run a playstation emulator you need to edit the es_systems.cfg to read BIN file(both .bin and .BIN as img seems not to work!)

RetroArch­Phoenix or retroarch­joyconfig ???

input_player1_a = xinput_player1_b = zinput_player1_y = ainput_player1_x = sinput_player1_start = enterinput_player1_select = rshiftinput_player1_l = qinput_player1_r = winput_player1_left = leftinput_player1_right = rightinput_player1_up = upinput_player1_down = down

http://blog.petrockblock.com/retropie­downloads/

retroarch ­L /home/root/RetroPie/emulatorcores/Genesis­Plus­GX/libretro.so/home/root/RetroPie/roms/megadrive/SONIC_CMP.smd

RetroPie ­ XBox Pad(Guide from here)

Following this, edit /etc/rc.local, adding (before anything else)

153

Page 154: MrRsPiManualGuide-KernelPanic

xboxdrv ­­trigger­as­button ­­id 0 ­­led 2 ­­deadzone 4000 ­­silent & sleep 1This ensures that the driver launches when the computer boots. Note the use of “–wid” in the instruction,which is for wireless controllers. Change it to –id for wired controllers.

Following this, entercd ~/RetroPie/emulators/RetroArch/tools

While in this directory, input the following command:./retroarch­joyconfig ­o p1.cfg ­p 1 ­j 0

You should increase digits by factor of 1 for each additional controller. If entered correctly, the resultingfiles should be added to retroarch.cfg:

sudo cat p*.cfg >> ~/RetroPie/configs/all/retroarch.cfg

You can then save and reboot to use your Xbox 360 controller.

RetroPie ­ Exit Games Using Your ControllersThe default method for exiting a game in EmulationStation is by restarting your Raspberry Pi – somethingthat can corrupt the SD card as this is only possible in this scenario by removing the power cable.

To overcome this, a workaround exists maps an exit option to your game controller.You’ll need to edit the retroarch.cfg file to do this, adding the following code:input_enable_hotkey_btn = "X"input_exit_emulator_btn = "Y"You will need to check the retroarch.cfg file to identify the buttons you want to use here. Obviously youdon’t want to exit games using the usual controller buttons – instead, you should be looking for the onesthat relate to the buttons in the centre of the controller, perhaps labelled “menu” or “start”.

RetroPie ­ Installing ROMsHopefully you have setup the folders to install the ROMs using SAMBA SHARES from the setup script. Ifnot you can still use MobaXTerm (then on the left navigate to /home/pi/RetroPie/roms/and you will find a folder for each emulator. Put the correct roms in the correct folders!

154

Page 155: MrRsPiManualGuide-KernelPanic

MAME

NEShttp://www.youtube.com/watchv=7_lbCaBUwhc&feature=bf_next&list=PLN4WWy3UrTHT02MuTtn9Q_WZxsXhk2ne7

Snes Emulator ­ SNES9xhttps://github.com/ToadKing/RetroArch­Rpi

Snes9xThere are 2 choice V1.39 (with oss sound) ­ hereor 1.53 (SNES SDL ­ with lots of frameskip!) ­ here

Version 1.39

Some requirements.sudo apt­get install libsdl­ttf2.0­dev libboost1.50­all­dev

cd ~mkdir SNEScd SNESgit clone https://github.com/chep/snes9x­rpicd snes9x­rpimakesudo make install

ConfJoy tool is replaced by confTool which configures keyboard too. Start it in itsdirectory, it will create input.config in snes directory (..). Its first argument is the numberof players who will use the keyboard. Use 0 (zero) if you have no keyboard.

ScummVMhttp://www.raspberrypi.org/phpBB3//viewtopic.php?f=35&t=10692

DGen(time to install ­ around 1 hr)

DGen Manual.http://www.rjanick.com/2012/10/29/dgen­on­the­raspberry­pi/http://dgen.sourceforge.net/

DGen Build InstructionsInstall this so you can run ROMS from Zips ­

sudo apt­get install libarchive­dev

155

Page 156: MrRsPiManualGuide-KernelPanic

cd ~mkdir DGencd DGenwget http://www.libsdl.org/release/SDL­1.2.15.tar.gztar ­xvf SDL­1.2.15.tar.gzcd SDL­1.2.15./configuresudo makesudo make installcd ..wget http://sourceforge.net/projects/dgen/files/dgen/1.32/dgen­sdl­1.32.tar.gztar ­xvf dgen<tabrm dgen­sdl­1.32.tar.gzcd dgen<tab>sudo ./configuresudo makesudo make install

If not work try usingmake install clean

Finall run DGen using this for fullscreen.dgen <filename> ­f

Or this when running on smaller screens!

dgen <filename> ­G 320x240

Tweaking DGenEdit settings

sudo nano /home/pi/.dgen/dgenrc.auto

The newest git version of dgen (and I think the newest release 1.32 version) includes ASM optimized emulators for them68k and z80... make sure you enable them =). You must edit the dgenrc.5 file and set the following

emu_z80_startup = drz80emu_m68k_startup = cyclone

The defaults are cz80 and musa, and they are not optimized for the arm platform.

Sonic Level Select

http://info.sonicretro.org/Sonic_hacks

DGen CONTROLSGAME PAD:Directional Control ­ Cursor KeysButton “A” ­ AButton “B” ­ S

156

Page 157: MrRsPiManualGuide-KernelPanic

Button “C” ­ DStart ­ EnterExit ­ EscF5 ­ Toggles “TV Modes”: blur, scanline, interlace, swab, offF6 ­ Toggles “Scale” Modes: hqx, scale2x, default (NONE)

For a FULL description of the Controls and Options see Here ­ http://dgen.sourceforge.net/

157

Page 158: MrRsPiManualGuide-KernelPanic

Mupen64 ­ RPiTO BUILD/RUNHardware ­ Mupen64plus­Rpi will build on a 512 or 256MEG Raspberry Pi, if you have a 256MEG variety make sureyou have the RAM split attributing a MAXIMUM of 64MEG to the GPU (use the config (sudo raspi­config))Operating System ­ Raspbian WheezyOver Clock ­ Due to the processing power required it is advised to run Mupen64plus­Rpi with the fastest Over Clockthat is stable on your System (use the config (sudo raspi­config))Dependencies Required ­ SDL1.2­devAdditional Files Required ­ Game ROMSRAM Split ­ At least 64MEG to the GPUBuild Time ­ Approximately 45 minutes to 1 Hour depending on overclock

Install the required dependanciessudo apt­get install libsdl1.2­dev

Download the source code from Github (on the right you will see a Cloud symbol with Download ZIP, that's the link forthe master folder) and extract (uncompress).Download Link ­ https://github.com/ricrpi/mupen64plus­rpi

CD into the folder and run the build script./m64p_build.sh

Once completed add some ROMs and extract them to an appropriate folder (I called mine n64roms),then CD into the test folder mupen64plus­rpi­master/test (where the executable and plugins are located ) and run theprogram along with the name and location of the ROMe.g. ./mupen64plus /home/pi/n64roms/mario.n64 (you can change the file name for easy typing)

CONFIGURATION FILE SETTINGSThe cfg file is located at /home/pi.confg (Hidden Folder)mupen64plus/mupen64plus.cfg

Basic changes are identified below, If you are familiar with emulator cfg files feel free to experiment with other settingsand report your findings (this will assist with emulator development).

[Video­General]# Width of output window or fullscreen widthScreenWidth = (Default: 640)# Height of output window or fullscreen heightScreenHeight = (Default: 480)

Change values to alter output resolution, 320x240 is the original hardware res (in most cases), and up to 1024x768has a minimal impact on performance (1­2% when running from Console)

[Video­Rice]# Control when the screen will be updated (0=ROM default, 1=VI origin update, 2=VI origin change, 3=CI change,4=first CI change, 5=first primitive draw, 6=before screen clear, 7=after screen drawn)ScreenUpdateSetting = (Default: 6)

Change value to alter screen update, can influence correct game performance (a setting of 4 will allow Star Fox 64 torender correctly and PilotWings 64 to display for example)

# Force to use texture filtering or not (0=auto: n64 choose, 1=force no filtering, 2=force filtering)ForceTextureFilter = (Default: 1)

Change value to enable filtering, smooth’s textures with minimal impact on performance

# Force to use normal alpha blenderNormalAlphaBlender = (Default: False)

Change to True fixes some games so environments display correctly

158

Page 159: MrRsPiManualGuide-KernelPanic

e.g.Turok Dinosaur Hunter

# If this option is enabled, the plugin will skip every other frameSkipFrame = (Default:True)

Change to False fixes some games in conjunction with ScreenUpdateSetting, however, due to every frame beingdisplayed slows emulatione.g.Goldeneye 64The Legend of Zelda: Majora’s Mask

Set ScreenUpdateSetting=1, SkipFrame = False

Enjoy!

159

Page 160: MrRsPiManualGuide-KernelPanic

SOFTWARE Projects 154

SiriProxy ­ As UserFrom Here

Before we start, I’d recommend getting tmux, but feel free to skip. You’ll need this (or something similar),if you plan to start the SiriProxy server in the foreground (so you can see the output) and disconnect theterminal session (without backgrounding the server). This will let you disconnect, reconnect without theserver stopping. This install process contains one very long step and I’d recommend running this withtmux in case you get disconnected. It also lets you run several terminal session with a single telnet/ssh

login. sudo apt­get install tmux

I’m also going to create a user called “pi” sudo adduser pi

SiriProxy Install1. Install everything needed for Ruby, RVM, git, etc. sudo apt­get install dnsmasq ruby build­essential openssl libreadline6 libreadline6­dev curl git­core zlib1g zlib1g­devlibssl­dev libyaml­dev libsqlite3­0 libsqlite3­dev sqlite3 libxml2­dev libxslt­dev autoconf libc6­dev ncurses­dev automakelibtool bison subversion

Select ‘y’ to continue.

2. Edit DNS(You can skip this if your router or other DNS can handle it. See “DNS” below) sudo nano /etc/dnsmasq.conf

Find the line starting with: #address=/double­click.net/127.0.0.1 (use Ctrl­W to search)Add a new line redirecting the Apple’s Siri server to your local IP (from ifconfig) address=/guzzoni.apple.com/192.168.168.63

Save and exit (Ctrl­O, Enter, Ctrl­X)restart dnsmasq sudo /etc/init.d/dnsmasq restart

160

Page 161: MrRsPiManualGuide-KernelPanic

Test DNS is resolving correctly ping guzzoni.apple.com

Type Ctrl­C as soon as you see an ip address (almost immediately)This should return Apple’s IP address (I got 17.174.8.16). Apple blocks ICMP, so the pings will timeoutjust make sure it resolves into a 17.x.y.z address.

3. Install RVM bash < <(curl ­s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm­installer)

Don’t worry about the warning in red, the next two commands take care of itLoad RVM as a function and update profile [[ ­s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"

echo '[[ ­s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM function' >> ~/.bash_profile

(I’d recommend using tmux for this bit) rvm install 1.9.3

You might have to runrvm autolibs enable

Which tells the ruby install to grab the bits it needs!

Don’t worry about this message: No binary rubies available for: debian/wheezy_sid/armv6l/ruby-1.9.3-p374.answer “Y” to all prompts (takes over an hour to run on the Raspberry)If you get the following error, it’s likely that you ran out of disk space (run “df –k” to check). Error running 'make', please read /home/pi/.rvm/log/ruby-1.9.3-p374/make.log There has been an error while running make. Halting the installation.

Set Ruby 1.9.3 as default rvm use 1.9.3 ­­default

4. Install the SiriProxy git clone git://github.com/plamoni/SiriProxy.git cd SiriProxy

Select 'y' to warning to continue.mkdir ~/.siriproxycp ~/SiriProxy/config.example.yml ~/.siriproxy/config.yml

rake install

Takes a while too. (if this doesn’t take a while, follow the error output and rungem install /home/pi/SiriProxy/pkg/siriproxy­0.5.3.gem

5. Generate Certificates siriproxy gencerts

6. Install the Certificate on your iPhoneYou can use any mechanism to get it to the iphone. As I’m using TerraTerm, I just used SSH SCP (Filemenu ­> SSH SCP…)

161

Page 162: MrRsPiManualGuide-KernelPanic

Another great alternative (if you’ll be doing a lot of editing on your local machine) is WinSCP:

E­mail the certificate yourself, click it and install on phone (ignore warning about it being untrusted)

7. BundleSet a few things in the environment first and create a symbolic link so that rvmsudo works. echo 'export rvmsudo_secure_path=1 ' >> ~/.bash_profile

source ~/.bash_profile

sudo ln ­s ~/.siriproxy /root/.siriproxy

rvmsudo siriproxy bundle

8. Start the server rvmsudo siriproxy server

A message should appear saying something like: Starting SiriProxy on 0.0.0.0:443.. SiriProxy up and running.

9. Set DNS server on phoneThe last step is to point your iPhone at your DNS server. This will be the PI’s IP unless you are using an

162

Page 163: MrRsPiManualGuide-KernelPanic

external DNS server.1. Got to Settings ­> Wi­Fi2. Click the blue arrow next to your connection3. Enter the Linux VM's IP

163

Page 164: MrRsPiManualGuide-KernelPanic

10. TestNote: with the current versions you will highly likely receive an InvalidByteSequence error. Don’t panic.SeeInvalidByteSequence below. Other errors, and solutions, can be found in Part 1Try it anywayPress and hold the home button.Say the exact phrase “Test Siri Proxy”. It should respond with exactly “Siri Proxy is up and running” andyou should see something like this: Create server for iPhone connection start conn #, @zip_stream=#, @consumed_ace=false, @name="iPhone", @ssled=false> [Info ­ Plugin Manager] Plugins laoded: [#>] [Info ­ iPhone] Received Object: LoadAssistant [Info ­ iPhone] Received Object: SetRestrictions [Info ­ iPhone] Received Object: SetRestrictions [Info ­ iPhone] Received Object: ClearContext [Info ­ iPhone] Received Object: SetSessionObjects [Info ­ Guzzoni] Received Object: AssistantLoaded [Info ­ iPhone] Received Object: StartSpeechRequest [Info ­ iPhone] Received Object: SetRequestOrigin [Info ­ User Location] lat: XX.07408038900973, long: ­YY.70323611215576 [Info ­ iPhone] Received Object: SpeechPacket [Info ­ Guzzoni] Received Object: SetConnectionHeader

164

Page 165: MrRsPiManualGuide-KernelPanic

[Info ­ iPhone] Received Object: SpeechPacket [Info ­ iPhone] Received Object: SpeechPacket [Info ­ iPhone] Received Object: SpeechPacket [Info ­ iPhone] Received Object: SpeechPacket [Info ­ iPhone] Received Object: SpeechPacket [Info ­ iPhone] Received Object: SpeechPacket [Info ­ iPhone] Received Object: SpeechPacket [Info ­ iPhone] Received Object: SpeechPacket [Info ­ iPhone] Received Object: SpeechPacket [Info ­ iPhone] Received Object: SpeechPacket [Info ­ iPhone] Received Object: FinishSpeech [Info ­ Guzzoni] Received Object: SpeechRecognized [Info ­ Plugin Manager] Processing 'Test Siri proxy ' [Info ­ Plugin Manager] Processing plugin # [Info ­ Plugin Manager] Matches (?i­mx:test siri proxy) [Info ­ Plugin Manager] Applicable states: [Info ­ Plugin Manager] Current state: [Info ­ Plugin Manager] Matches, executing block [Info ­ Plugin Manager] Say: Siri Proxy is up and running! [Info ­ Plugin Manager] Sending Request Completed

Siri Proxy PluginsGenerally visit the GitHub,Goto the ~/SiriProxy/Plugins FolderDo a git clone <git>see what’s in the config­info.yml (copy the install bit) ­ ignore this and just make the path equal so it canfind the config­info.ymland paste in the general file below.sudo nano ~/.siriproxy/config.ymlrun rvmsudo sirproxy bundlerun rmvsudo bundles install

Finally rvmsudo siriproxy server (and it should ALL be working!)

Magic8Ball ­ https://github.com/Ponyboy47/siriproxy­magic8ballSiri­IMDB ­ https://github.com/mattparmett/SiriProxy­SiriIMDBSir­FoulLanguage ­ https://github.com/coden00b/SiriProxy­FoulLanguage

Adding your own Siri CommandsEdit this file.sudo nano ~/SiriProxy/plugins/siriproxy­example/lib/siriproxy­example.rb

find the ‘listen_for’, add your own commands. They must be aligned and the colours MUST match up! listen_for /what time is it/i do say "It's Hammer Time." #Say something to the user! request_completed #always complete your request! end

You can add commands to be run using the ‘puts %x ’command. listen_for /Quake/i do

165

Page 166: MrRsPiManualGuide-KernelPanic

say "about to run Quake3" #Say something puts %xsudo /home/pi/Quake3/ioquake3.arm request_completed #Always complete your requests! end

After you have made changes you should dorvmsudo siriproxy updatervmsudo bundle installrvmsudo siriproxy bundle

Then test withrvmsudo siriproxy server

166

Page 167: MrRsPiManualGuide-KernelPanic

SiriProxy ­ As RootDifferent Approach, not as ROOThttp://www.hometoys.com/emagazine/2013/02/siri­home­automation­integration­from­start­to­finish­brpart­1­­the­basics­using­a­linux­vm/2087

Best guide yet.http://steve0hh.wordpress.com/2013/02/11/raspberry­pi­siri­proxy/

https://gist.github.com/elvisimprsntr/4409751

http://simonthepiman.com/how_to_setup_windows_file_server.php ­ setting up SAMBA.

Clone the GitHub and instructions.https://github.com/plamoni/SiriProxy

http://www.idownloadblog.com/2011/12/09/how­to­install­siri­proxy­tutorial­video/

1. UPDATE YOUR PI.Type this into Pi’s terminal:apt­get updateapt­get dist­upgradeapt­get autoremove

2. SET THE ROOT PASSWORD FROM THE USER ACCOUNTThis might not sound important, but this will save a lot of hassel! You’ll need root access to start SiriProxy, but youdon’t need to sudo while installing RVM, which will result in your user not being able to start SiriProxy server. Or rootnot having RVM, SiriProxy installed for them.Typesudo passwd

Set the desired password.Log out and log back in using root.Remove the original account (Optional) :deluser

3. INSTALLING THE BASICSapt­get install samba samba­common­bin ssh vim rcs unzip ­y

4. EDIT THE NETWORK SETTINGS TO USE A STATIC IP ADDRESSWe do this so as your Pi doesn’t change it’s IP address, hence we’ll have lesser hassel when setting up the iPhonefor SiriProxy. To edit, type :vim /etc/network/interfaces

Then once in the configuration file, comment the following out by adding a # to the front:Fromiface eth0 inet dhcp

toiface eth0 inet static

Then add the following snippet below the line of code you have just commented out.

167

Page 168: MrRsPiManualGuide-KernelPanic

Note: Replace the words in caplocks with your own address.auto eth0iface eth0 inet static

address YOUR­DESIRED­IP­ADDRESSnetmask 255.255.255.0broadcast 192.168.1.255network 192.168.1.0gateway 192.168.1.254

Example of mine as my Pi’s IP address was 192.168.1.6:auto eth0iface eth0 inet static

4. REBOOT YOUR PIReboot to have the changes take effect.To reboot, type:reboot

5. BREAK THE CIRCULAR APPLE’S SIRI SERVER DNS RE­DIRECTEdit your DNS settings :nano /etc/resolv.conf

Comment out NAMESERVER entires from your ISP or router internal IP address, which is usually just the first line inthe file, then add this into the file :# Google public DNS serversnameserver 8.8.8.8nameserver 8.8.4.4# Level3 public DNS servers ­ less hops and shorter ping timesnameserver 209.244.0.3nameserver 209.244.0.4

6. SETUP YOUR DNS SERVERI am opting to use Pi as the DNS server as I do not want to mess with my router’s setting.

To install DNSMASQ, type :sudo apt­get install dnsmasq

Change the config file.sudo nano /etc/dnsmasq.conf

At around line 63, find the following#address=double­click.net/127.0.0.1

Under it add this# iOS production Siri serveraddress=/guzzoni.apple.com/<your static ip># iOS beta Siri serveraddress=/kryten.apple.com/<your static ip>

Hit save, then restart dnsmasq by typing:sudo /etc/init.d/dnsmasq restart

7. INSTALL THE PREREQUISITE THAT NEEDED TO BE INSTALLED :

168

Page 169: MrRsPiManualGuide-KernelPanic

sudo apt­get install ruby build­essential openssl libreadline6 libreadline6­dev curl git­core zlib1g zlib1g­dev libssl­devlibyaml­dev libsqlite3­dev sqlite3 libxml2­dev libxslt­dev autoconf libc6­dev ncurses­dev automake libtool bisonsubversion pkg­config ­y

8. INSTALL RVMbash < <(curl ­s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm­installer)

9. SET RVM PATH[[ ­s "/etc/profile.d/rvm.sh" ]] && . "/etc/profile.d/rvm.sh"

10. SET THE RVM PATH TO BE SET UP EVERY TIME I LOG INecho '[[ ­s "/etc/profile.d/rvm.sh" ]] && . "/etc/profile.d/rvm.sh" # Load RVM function' >> ~/.bash_profile

11. INSTALL RUBY 1.9.3(This will take quite a long time.. So go grab a coffee and come back.)rvm install 1.9.3

12. CLONE THE SIRIPROXY REPOcd ~sudo git clone git://github.com/plamoni/SiriProxy.git

13. ENTER THE SIRIPROXY DIRECTORYcd SiriProxy

14. MAKE THE .SIRIPROXY DIRECTORY IN MY HOME DIRECTORYmkdir ~/.siriproxy

15. COPY THE EXAMPLE CONFIG TO .SIRIPROXY DIRECTORY TO USEcp ./config.example.yml ~/.siriproxy/config.yml

16. INSTALL SIRIPROXYCan take a minute or tworake installN.B. If not running as root you will probably have to set permissions usingsudo chown ­R whoami~/.rvmandsudo chown ­R whoami~/.SiriProxy

It them fails on the build and tells you tur rungem install /home/pi/SiriProxy/pkg/siriproxy­0.5.2.gemDO NOT RUN THIS AS SUDO, it will fail, try it normally!

17. GENERATE THE CERTIFICATES FOR YOUR IPHONE TO USEsiriproxy gencerts

18. EMAIL & INSTALL IT TO YOUR IPHONE!As SSH port 22 is opened by default on the Raspbian “wheezy” image, we could use WinSCP (on our main computer)to get the certificate (ca.pem) from our Pi. To do that, we’ve to type (on our main computer) :

Naviagate to /home/pi/.siriproxy and copy the ca.pem.

Attach this file to an email account you have access to on your iPhone.On the iPhone simply, open your email, tap the file and follow the prompts to install the certificate.

169

Page 170: MrRsPiManualGuide-KernelPanic

19. CONFIGURE YOUR IPHONEAs we’ll need to configure the DNS settings on the iPhone!.Head to Settings app on your iPhone, select Wifi.

Then select the blue arrow of the hotspot you are connected to for more settings.

Change the DNS IP address to your Pi’s IP address, in my case, I’ve set it to192.168.1.6, which is my IP address.

170

Page 171: MrRsPiManualGuide-KernelPanic

20. BUNDLE SIRIPROXYThis installs the plugins and what notsiriproxy bundlebundle install

21. START THE SERVER!!To start SiriProxy, type :siriproxy server

In the terminal it should show something like :

22. TEST IF IT’S WORKING!On your iPhone launch Siri and say : test siri proxyIf it replys with Siri Proxy is up and running!, then you know you got it. And on the terminal, you will see somethinglike the image below.

171

Page 172: MrRsPiManualGuide-KernelPanic

Ultrasonic Distance Monitor

http://www.raspberrypi­spy.co.uk/2013/01/ultrasonic­distance­measurement­using­python­part­2/

172

Page 173: MrRsPiManualGuide-KernelPanic

Taking Screenshots on the Raspberry PiPosted by zag on Feb 27 2013 04:26 PM

It looks like the default debian image isn't setup to take screenshots at the moment.

Most people will need to make a screenshot at some point, so here is a quick guide to setting it up.

Step 1

Load up start >> accessories >> LXTerminalsudo apt­get install scrot

When the install is finished, type 'scrot' at the terminal to start it.

Step 2

Press "Prt Scr" on the keyboardNow go to file browser and you will see the screenshot in your user area.Something like this:

[attachment=222:screenshot.jpg]

173

Page 174: MrRsPiManualGuide-KernelPanic

Simple Samba Share http://elinux.org/R­Pi_NAS

(Tried this so kids could grab stuff from my demo pi?)cd~

#Install the 2 samba packages (30 ish MB)sudo apt­get updatesudo apt­get install samba

Edit the samba config for your share!sudo nano /etc/samba/smb.conf

#Add the following at the end[MROShare]comment =MRO Sharepath = /home/pi/read only = Yeswriteable = Yescreate mask = 0777directory mask = 0777guest only = Yesguest ok = Yes

#Save the file (ctrl + o, Enter, ctrl+x)#Restart the Samba service. Test.

sudo service samba restart

use smbget or similar to test (try out on windows PC!)

SMBGET (tested and working!)you need to have samba installed to use this to grab a file.

sudo smbget smb://<ipaddress>/<folder>/<file>

or to grab an entire folder (use ­R recursive)sudo smbget ­R smb://<ipaddress>/<folder e.g. MROShare>/<file>

SAMBA Server on the Pi.

1. Ensure SSH setup on the Pi.Login using the default user pi and the default password raspberry.

2. Now lets make sure all the system updates from Debian have been appliedpi@raspberrypi~$ sudo apt­get update

NOTE:- The disk drives that I will be attaching will be formatted in windows format - eitherFAT32 or NTFS

174

Page 175: MrRsPiManualGuide-KernelPanic

3. Attach the disk drive or drives to the Raspberry Pi then typepi@raspberrypi~$ sudo fdisk ­l

This will show all the details of the attached disks even if you are not yet using or are ableto access them.

A powered 1Tb disk drive and a 400Mb usb card­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­Disk /dev/mmcblk0: 3965 MB, 3965190144 bytes Device Boot Start End Blocks Id System/dev/mmcblk0p1 17 1216 76800 c W95 FAT32 (LBA)/dev/mmcblk0p2 1233 26672 1628160 83 Linux/dev/mmcblk0p3 26689 29744 195584 82 Linux swap / Solaris

Disk /dev/sda: 1000.2 GB, 1000204886016 bytes Device Boot Start End Blocks Id System/dev/sda1 1 121601 976760001 7 HPFS/NTFS

Disk /dev/sdb: 4005 MB, 4005560320 bytes Device Boot Start End Blocks Id System/dev/sdb1 1 486 3903763+ b W95 FAT32­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­From the above listing you can see a disk /dev/mmcblk0 (the SD Card) which contains 3partitions - so this is the operating system disk.

I also have /dev/sda which is a Terabyte drive which has one partition and has beenformatted in HPFS/NTFS windows NT disk format

Finally I have a disk /dev/sdb that is a 4Gb usb card with 1 partition but this time its beenformatted in a windows FAT32 format - old style formatted.

All the disk drives and partitions attached to the Pi are shown, they are all given a deviceaddress such as /dev/sda with a partiton 1 so /dev/sda1 is the disk in the first Pi usb portand is partition 1.

4. Now we need to make the disks available to the operating system so we need to createa point in the filesystem to mount the disks on.

To do this we need to create a directory that the disk can be attached to, so in theexample below we will use /mnt/disk1 for the 1st Disk and /mnt/disk2 for the second.

pi@raspberrypi~$ sudo mkdir /mnt/disk1pi@raspberrypi~$ sudo mkdir /mnt/disk2

The above commands have made 2 new directories for us to use.

To test they exist typepi@raspberrypi~$ ls /mnt

it should show the following if all is ok­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­disk1disk2­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

5. Now we need to attach the disks to these folders so we have to edit the /etc/fstab filethat is used my the operating system on bootup to connect the physical disks to the

175

Page 176: MrRsPiManualGuide-KernelPanic

filesystem.pi@raspberrypi~$ sudo nano /etc/fstab

This will show the following­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­proc /proc proc defaults 0 0/dev/mmcblk0p1 /boot vfat defaults 0 0#/dev/mmcblk0p3 none swap sw 0 0­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

We need to add the bottom 2 lines for the 2 disk drives, please note that the entry vfat orntfs-3g is dependant on your disk type and should be modified accordingly.If you have only attached one device only create the relevent entry for that disk.

­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­proc /proc proc defaults 0 0/dev/mmcblk0p1 /boot vfat defaults 0 0#/dev/mmcblk0p3 none swap sw 0 0/dev/sda1 /mnt/disk1 ntfs­3g defaults 0 0/dev/sdb1 /mnt/disk2 vfat defaults 0 0­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

To make the files visible to the filesystem typepi@raspberrypi~$ sudo mount ­a

This will try to mount the new devices into /mnt/disk1 and /mnt/disk2 - so to test if it hasworked type

pi@raspberrypi~$ ls /mnt/disk1This should now list any files on the disk that you have put there. If this is not the casethen check that the disk types are correct in /etc/fstab

6. Now we need to install a software package called samba which will allow a unix box toshare windows files.

pi@raspberrypi~$ sudo apt­get install sambaWait while stuff flies up the screen and type y at any yes/no promptsDepending on the Distro you are using you may need to install this, so do it anyway.

pi@raspberrypi~$ sudo apt­get install samba­common­bin

7. When all is complete then the samba package has been installed so will need configuringfor your setup, so you will need to edit the /etc/samba/smb.conf file.

pi@raspberrypi~$ sudo nano /etc/samba/smb.confThe things that possibly need changing are the workgroup entry set to WORKGROUP for XPand previous operating systems and HOME for Windows 7 and above (not sure what is thedefault for Vista).workgroup = WORKGROUPThen i would comment out the following lines by adding a ; to the front of the item as thismakes initial setup and testing easier.

­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­;[homes]; comment = Home Directories; browseable = no;[printers]; comment = All Printers; browseable = no; path = /var/spool/samba; printable = yes; guest ok = no

176

Page 177: MrRsPiManualGuide-KernelPanic

; read only = yes; create mask = 0700;[print$]; comment = Printer Drivers; path = /var/lib/samba/printers; browseable = yes; read only = yes; guest ok = no;[cdrom]; comment = Samba server's CD­ROM; read only = yes; locking = no; path = /cdrom; guest ok = yes; preexec = /bin/mount /cdrom; postexec = /bin/umount /cdrom­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

Then finally at the end add your windows share name - i will use a share name ofusband will share out the content of /mnt/disk1 - to share the other disk, addanother entry as below with the share name within the [ ] and the path to the otherdisk drive.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­[usb]comment = USB Sharepath = /mnt/disk1writeable = Yesonly guest = Yescreate mask = 0777directory mask = 0777browseable = Yespublic = yes­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

8. At last we can restart samba and test the configuration so to restart samba.pi@raspberrypi~$ sudo service samba restart

and to check the shares and configuration runpi@raspberrypi~$ sudo testparm ­s

this should show something similar to that below­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­Load smb config files from /etc/samba/smb.confrlimit_max: rlimit_max (1024) below minimum Windows limit (16384)Processing section "[usb]"Loaded services file OK.Server role: ROLE_STANDALONE[global]server string = %h serverobey pam restrictions = Yespam password change = Yespasswd program = /usr/bin/passwd %upasswd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n*password\supdated\ssuccessfully* .unix password sync = Yessyslog = 0log file = /var/log/samba/log.%mmax log size = 1000dns proxy = Nowins support = Yespanic action = /usr/share/samba/panic­action %d

177

Page 178: MrRsPiManualGuide-KernelPanic

[usb]comment = USB Sharepath = /mnt/disk1read only = Nocreate mask = 0777directory mask = 0777guest only = Yesguest ok = Yes­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

If you get the above info then you need to add the pi user to the samba user databasewhich is not the same as the pi username/password but can be so

pi@raspberrypi~$ sudo smbpasswd ­a piThis will add a pi user with the password you typed in for windows to connect with.

Now try connecting to the server using windows map network drive. On Windows XP youwill see the following. So type \\raspberrypi\usb in the Folder field.

Now click on the [Connect using a different user name] link and enter raspberrypi\piinthe user name field and raspberry in the password field.NOTE: windows will always by default try your username and password from your PC tomake the connection (in my case my PC is called VNET and my username is simon so yousee VNET\simon in the window), and as we only have the one user on theRaspberry Pi,we have to specify that the user connecting is one that exists on the Pi. We also have toalso specify the machine that the user is on before the user name therefore the usernameis raspberrypi\pi.

178

Page 179: MrRsPiManualGuide-KernelPanic

Then click [OK] which will close the pop-up and [Finish], this should now map your drive tothe Raspberry Pi NAS server.

9. Right the samba share is working, however if you reboot the Pi then the drive will not beauto mounted, and therefore the share will be empty - so we will need to install acommand called autofs which is designed to automatically mount usb disk drives.

pi@raspberrypi~$ sudo apt­get install autofsThis will install the auto usb mounting system.

9. However we need to set up a config file to allow the automounting of the usb disk.pi@raspberrypi~$ sudo vi /etc/auto.master

At the end of the file is the following­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­+auto.master­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

You need to add the following below the +auto.master entry­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­+auto.master/media/ /etc/auto.ext­usb ­­timeout=10,defaults,user,exec,uid=1000­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

Now you can reboot and the server will keep on working and sharing your windows files onboot

179

Page 180: MrRsPiManualGuide-KernelPanic

SOFTWARE ­ XBMC 174

XBMC is the best media software I have ever used. I’ve been a fan and been a ‘user’ since the days ofthe old XBMC4Xbox! It was the major factor as to WHY I jailbroke my iPad!

However as this guide is for the raspberry pi let’s deal with that!

I’ve tried both Xbian and RaspBMC.

XBian seems stable but is only updated half as often. Both seem to work well. RaspBMC has theadvantage of being one of the standard installs for NOOBS. N.B. I had trouble with the RaspBMC usingNOOBS, if you’re using the ‘Auto Update’ feature it can baulk your install (this is allegedly fixed with thenewest update!). Better to do a custom build if it is one you are using all the time! (I have 2 floatingaround the house, this may become 3, with one hooked up to the Stereo!)

You’ll need to install the following bits of software if you’re trying to do anything clever.

sudo apt­get install git­clone unzip

Booting to Black ScreenThe raspberry pi seems to have some issues with some TVs, where it will seemingly boot to blackscreen. I think this is something to do with the HDMI stopping supplying power or something and the Pidefaulting to the Composite Video Out. To stop this edit the Config.txt on the root of the card ensuring ithas the following (the last 3 lines are the most important!)

arm_freq=840core_freq=350gpu_freq=253force_turbo=1disable_overscan=1gpu_mem=128start_file=start_x.elffixup_file=fixup_x.dathdmi_force_hotplug=1hdmi_group=1hdmi_mode=16

180

Page 181: MrRsPiManualGuide-KernelPanic

Windows 7 and Adding SourcesI have had issues with a Windows 7PC *(or several of them on the same network not showing upinXBMC, to fix this ensure they have STATIC IP addresses. When adding sources don’t bother searchingjust use

smb://<fixed ip>/<share>, so my TV folder would be smb://192.168.1.1/Tv

Also ensure when adding shares to Windows tha tyou use ADVANCED SHARING, EVERYONE should havepermissions.

Right Click on Folder Properties Sharing Advanced Sharing Permissions Check that ‘Everyone’ is etc with at least ‘read’ allow ticked.

181

Page 182: MrRsPiManualGuide-KernelPanic

How to add Sources/Repos/AddonsThe best way to get additional plugins, addons and Repos (repositories that will auto update yoursoftware when new versions become available!) etc is to add the sources etc.

In XBMC goto ‘Programs­>File Manager’, then ‘Add source’.

2 Excellent sources to add are

XBMC: http://xbmc.flirc.tvInstall the repository so when updates are available it will update automatically.Then install the Addon.

Fusion: http://fusion.xbmchub.com(install Addons Via Zip File, choose the hubwizard­beta)From the Repo

By adding them as sources it will make it easier to install the additional addons. (instead of browsing forlocal Zip Files, you can then browse for Zip files from the online sources.

Goto ‘Videos­>Addons’ choose the ‘XBMC HubWizard’, wait for the launcher to run then choose the‘Android’ install. This will install a ton of addons, but it will also mess up some of your defaults so beprepared to set things up again! (It will also change the boot logo and your wallpaper, so have thoseready too!)

Get the FLIRC Plugin from the GitHub ­ https://github.com/flirc/flirc­xbmc­plugin

182

Page 183: MrRsPiManualGuide-KernelPanic

Custom XML for better remote usage (at least on our big telly!!!)

sudo nano /$HOME/.xbmc/userdata/keymaps/remote.xml

<keymap> <FullscreenVideo> <remote> <select>OSD</select>

<subtitle>ShowSubtitles</subtitle> <red>ShowSubtitles</red>

</remote> </FullscreenVideo><Visualisation> <remote> <select>OSD</select> <right>SkipNext</right> <left>SkipPrevious</left> <back>Back</back> </remote></Visualisation><global> <remote> <menu>ContextMenu</menu> </remote> </global></keymap>

Fixing TV Scraper ErrorSometime if you’re using sources and scanning XBMC will come up with ‘unable to be connect to source,continue scanning error… this can get boring. I think it’s something to do with theTVDB and the scraper.This seemed to fix it for me.

You may have to create / edit the following file./$HOME/.pi/.xbmc/addons/metadata.tvdb.com/tvdb.xml

Hi ive edit the .xml myself and also got episode information working in fact tested 100% working on

my frodo

sorry if it takes up too much space but i dunno how else to post it for others but use this

exactly as is (save as tvdb.xml and replace in folder)

<?xml version="1.0" encoding="UTF-8"?><!-- should be self-explanatory --><scraper framework="1.1" date="2009-01-27"><NfoUrl dest="3"><RegExp input="$$1" output="&lt;urlcache=&quot;\1-$INFO[language].xml&quot;&gt;http://thetvdb.com/api/1D62F2F90030C444/series/\1/all/$INFO[language].zip&lt;/url&gt;&lt;id&gt;\1&lt;/id&gt;" dest="3"><expression>http://thetvdb.com/(?:index\.php)?\?tab=series&amp;id=([0-9]+)</expression></RegExp><RegExp input="$$1" output="&lt;details&gt;&lt;url cache=&quot;tt\1.xml&quot;function=&quot;GetTVDBId&quot;&gt;http://thetvdb.com/api/GetSeriesByRemoteID.php?imdbid=tt\1&amp;amp;langu

183

Page 184: MrRsPiManualGuide-KernelPanic

age=$INFO[language]&lt;/url&gt;&lt;/details&gt;" dest="3+"><expression>imdb....?/title/tt([0-9]*)</expression></RegExp><RegExp input="$$1" output="&lt;details&gt;&lt;url cache=&quot;tt\1.xml&quot;function=&quot;GetTVDBId&quot;&gt;http://thetvdb.com/api/GetSeriesByRemoteID.php?imdbid=tt\1&amp;amp;language=$INFO[language]&lt;/url&gt;&lt;/details&gt;" dest="3+"><expression>imdb....?/Title\?([0-9]*)</expression></RegExp></NfoUrl>

<GetTVDBId dest="3"><RegExp input="$$1" output="&lt;details&gt;&lt;urlcache=&quot;\1-$INFO[language].xml&quot;&gt;http://thetvdb.com/api/1D62F2F90030C444/series/\1/all/$INFO[language].zip&lt;/url&gt;&lt;id&gt;\1&lt;/id&gt;&lt;/details&gt;" dest="3"><expression>&lt;seriesid&gt;([0-9]*)&lt;/seriesid&gt;</expression></RegExp></GetTVDBId>

<EpisodeGuideUrl dest="3"><RegExp input="$$1" output="\1" dest="3"><expression>(.*?http://thetvdb.com.*)</expression></RegExp><RegExp input="$$1" output="\1" dest="3"><expression>(.*?http://thetvdb.com.*)</expression></RegExp></EpisodeGuideUrl>

<!-- input: $1=query string --><!-- returns: the url we should use to do the search --><CreateSearchUrl dest="3"><RegExp input="$$1" output="&lt;urlcache=&quot;cache-\1$$4.xml&quot;&gt;http://thetvdb.com/api/GetSeries.php?seriesname=\1$$4&amp;amp;language=$INFO[language]&lt;/url&gt;" dest="3"><RegExp input="$$2" output="%20(\1)" dest="4"><expression clear="yes">(.+)</expression></RegExp><expression/></RegExp></CreateSearchUrl>

<!-- input: $1=html $2=search query --><!-- returns: results in xml format<results><movie><title>*</title><url>*</url>*#urls<extra>*</extra></movie>*</results> --><GetSearchResults dest="1"><RegExp input="$$4" output="&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;standalone=&quot;yes&quot;?&gt;&lt;results&gt;\1&lt;/results&gt;" dest="1"><RegExp input="$$1" output="&lt;entity&gt;&lt;title&gt;\3&lt;/title&gt;&lt;language&gt;\2&lt;/language&gt;&lt;urlcache=&quot;\1-\2.xml&quot;&gt;http://thetvdb.com/api/1D62F2F90030C444/series/\1/all/\2.zip&lt;/url&gt;&lt;id&gt;\1&lt;/id&gt;&lt;/entity&gt;" dest="4"><expressionrepeat="yes">&lt;seriesid&gt;([0-9]*)&lt;/seriesid&gt;[^&lt;]*&lt;language&gt;([^&lt;]*)&lt;/language&gt;[^&lt;]*&lt;SeriesName&gt;([^&lt;]*)&lt;/SeriesName&gt;</expression></RegExp><expression noclean="1"/></RegExp></GetSearchResults>

<!-- input: $1..#urls=html --><!-- input: $(#urls+1): extra !--><!-- returns: results in xml format<details><plot>*</plot><director>*</director><premiered>*</premiered><episodeguide>*</episodeguide></details> --><GetDetails dest="7"><RegExp input="$$4" output="&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;standalone=&quot;yes&quot;?&gt;&lt;details&gt;\1&lt;/details&gt;" dest="7"><RegExp input="$$1" output="\1" dest="5"><expression noclean="1">&lt;Series&gt;.*?&lt;id&gt;$$2&lt;/id&gt;(.*)</expression></RegExp><RegExp input="$$5" output="&lt;plot&gt;\1&lt;/plot&gt;" dest="4"><expression noclean="1">&lt;Overview&gt;([^&lt;]*)&lt;/Overview&gt;</expression></RegExp><RegExp input="$$2" output="&lt;id&gt;\1&lt;/id&gt;" dest="4+"><expression/></RegExp><RegExp input="$$1" output="&lt;mpaa&gt;\1&lt;/mpaa&gt;" dest="4+"><expression>&lt;ContentRating&gt;([^&lt;]*)&lt;/ContentRating&gt;</expression></RegExp>

184

Page 185: MrRsPiManualGuide-KernelPanic

<RegExp input="$$5" output="&lt;premiered&gt;\1&lt;/premiered&gt;" dest="4+"><expression>&lt;FirstAired&gt;([^&lt;]*)&lt;/FirstAired&gt;</expression></RegExp><RegExp input="$$5" output="&lt;rating&gt;\1&lt;/rating&gt;" dest="4+"><expression>&lt;Rating&gt;([^&lt;]*)&lt;/Rating&gt;</expression></RegExp><RegExp input="$$5" output="&lt;studio&gt;\1&lt;/studio&gt;" dest="4+"><expression>&lt;Network&gt;([^&lt;]*)&lt;/Network&gt;</expression></RegExp><RegExp input="$$5" output="&lt;title&gt;\1&lt;/title&gt;" dest="4+"><expression>&lt;SeriesName&gt;([^&lt;]*)&lt;/SeriesName&gt;</expression></RegExp><RegExp input="$$5" output="\1" dest="10"><expression noclean="1">&lt;Genre&gt;([^&lt;]*)&lt;/Genre&gt;</expression></RegExp><RegExp input="$$10" output="&lt;genre&gt;\1&lt;/genre&gt;" dest="4+"><expression repeat="yes">([^\|]*)\|</expression></RegExp><RegExp input="$$10" output="&lt;genre&gt;\1&lt;/genre&gt;" dest="4+"><expression repeat="yes">([^,]*),</expression></RegExp><RegExp input="$$10" output="&lt;genre&gt;\1&lt;/genre&gt;" dest="4+"><expression>([^\|,]+)$</expression></RegExp><!-- actors with thumbs --><RegExp input="$$5"output="&lt;actor&gt;&lt;name&gt;\2&lt;/name&gt;&lt;role&gt;\3&lt;/role&gt;&lt;thumb&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;&lt;/actor&gt;" dest="4+"><expression repeat="yes"noclean="1,2,3">&lt;Actor&gt;.*?&lt;Image&gt;([^&lt;]+)&lt;/Image&gt;.*?&lt;Name&gt;([^&lt;]*)&lt;/Name&gt;.*?&lt;Role&gt;([^&lt;]*)</expression></RegExp><!-- actors without thumbs --><RegExp input="$$5" output="&lt;actor&gt;&lt;name&gt;\2&lt;/name&gt;&lt;role&gt;\3&lt;/role&gt;&lt;/actor&gt;"dest="4+"><expression repeat="yes"noclean="1,2,3">&lt;Actor&gt;.*?&lt;Image&gt;([^&lt;]*)&lt;/Image&gt;.*?&lt;Name&gt;([^&lt;]*)&lt;/Name&gt;.*?&lt;Role&gt;([^&lt;]*)</expression></RegExp><RegExp input="$$5" output="&lt;thumbaspect=&quot;banner&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;series&lt;/BannerType&gt;[^&lt;]*&lt;BannerType2&gt;graphical&lt;/BannerType2&gt;[^&lt;]*&lt;Language&gt;$INFO[language]&lt;/Language&gt;</expression></RegExp><RegExp input="$$5" output="&lt;thumbaspect=&quot;banner&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;series&lt;/BannerType&gt;[^&lt;]*&lt;BannerType2&gt;graphical&lt;/BannerType2&gt;[^&lt;]*&lt;Language&gt;((?!$INFO[language])[a-z])*&lt;/Language&gt;</expression></RegExp><RegExp input="$$5" output="&lt;thumbaspect=&quot;banner&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;series&lt;/BannerType&gt;[^&lt;]*&lt;BannerType2&gt;text&lt;/BannerType2&gt;[^&lt;]*&lt;Language&gt;$INFO[language]&lt;/Language&gt;</expression></RegExp><RegExp input="$$5" output="&lt;thumbaspect=&quot;banner&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;series&lt;/BannerType&gt;[^&lt;]*&lt;BannerType2&gt;text&lt;/BannerType2&gt;[^&lt;]*&lt;Language&gt;((?!$INFO[language])[a-z])*&lt;/Language&gt;</expression></RegExp><RegExp input="$$5" output="&lt;thumbaspect=&quot;banner&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;series&lt;/BannerType&gt;[^&lt;]*&lt;BannerType2&gt;blank&lt;/BannerType2&gt;[^&lt;]*&lt;Language&gt;&lt;/Language&gt;</expression></RegExp><RegExp input="$$5" output="&lt;thumb aspect=&quot;poster&quot; type=&quot;season&quot;season=&quot;\2&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;season&lt;/BannerType&gt

185

Page 186: MrRsPiManualGuide-KernelPanic

;[^&lt;]*&lt;BannerType2&gt;season&lt;/BannerType2&gt;[^&lt;]*&lt;Language&gt;$INFO[language]&lt;/Language&gt;[^&lt;]*[^S]*Season&gt;([0-9]+)&lt;/Season&gt;</expression></RegExp><RegExp input="$$5" output="&lt;thumb aspect=&quot;poster&quot; type=&quot;season&quot;season=&quot;\3&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;season&lt;/BannerType&gt;[^&lt;]*&lt;BannerType2&gt;season&lt;/BannerType2&gt;[^&lt;]*&lt;Language&gt;((?!$INFO[language])[a-z])*&lt;/Language&gt;[^&lt;]*[^S]*Season&gt;([0-9]+)&lt;/Season&gt;</expression></RegExp><RegExp input="$$5" output="&lt;thumb aspect=&quot;banner&quot; type=&quot;season&quot;season=&quot;\2&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;season&lt;/BannerType&gt;[^&lt;]*&lt;BannerType2&gt;seasonwide&lt;/BannerType2&gt;[^&lt;]*&lt;Language&gt;$INFO[language]&lt;/Language&gt;[^&lt;]*[^S]*Season&gt;([0-9]+)&lt;/Season&gt;</expression></RegExp><RegExp input="$$5" output="&lt;thumb aspect=&quot;banner&quot; type=&quot;season&quot;season=&quot;\3&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;season&lt;/BannerType&gt;[^&lt;]*&lt;BannerType2&gt;seasonwide&lt;/BannerType2&gt;[^&lt;]*&lt;Language&gt;((?!$INFO[language])[a-z])*&lt;/Language&gt;[^&lt;]*[^S]*Season&gt;([0-9]+)&lt;/Season&gt;</expression></RegExp><RegExp input="$$5" output="&lt;thumbaspect=&quot;poster&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;poster&lt;/BannerType&gt;</expression></RegExp><RegExp input="$$5" output="&lt;thumb aspect=&quot;poster&quot; type=&quot;season&quot;season=&quot;-1&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;poster&lt;/BannerType&gt;</expression></RegExp><RegExp conditional="fanart" input="$$7" output="&lt;fanarturl=&quot;http://thetvdb.com/banners/&quot;&gt;\1&lt;/fanart&gt;" dest="4+"><RegExp input="$$5" output="&lt;thumb dim=&quot;\2&quot; colors=&quot;\3&quot;preview=&quot;_cache/\1&quot;&gt;\1&lt;/thumb&gt;" dest="7+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;fanart&lt;/BannerType&gt;[^&lt;]*&lt;BannerType2&gt;([^&lt;]*)&lt;/BannerType2&gt;[^&lt;]*&lt;Colors&gt;([^&lt;]*)&lt;/Colors&gt;[^&lt;]*&lt;Language&gt;$INFO[language]&lt;/Language&gt;</expression></RegExp><RegExp input="$$5" output="&lt;thumb dim=&quot;\2&quot; colors=&quot;\3&quot;preview=&quot;_cache/\1&quot;&gt;\1&lt;/thumb&gt;" dest="7+"><expressionrepeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;fanart&lt;/BannerType&gt;[^&lt;]*&lt;BannerType2&gt;([^&lt;]*)&lt;/BannerType2&gt;[^&lt;]*&lt;Colors&gt;([^&lt;]*)&lt;/Colors&gt;[^&lt;]*&lt;Language&gt;((?!$INFO[language])[a-z])*&lt;/Language&gt;</expression></RegExp><expression noclean="1"/></RegExp><RegExp input="$$2" output="&lt;episodeguide&gt;&lt;urlcache=&quot;$$2-$INFO[language].xml&quot;&gt;http://thetvdb.com/api/1D62F2F90030C444/series/\1/all/$INFO[language].zip&lt;/url&gt;&lt;/episodeguide&gt;" dest="4+"><expression/></RegExp><expression noclean="1"/></RegExp></GetDetails>

<!-- input: $1=html !--><!-- input: $2=series url !--><!-- returns: results in xml format<episodeguide><episode><title>*</title><url>*</url><season>*</season><epnum>*</epnum><thumb>*</thumb><id>*</id><aired>*</aired></episode>*</episodeguide> !--><GetEpisodeList dest="3"><RegExp input="$$4" output="&lt;episodeguide&gt;\1&lt;/episodeguide&gt;" dest="3"><RegExp input="$$2" output="\2-\3" dest="10"><expression>http://thetvdb.com/api/(.+)/series/([0-9]*)/all/(.+).zip</expression></RegExp><RegExp conditional="!dvdorder"><!-- Regular episodes (Absolute order) --><RegExp conditional="absolutenumber" input="$$1"output="&lt;episode&gt;&lt;id&gt;\1&lt;/id&gt;&lt;title&gt;\2&lt;/title&gt;&lt;aired&gt;\3&lt;/aired&gt;&lt;epnum&gt;\4&l

186

Page 187: MrRsPiManualGuide-KernelPanic

t;/epnum&gt;&lt;season&gt;1&lt;/season&gt;&lt;url cache=&quot;$$10.xml&quot;&gt;$$2&lt;/url&gt;&lt;/episode&gt;"dest="4+"><expressionrepeat="yes">&lt;Episode&gt;.*?&lt;id&gt;([0-9]*).*?&lt;EpisodeName&gt;([^&lt;]*).*?&lt;FirstAired&gt;([^&lt;]*).*?&lt;absolute_number&gt;([0-9]*).*?&lt;/Episode&gt;</expression></RegExp><!-- Specials (Absolute order) --><RegExp conditional="absolutenumber" input="$$1"output="&lt;episode&gt;&lt;id&gt;\1&lt;/id&gt;&lt;title&gt;\2&lt;/title&gt;&lt;aired&gt;\4&lt;/aired&gt;&lt;epnum&gt;\3&lt;/epnum&gt;&lt;season&gt;0&lt;/season&gt;&lt;url cache=&quot;$$10.xml&quot;&gt;$$2&lt;/url&gt;&lt;/episode&gt;"dest="4+"><expressionrepeat="yes">&lt;Episode&gt;.*?&lt;id&gt;([0-9]*).*?&lt;EpisodeName&gt;([^&lt;]*).*?&lt;EpisodeNumber&gt;([0-9]*).*?&lt;FirstAired&gt;([^&lt;]*).*?&lt;SeasonNumber&gt;0&lt;/SeasonNumber&gt;.*?&lt;/Episode&gt;</expression></RegExp><!-- Normal episodes --><RegExp conditional="!absolutenumber" input="$$1" output="&lt;episode&gt;&lt;title&gt;\2&lt;/title&gt;&lt;urlcache=&quot;$$10.xml&quot;&gt;$$2&lt;/url&gt;&lt;epnum&gt;\3&lt;/epnum&gt;&lt;season&gt;\5&lt;/season&gt;&lt;id&gt;\1&lt;/id&gt;&lt;aired&gt;\4&lt;/aired&gt;&lt;/episode&gt;" dest="4"><expressionrepeat="yes">&lt;Episode&gt;.*?&lt;id&gt;([0-9]+).*?&lt;EpisodeName&gt;([^&lt;]*).*?&lt;EpisodeNumber&gt;([0-9]+)[^&lt;]*.*?&lt;FirstAired&gt;([^&lt;]*)&lt;/FirstAired&gt;.*?&lt;SeasonNumber&gt;([0-9]+)[^&lt;]*.*?&lt;/Episode&gt;</expression></RegExp></RegExp><!-- DVD order --><RegExp conditional="dvdorder" input="$$1" output="&lt;episode&gt;&lt;title&gt;\4&lt;/title&gt;&lt;urlcache=&quot;$$10.xml&quot;&gt;$$2&lt;/url&gt;&lt;epnum&gt;\2&lt;/epnum&gt;&lt;season&gt;\3&lt;/season&gt;&lt;id&gt;\1&lt;/id&gt;&lt;aired&gt;\5&lt;/aired&gt;&lt;/episode&gt;" dest="4"><expressionrepeat="yes">&lt;Episode&gt;.*?&lt;id&gt;([0-9]+).*?&lt;Combined_episodenumber&gt;([^&lt;]*).*?&lt;Combined_season&gt;([^&lt;]*).*?&lt;EpisodeName&gt;([^&lt;]*).*?&lt;FirstAired&gt;([^&lt;]*)&lt;/FirstAired&gt;.*?&lt;/Episode&gt;</expression></RegExp><expression noclean="1"/></RegExp></GetEpisodeList>

<!-- input: $1=html --><!-- returns: results in xml format<details><writer>*</writer><director>*</director><cast>*</cast><rating>*</rating><rank>*</rank><plot>*</plot> --><GetEpisodeDetails dest="3"><RegExp input="$$4" output="&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;standalone=&quot;yes&quot;?&gt;&lt;details&gt;\1&lt;/details&gt;" dest="3"><RegExp input="$$1" output="\1" dest="8"><expression noclean="1">&lt;Episode&gt;.*?&lt;id&gt;$$2&lt;/id&gt;(.*?)&lt;/Episode&gt;</expression></RegExp><RegExp input="$$1" output="&lt;uniqueid&gt;$$2&lt;/uniqueid&gt;" dest="4"><expression/></RegExp><RegExp input="$$8" output="&lt;plot&gt;\1&lt;/plot&gt;" dest="4+"><expression>&lt;Overview&gt;([^&lt;]*)&lt;/Overview&gt;</expression></RegExp><RegExp input="$$8" output="\1" dest="6"><expression noclean="1">&lt;Writer&gt;([^&lt;]*)&lt;/Writer&gt;</expression></RegExp><RegExp input="$$6" output="&lt;credits&gt;\1&lt;/credits&gt;" dest="4+"><expression repeat="yes">([^\|]*)\|</expression></RegExp><RegExp input="$$6" output="&lt;credits&gt;\1&lt;/credits&gt;" dest="4+"><expression repeat="yes">([^,]*),</expression></RegExp><RegExp input="$$6" output="&lt;credits&gt;\1&lt;/credits&gt;" dest="4+"><expression>([^\|,]+)$</expression></RegExp><RegExp input="$$8" output="\1" dest="6"><expression noclean="1">&lt;Director&gt;([^&lt;]*)&lt;/Director&gt;</expression></RegExp><RegExp input="$$6" output="&lt;director&gt;\1&lt;/director&gt;" dest="4+"><expression repeat="yes">([^\|]*)\|</expression></RegExp><RegExp input="$$6" output="&lt;director&gt;\1&lt;/director&gt;" dest="4+"><expression repeat="yes">([^,]*),</expression></RegExp><RegExp input="$$6" output="&lt;director&gt;\1&lt;/director&gt;" dest="4+"><expression>([^\|,]+)$</expression>

187

Page 188: MrRsPiManualGuide-KernelPanic

</RegExp><RegExp input="$$8" output="\1" dest="6"><expression noclean="1">&lt;GuestStars&gt;([^&lt;]*)&lt;/GuestStars&gt;</expression></RegExp><RegExp input="$$6" output="&lt;actor&gt;&lt;name&gt;\1&lt;/name&gt;&lt;/actor&gt;" dest="4+"><expression repeat="yes">([^\|]*)\|</expression></RegExp><RegExp input="$$6" output="&lt;actor&gt;&lt;name&gt;\1&lt;/name&gt;&lt;/actor&gt;" dest="4+"><expression repeat="yes">([^,]*),</expression></RegExp><RegExp input="$$6" output="&lt;actor&gt;&lt;name&gt;\1&lt;/name&gt;&lt;/actor&gt;" dest="4+"><expression>([^\|,]+)$</expression></RegExp><RegExp input="$$8" output="&lt;title&gt;\1&lt;/title&gt;" dest="4+"><expression>&lt;EpisodeName&gt;([^&lt;]*)&lt;/EpisodeName&gt;</expression></RegExp><!-- Regular Episodes - Absolute Order --><RegExp conditional="absolutenumber" input="$$8"output="&lt;season&gt;1&lt;/season&gt;&lt;episode&gt;\2&lt;/episode&gt;" dest="4+"><expression>&lt;SeasonNumber&gt;([1-9]*)&lt;/SeasonNumber&gt;.*?&lt;absolute_number&gt;([0-9]*)&lt;/absolute_number&gt;</expression></RegExp><!-- Specials - Absolute Order --><RegExp conditional="absolutenumber" input="$$8"output="&lt;season&gt;0&lt;/season&gt;&lt;episode&gt;\1&lt;/episode&gt;" dest="4+"><expression>&lt;EpisodeNumber&gt;([0-9]*)&lt;/EpisodeNumber&gt;.*?&lt;SeasonNumber&gt;0&lt;/SeasonNumber&gt;</expression></RegExp><!-- Normal Season/Episodes --><RegExp conditional="!absolutenumber" input="$$9" output="&lt;season&gt;\1&lt;/season&gt;" dest="4+"><RegExp conditional="!dvdorder" input="$$8" output="\1" dest="9"><expression clear="yes">&lt;SeasonNumber&gt;([^&lt;]*)&lt;/SeasonNumber&gt;</expression></RegExp><RegExp conditional="dvdorder" input="$$8" output="\1" dest="9"><expression>&lt;Combined_season&gt;([^&lt;]*)&lt;/Combined_season&gt;</expression></RegExp><expression/></RegExp><RegExp conditional="!absolutenumber" input="$$9" output="&lt;episode&gt;\1&lt;/episode&gt;" dest="4+"><RegExp conditional="!dvdorder" input="$$8" output="\1" dest="9"><expression clear="yes">&lt;EpisodeNumber&gt;([^&lt;]*)&lt;/EpisodeNumber&gt;</expression></RegExp><RegExp conditional="dvdorder" input="$$8" output="\1" dest="9"><expression>&lt;Combined_episodenumber&gt;([^&lt;]*)&lt;/Combined_episodenumber&gt;</expression></RegExp><expression/></RegExp><RegExp input="$$8" output="&lt;thumb&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"><expression>&lt;filename&gt;([^&lt;]+)&lt;/filename&gt;</expression></RegExp><RegExp input="$$8" output="&lt;aired&gt;\1&lt;/aired&gt;" dest="4+"><expression>&lt;FirstAired&gt;([^&lt;]+)&lt;/FirstAired&gt;</expression></RegExp><RegExp input="$$8" output="&lt;displayseason&gt;\1&lt;/displayseason&gt;" dest="4+"><expression>&lt;airsbefore_season&gt;([^&lt;]+)&lt;/airsbefore_season&gt;</expression></RegExp><RegExp input="$$8" output="&lt;displayepisode&gt;\1&lt;/displayepisode&gt;" dest="4+"><expression>&lt;airsbefore_episode&gt;([^&lt;]+)&lt;/airsbefore_episode&gt;</expression></RegExp><RegExp input="$$8" output="&lt;displayafterseason&gt;\1&lt;/displayafterseason&gt;" dest="4+"><expression>&lt;airsafter_season&gt;([^&lt;]+)&lt;/airsafter_season&gt;</expression></RegExp><RegExp input="$$8" output="&lt;rating&gt;\1&lt;/rating&gt;" dest="4+"><expression>&lt;Rating&gt;([^&lt;]+)&lt;/Rating&gt;</expression></RegExp><RegExp input="$$1" output="&lt;runtime&gt;\1&lt;/runtime&gt;" dest="4+"><expression>&lt;Runtime&gt;([^&lt;]+)&lt;/Runtime&gt;</expression></RegExp><expression noclean="1"/></RegExp></GetEpisodeDetails></scraper>

188

Page 189: MrRsPiManualGuide-KernelPanic

Setting up a Shared LibraryBasic Explination here ­http://lifehacker.com/5634515/how­to­synchronize­your­xbmc­media­center­across­every­room­in­the­house

Full guide ­http://wiki.xbmc.org/index.php?title=HOW­TO:Share_libraries_using_MySQL(N.B. Only use version 5.5 of SQL the latest version 5.6 doesn’t work!)

First setup the SQL DB.1. Download a copy of MySQL server from http://dev.mysql.com/downloads/mysql/2. Select Standard configuration3. Create a password when asked4. Select that you want the database to have network access when prompted during installation.5. Open the "MySQL Command Line Client" from the MySQL start menu6. Enter the following commands:

1. Type in: CREATE USER 'xbmc' IDENTIFIED BY 'xbmc'; and press return2. Type in: GRANT ALL ON *.* TO 'xbmc'; and press return

7. Close out the command line tool8. In Windows 7, you may need to make an exception in the "Windows Firewall"

1. Go to control panel and open windows firewall2. Click on advanced settings3. Click on Inbound Rules, then new rule4. Chose the port option, click next5. Then type in the port number you set mysql to use(Default is 3306)6. Make sure Allow the connection is checked then click next7. Name it MYSQL Inbound(or whatever you want) then click finish8. Use these same steps to set up the Outbound exception then name it MYSQL Outbound(or whatever you

want) then you're finished.9. You may or may not have to set up both in and outbound, someone with more knowledge please edit this if you

know.10. In Windows XP, you may need to make an exception in the "Windows Firewall"

1. Open Control Panel and Set to 'Classic View'2. Double Click on Windows Firewall3. Click on Exception­­>Add Port4. Name It MySQL XBMC or whatever you want5. Then type in the port number you set mysql to use(Default is 3306)

Edit the advancedsettings.xml

(in the userdata folder!)

GNU nano 2.2.6 File: /$HOME/.xbmc/userdata/advancedsettings.xml Modified

<advancedsettings><videodatabase><type>mysql</type><host>192.168.1.2</host><port>3306</port><user>xbmc</user><pass>xbmc</pass><name>xbmc_video</name></videodatabase>

<musicdatabase><type>mysql</type><host>192.168.1.2</host><port>3306</port>

189

Page 190: MrRsPiManualGuide-KernelPanic

<user>xbmc</user><pass>xbmc</pass><name>xbmc_music</name></musicdatabase>

<videolibrary>

<importwatchedstate>true</importwatchedstate>

<backgroundupdate>true</backgroundupdate> <!­­ set to hide the $

</videolibrary>

<videoscanner> <ignore errors>true</ignore errors><videoscanner>

</advancedsettings>

190

Page 191: MrRsPiManualGuide-KernelPanic

Remote Controls.There are many ways to control XBMC on the Pi.You can use a mouse, which has limited functionality.You can use a keyboard, a little difficult to navigate sometimes.You can use remote (£30 from CPC) or from a chinese wholesaler if you’re not in a rush ­http://www.tomtop.com/computers­networking/hausbell­2­4g­mini­wireless­qwerty­keyboard­mouse­touchpad­for­pc­notebook­android­tv­box­htpc­c1705.html

This works remarkably well, comes with arechargeable phone battery and reciever.

You need direct line of site, but half the price.

The final option is to use your phone / ipad / tabletetc. Most of them have XBMC remote apps. Theofficial iOS xbmcRemote app works well, althoughI would recommend using static IP. (it can thencontrol multiple instances (just not at the sametime!)

To do this you will need to turn on Zeroconf in theXBMC ­> Settings ­> Services­> Zeroconf.

I’d also recommed you change the network ID ofeach of the Pi’s if you’re using multiple ones. (seeelsewhere in this guide!)

191

Page 192: MrRsPiManualGuide-KernelPanic

Accessing Region Locked Content. :)Getting the iPlayer to work in the States, or 1 channel or FreeCable plugins to work outside the US­of­A isa pain in the butt. However I have recently had some success using the excellent Tunlr service,admittedly you have to fiddle a bit with XBMC settings, but ttings, but not too dtastically. Basically it jutrequires you to set hte Primary DNS server to theirs. In RaspBMC goto the RaspBMC settings ­>Network and just enter the dteails, sometimes you’ll ahve to check the numbers, other times you mightahve to choose thihjeir backup serverseir backup server. Through this I’ve watched episdoes of the‘Colbert Report’ on Comedy Central, an episode of ‘ANTM’ on theCW, and an ‘Intervention’ on A&E. I willkeep this updated .

Plugins I know are working. Plugins that are currently broken.

Video iPlayer FreeCable 1Channel Navi­X IceFilms YouTube Vimeo Radbox

Audio 8Tracks PBS Digitally IMported

VideoDemand 54OD(both are broken till someone can reverseengineer thei encryption)

Get iPlayerAlthough technically not XBMC as this is designed to run in Raspbian this sounded useful and pretty cool.This software should allow you to capture and record BBC programs from iPlayer (of course this wont’work if you’re outside GB unless you’re smart with a Proxy. (see www.tunlr.com)

Full instructions here.http://raspi.tv/2012/get_iplayer­full­instructions­for­raspberry­pi­install­from­scratch

192

Page 193: MrRsPiManualGuide-KernelPanic

USEFUL BITS OF PYTHON 187

Running A Console Command Via PythonFirst

import os

The call any command you would usually type in the console using

os.system(‘<command>’)

Notice the single quotes, you can use multiple commands, string them together using && or use single &to put them in the background.

Passing Arguments to Python programsYou can pass arguments to python progams, e.g. TwitterPhoto.py listed later

python TwitterPhoto.py ‘arg1’ ‘arg2’

in the python code you can then recall these usingx = sys.argv[1]y = sys.argv[2]

Changing Terminal Text Colours / Effects Via PythonThis I would have thought would have been simple enough, sadly it was not. The only way I found to dothis was to download and address a python module called colorama, ensure you call the commandsFore, Back, Style etc from the colorama script. then use print(<colour bit> + ‘message’)

from colorama import Fore, Back, Styleprint(Fore.RED + 'some red text')print(Back.GREEN + and with a green background')print(Style.DIM + 'and in dim text')print(+ Fore.RESET + Back.RESET + Style.RESET_ALL)print('back to normal now')

Quick Python Pygame Joystick Axis Detection (Tested and Rechecked.)From here

#!/usr/bin/env python

import pygameimport timeimport math

193

Page 194: MrRsPiManualGuide-KernelPanic

# init controllerpygame.init()controller = pygame.joystick.Joystick(0)controller.init()print 'Xbox Controller Connected'

print '/*********************************/'print ' Joystick Drive Program 'print "Updated by MRO for XBox Pad "print '/*********************************/'

key = 0y = 0x = 0

while key != 'q': for event in pygame.event.get(): if event.type == pygame.JOYAXISMOTION:

#Print out the Axis pressed and the Value turned out (usually between ­1 and 1) print "Axis: ",event.axis," Value: ",event.value

if event.axis == 1: y = event.value

# to make these less sensetive turn them to 0.5s (for bigger deadzone?) if math.fabs(y) < 0.2: y = 0 if event.axis == 0: #I had to check this value using the above event.axis!!! x = event.value if math.fabs(x) < 0.2: x = 0

# Display the correct output hopefully! command = ' ' if y < 0: command = 'up' elif y > 0: command = 'down' elif x < 0: command = 'left' elif x > 0: command = 'right'

if command != ' ':print command

Using Pygame to detect Joystick Presses<from here> N.B. I had to change the ‘def print’ function to ‘def printout’ as this conflicted with Python’s exisiting printcommand. No biggy. Just change textprint.print to textpring.printout

import pygame

# Define some colorsBLACK = ( 0, 0, 0)WHITE = ( 255, 255, 255)

# This is a simple class that will help us print to the screen# It has nothing to do with the joysticks, just outputing the# information.class TextPrint: def __init__(self): self.reset() self.font = pygame.font.Font(None, 20)

def print(self, screen, textString): textBitmap = self.font.render(textString, True, BLACK) screen.blit(textBitmap, [self.x, self.y]) self.y += self.line_height

194

Page 195: MrRsPiManualGuide-KernelPanic

def reset(self): self.x = 10 self.y = 10 self.line_height = 15

def indent(self): self.x += 10

def unindent(self): self.x ­= 10

pygame.init()

# Set the width and height of the screen [width,height]size = [500, 700]screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

#Loop until the user clicks the close button.done = False

# Used to manage how fast the screen updatesclock = pygame.time.Clock()

# Initialize the joystickspygame.joystick.init()

# Get ready to printtextPrint = TextPrint()

# ­­­­­­­­ Main Program Loop ­­­­­­­­­­­while done==False: # EVENT PROCESSING STEP for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done=True # Flag that we are done so we exit this loop

# Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUPJOYHATMOTION if event.type == pygame.JOYBUTTONDOWN: print("Joystick button pressed.") if event.type == pygame.JOYBUTTONUP: print("Joystick button released.")

# DRAWING STEP # First, clear the screen to white. Don't put other drawing commands # above this, or they will be erased with this command. screen.fill(WHITE) textPrint.reset()

# Get count of joysticks joystick_count = pygame.joystick.get_count()

195

Page 196: MrRsPiManualGuide-KernelPanic

textPrint.print(screen, "Number of joysticks: ".format(joystick_count) ) textPrint.indent()

# For each joystick: for i in range(joystick_count): joystick = pygame.joystick.Joystick(i) joystick.init()

textPrint.print(screen, "Joystick ".format(i) ) textPrint.indent()

# Get the name from the OS for the controller/joystick name = joystick.get_name() textPrint.print(screen, "Joystick name: ".format(name) )

# Usually axis run in pairs, up/down for one, and left/right for # the other. axes = joystick.get_numaxes() textPrint.print(screen, "Number of axes: ".format(axes) ) textPrint.indent()

for i in range( axes ): axis = joystick.get_axis( i ) textPrint.print(screen, "Axis value: :>6.3f".format(i, axis) ) textPrint.unindent()

buttons = joystick.get_numbuttons() textPrint.print(screen, "Number of buttons: ".format(buttons) ) textPrint.indent()

for i in range( buttons ): button = joystick.get_button( i ) textPrint.print(screen, "Button :>2 value: ".format(i,button) ) textPrint.unindent()

# Hat switch. All or nothing for direction, not like joysticks. # Value comes back in an array. hats = joystick.get_numhats() textPrint.print(screen, "Number of hats: ".format(hats) ) textPrint.indent()

for i in range( hats ): hat = joystick.get_hat( i ) textPrint.print(screen, "Hat value: ".format(i, str(hat)) ) textPrint.unindent()

textPrint.unindent()

# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

# Go ahead and update the screen with what we've drawn. pygame.display.flip()

# Limit to 20 frames per second

196

Page 197: MrRsPiManualGuide-KernelPanic

clock.tick(20)

# Close the window and quit.# If you forget this line, the program will 'hang'# on exit if running from IDLE.pygame.quit ()

197

Page 198: MrRsPiManualGuide-KernelPanic

Pi Club 192Here’s a rough list of what happened at Pi­Club, attendance, issues, problems etc.

Session 1 ­ Basic Setup (Network) and Minecraft (an Easy Win)What worked­ Explain to kids they need a few commands to get them working on the network!­ Giving kids memory cards to look after / keeping hold of those kids did not want to take away.­ Giving kids small identifying sticker (from my £1.99 Lego sticker book) Put them on the cards so theyknow who’s is who’s. Get cards stored in little wallet to carry around!­ Get kids to use every other computer in my room setup, then they can open this document on the otheras a reference.­ Sort out memory stick of Awesome (with stuff needed to be passed around)­ Nice to see some kids bringing their OWN Pi’s!!!!

Session 2 ­ USB Rocket LaunchersGot out 4 new USB Rocket Launchers explained about commands etc. Got them to acquire files etc.

Issues­ Getting all the darts back! (although most kids after explination and cost were very, very good!)­ Not enough USB Hubs (must buy 2 more!)­ Not enough exposed / accessible power sockets for hubs.­ 2 of the rocket launcher only seem to fire from certain hubs, they’d move, but not fire!

Session 3 ­ Quake 3 and Emulation (DGEN?)Quake 3 Basic install!Compiling your own code!DGen (test if this work via a smbget!)Games.­ Discuss legality of ROMs and full version of Quake 3.

Suggestions:Currently some of the stuff in this doc requires access to sites like dropbox etc that are blocked by theschool proxy. I tried working around this with GDrive, but it’s a real faff. I stumbled upon a solution that Ithought was reasonable. Setup your /home/pi/ folder as a SAMBA share, (see guide), then get the kids toinstall SAMBA, you can then use ‘smbget’ rather than ‘wget’ to grab files directly from the Master Pi!(instead of just the AWESOME Pendrive).

What Worked.:smbget did work, even when the Pi was running as a server! Problems arose when the kids hadn’texpanded the root fs to fill the card and a couple of the cards got full. 4GB isn’t THAT big! Get 8GBs if

198

Page 199: MrRsPiManualGuide-KernelPanic

you can. One or two cards had a bit of corruption, this seems to happen if you power the Pi’s via USBand connect them upto a high drain device, like the rocket launcher??? Q3 Areana was good fun, wediscussed custom servers, even ran the one at the front as a dedicated server, even better when one‘bright spark’ realised he could KICK people off using various commands (I wouldn’t have thought of doingthat!)

What didn’t work:DGen / Snes9x ­ Despite the setup of the Megadrive 2 with Sonic 2 and the Pi running DGen (that seemswell fussy with SDL­DispMax (still can’t run on my own card!). I didn’t explain this very well. Suggest kidsgo away and find models. One kid suggested he’s like to create his own (off the back of the minecraftskinning, assuming it was just JPG files to edit!) I explained he’d need to learn a little 3d modelling. Imight see if I can find a guid on this! (Perhaps Sketchup to Q3 Arean!) I did offer rewards for kids thatemailed me links to level’s / Mods, got one to the Simpson’s neighbourhood, however this would not runon the Pi due to the memory limitations, nothing else! But I did find some collective map packs,lvl_10th_Anniversary pack, seemed to be quite good. Will have a play with some modifiers perhaps tryrunning ‘The Dark Conjunction’ mod. (now I have realised what the BAT files do!, just call the standardquake exe (or in this case .arm) with some arguments!) One issue I found with Q3 on the whiteboardwas the teeny tiny console font (in Q3 console, not the BASH!).

Session 4 ­ Breakout Board(s), Wiring bits?Suggestions:Screaming Jelly Baby?Intro to Python?

What Worked:By this time I’ve had a couple of student asking about setting up wireless adapters (as most routers areoften away from their rooms!). The first one was a simple enable in X and disable the school bits in/etc/apt/apt.conf (# out the school proxy). The second was issues installing drivers??? Still unsovled, butworking on it. A smaller group this time (due to 2 week absense and school trip to Holland!). Talked thebriefly through the project. Introduced the Cobbler Kit, or bits, showed the Pins, explained they’re aninterace to the outside world. Printed off 5 copies of the ‘Singing Jellybaby’ OCR Worksheet as a basis.The more able students were EAGER to get going on this, one got through very quickly and moved on.Another followed this up later and then tried expanding up on the idea, but wanted to change the textcolour in the Terminal of his output (found a python plugin called colorama), With a bit of tweaking gotthis done! By this point those not interested in the GPIO etc were able to get up and running / networkedon Quake3 or Minecraft without much assistance. Keep backing up the SD Card Image!

What Didn’t WorkFor many this was their first introduction to writing python scritps, some struggled with syntax. I didn’texplain about Tabbing your code (across the page for loops etc). This caused one or two issues. Shouldhave checked earlier the MP3 was available. If done again grab the MP3, or create their own (Have MICsetup for this!).

199

Page 200: MrRsPiManualGuide-KernelPanic

Session 4.5 ­ Fail.This was a bit of a damp squid. Getting back from 2 weeks off, unprepared and without any resources. Itwas a mulling around session and kids were distracted. Not a great turn out. Kids still not takingownership of memory cards. Need more incentives / rewards???

Session 5 ­ Robot Arm.

What WorkedOne pupil was keen to try out the XBMC distro he’d found. Was able to setup and use his phone ashotspot. Managed to stream lots of videos from YouTube.Let kids loose on the Robot Arms that I’d got via STEM budget, they’re fun to build, but the kids need*SOME* support. However one or two students really enjoyed creating them. Hoped to get them hookedup to Pi’s but ran out of time. Managed to get the code for it to work with PS3 Pad (Wired I assume!) Butthen forgot the PS3 pad. Found a Year 11 to fetch one at lunch. But they never came back. :( (Don’t relyon Year 11s for kit!) Years 7­9 more reliable. Howeve they’re not allowed off site.

What didn’t work.Forgetting equipment. Have multiples of everything for usage? This is one option. Need to write up moretutorials, get laptops that were promised so can do SSH, a great way of getting large chunks of codequickly on the Pis! School won’t let it be installed on the desktops! Boo. Security Risk Apparently!

Session 6 ­ Pi Camera.

What WorkedDemonstrated the camera, had a brief discussion about the Camera, why not USB, the fact uses fastbus. Looked at the physical camera, commented on size, compared it to phone camera. Demo’d itdoing basic photo capture, then a bit of video capture. The magic was kept alive as this was donethrough the magic of WinSCP which allowed quick access / viewing of photos. Nice that had a year 9trying to download Quake 3 Mods, he eventually (through the school proxy) found a few. Then haddiscussion on how to get this onto Quake on the Pi, discussed how AWESOME wget command was,then via SSH enabled browser access on the Pi (this is different to just using the proxy at the bash!) andhe browsed on the Pi, found the file, downloaded the link, unzipped, put on the pi and tested! Hemanaged to find a good level that was a DJ Deck, if you stood on the desk you spun!!! Had one kids stillbuilding robot arm, this has taken him nearly 4 sessions, but is almost complete! The other bright sparkwanted Pi Club stickers, so we killed a tree going through publisher lining up margins etc, only to finallyprint on the laser and was badly aligned, but the child learnt quite a lot about Publisher, borders, paperetc.

What didn’t work.Wanted to try stop motion capture and possibly web streaming. This would have been brilliant to getstudents next door (or on any other computer on the school network viewing the camera output. I did nothowever have time to get this working in the club. (further reading and fiddly configuration shoudl havebeen done before the club. Kids were marvelled at lego case that I have my Pi in, perhaps provide tutorialPDF of instructions.

200

Page 201: MrRsPiManualGuide-KernelPanic

Session 6.5 ­ A Short Pi Club due to meetings and other commitments.Talked about Torrents (Legal downloading of large files) as tried to demonstrate how I could not downloadCrunchBang at school via the system as it was a torrent and ports are blocked at school, so would haveto do this at home. Want to be able to run Pi next to computer setup. Works better that way! Lessguessing! Did show that you could take over another students Pi by SSHing to it.

What WorkedGetting kids to log on to PCs and setup Pis relatively quickly.Getting kids to write their IP Addresses on the whiteboard!

It’s worth downloadig useful videos, the Gigafide (Tinkernut) YouTube on how to hack minecraft is usefuland funny too. well worth grabbing for later use. ­ http://www.youtube.com/watch?v=YsXumCkcxLw

What didn’t workThe Github seemed blocked at school! (sigh another issue!)Had lots of trouble setting up my end (laptop, and project screen hardly visible in the bright light!

Session 7 ­ Minecraft Hacking on the Pi using Python Scripts?POA ­ Get Minecraft running on the Pi’s create a couple of custom ‘simple’ scripts to allow people to hackminecraft, demonstrate how to get the PyScripts from the site (have them downloaded already, just incase!) then run via SSH for extra awesomeness???

What WorkedWhat Didn’t work.

Session 8 ­ PiFM (Pirate Radio!)POA ­ Get students to see how simple it is to get FM signal from a Pi.Get students to record a piece of audio (convert to correct format!)Get them to play it back out, possibly write a script to make the signal loop round and round (perhaps aZombie test message? Like I did.)Setup Live Mic Example (tested and working).Get them to run around the school testing just how far the signal will go. Also freak out random studentsif you have a good clear view of the atrium!

Session 9 ­ TwitteringThis requires the students to have Access to TWITTER! (otherwise the twitter API will not work!)Show them how you call the API each time with useful bits of info!

201

Page 202: MrRsPiManualGuide-KernelPanic

COST OF STUFF / PRICE GUIDE 196

Product VendorApproxCost

Raspberry Pi. Farnell £30.00Suitable Adapter Plug Farnell / RS £5.00HDMI Cable (ASDA VALUE) £3.00HDMI ­> DVI Cable EBay £3.00USB Hub (Powered) EBay / Amazon. £7.00Keyboard Generic (Go Wilkinsons / Similar) £5.00PS3 Control Pad Amazon (Must be Genuine!) £30Mouse Generic £5.00Bluetooth Adapter Poundland £1.00Wireless Adapter Amazon (Edimax) £8.00Prototype Board Kit Ebay £10.00Cobbler Interface Cable Adafruit £8.50Pi Case SK Pang £12.50Memory Cards 8GB www.MemoryBits.co.uk or www.7dayshop.com £7USB Remote Control Play.com / Ebay £5.00Textstar LCD Module Cool Components £28.00Remote ATV ‘The Bear’(kit, with 3x Motors) www.IWoot.com £20.00Assorted Electronic Components (Chips andLCDs etc) Maplins £10.00Jumper Wires (Motherboard type for LCD) Maplins £3.99GERT Board www.farenell.com £40.00Random LCD Displays Hitachi HD44780 LCDcontroller Compatible Ebay £20.00Motor Driver Chips and Breadboard BreakoutBits http://www.hobbytronics.co.uk £18.00Robot Arm (USB) Maplins £30.00Pi­Car Pi­Car.com £30.00

LED Strip Lights (12volt)

Ebay (user ­http://myworld.ebay.co.uk/gomepls?_trksid=p2047675.l2559) £4.00

Armtel Board (for lighting) ­ NooGroove USBBoard ­ ATMEGA32U2 (AT90USB162) AVRStick Ebay £11New 5V 8 Channel Relay Module Board forArduino PIC AVR M Ebay £6.00Solar Charger Online (Paypal) ­ [email protected] £20.00

PS3 Eyetoy Game (2nd Hand) £2

LED Borg http://www.piborg.com/ledborg £5

3.5" TFT LCD Car Rear View Monitor ColorScreen DVD VCR For Car Backup Camera

Ebay £12.03

Dream Cheeky USB Rocket Launcher Amazon. £29

TV Tuner (USB) ­ August DVB­T205 USBFreeview Tuner Stick

Amazhttp://www.amazon.co.uk/gp/product/B002EHVP9C/ref=oh_details_o00_s00_i00?ie=UTF8&psc=1on

£15

DC Power Supply (3­12V) Wilkos £5

Pebble Power Supply Scan.co.uk £14

Forward PowerTube Phone Battery Scan.co.uk £9

202

Page 203: MrRsPiManualGuide-KernelPanic

Pi Bow Case www.pimoroni.com £13

Camer Mount thepihut.com £3

Pi Heatsink thepihut.com £1

Pi Noodle Cable thepihut.com £3

Pi Vesa Mount (Slice) thepihut.com £5

Cheap Pocket Radio to test PiFM Poundland £1

PiHub http://shop.pimoroni.com/products/pihub £25 (incshipping)

Burger Speakers (USB Charge and fittedaudio jack.)

ebay £3

203

Page 204: MrRsPiManualGuide-KernelPanic

Linux Mini Guide (for Laptop / PC) 198Here is just where I will jot down some experiences that I’ve had since I’ve been bold enough to dabblewith Linux on Desktops / Laptops.I’d recommend you start with LiveUSBs/DVDs.I’ve tried different Debian based distros.Ubuntu seems pretty friendly, but didnt’ work very well on old tech.Linux Mint seems stable and works with many things out of the box!

Create a Live USB with Persistance.This means you don’t loose the settings you’ve done / created every time.

This software LILI ­ Linux Live USB Creator allows you to add persistance to a live linux distro (CurrentlyTesting with Mint!)

How to Enable SSH on Linux Mint 15 /14 / 13 / 12

I have noticed that a lot of people do not know how to enable SSH on Linux Mint systems, so I havedecided to make this article.

To enable SSH (secure shell) on Linux Mint 15 Olivia, Linux Mint 14 Nadia, Linux Mint 13 Maya and LinuxMint 12, all you have to do is install the SSH package, which isopenssh­server.

sudo apt­get updatesudo apt­get install openssh­server

sudo passwd mint<enter a new password!>

VNC on Linux to Pi

Install the VNCViewer softwaresudo apt­get install vncviewervncviewer <ip address of pi> :1

204