100% found this document useful (1 vote)
1K views

MrRsPiManualGuide KernelPanic

Currently Working on: Setting up Newsreader on a Pi yourraspberrypi / Mini CNC Laser Engraver DukePad Cloud Lamp Sonic Pi Internet Radio Receiver. NFC with the Pi. 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 do a serious school test!!!

Uploaded by

Aldinei Aragão
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views

MrRsPiManualGuide KernelPanic

Currently Working on: Setting up Newsreader on a Pi yourraspberrypi / Mini CNC Laser Engraver DukePad Cloud Lamp Sonic Pi Internet Radio Receiver. NFC with the Pi. 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 do a serious school test!!!

Uploaded by

Aldinei Aragão
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 204

(Pleasewaitwhilethisloads!DonttryopeningonaPiatall,itwonteverfinish!

DedicatedtoJohnRoutledge 03/02/4710/05/2013. Heneverhidthescrewdrivers! andPenelopeAliceRoutledge 21stJuly2013

LastUpdated:12thNov2013TotalPages204 1

RandomLinkstoSort.

http://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/robot/getting_started/ http://pkgs.org/ http://www.moop.org.uk/index.php/2013/08/10/voicecontrolledlights/ WinSCPnotabletocopyfiles?


D e f a u l t s ! a u t h e n t i c a t e

Tothe/etc/sudoersfile.

CurrentlyWorkingon: SettingupNewsreaderonaPi http://www.howtogeek.com/162060/howtoinstallnzbgetforlightweightusenetdownloadingon yourraspberrypi/ MiniCNCLaserEngraver http://funofdiy.blogspot.co.uk/2013/10/araspberrypicontrolledminilaser.html DukePadhttps://wiki.openjdk.java.net/display/OpenJFX/DukePad CloudLamphttp://falldeaf.com/2013/07/thepicontrolscript/ SonicPihttp://www.cl.cam.ac.uk/projects/raspberrypi/sonicpi/teaching.html http://www.raspberrypi.org/phpBB3/viewtopic.php?f=63&t=58313&p=438279 InternetRadioReceiver. http://www.tommedley.com/403/raspberrypiradios/ NFCwiththePI. http://learn.adafruit.com/adafruitnfcrfidonraspberrypi/overview https://docs.google.com/viewer?url=http://learn.adafruit.com/downloads/pdf/adafruitnfcrfidonr aspberrypi.pdf&chrome=true RaspberryPiCameramoduleWebStreamingusingMotion. http://www.raspberrypi.org/phpBB3/viewtopic.php?p=356814 IKEALightsHack

SettingupthePiasanWirelessAccessPoint http://learn.adafruit.com/settinguparaspberrypiasawifiaccesspoint?view=all PiratePi??? 2

Minecraftrendering3DOBJModels(Cthulhudidntworkverywell,nyancattofollow!) SiriProxyTestatschool? UsingCamerasWorkingwithPS3Eyetoy(onlyconnectedtoPiThough,notthehub!!!), multiplecamerasrunningwilltrytimelapsevideonext,timelapseupandrunning,butneedtodo aseriousschooltest!!!(removedtheIRsensorfromaPS3Eyetoy,nowwillpickupInfrared,or moreimportantlyifyoubathestuffinanIRLight(strongerthanWiiBar)youcanseewhats happeninginthedark!!! EmulationStationselectedPSXgamesnotworking. CUPS(PrintingfromLinux!)Testedandneedtweaking,tryatschool. Telnethttp://www.youtube.com/watch?v=NS6t8HnrrXw PiUihttp://blog.davidsingleton.org/introducingpiui/ ConnectingyourPitoGMail http://mitchtech.net/connectraspberrypitogmailfacebooktwittermore/ RemotePiAccess http://pihw.wordpress.com/guides/directnetworkconnection/ PiasaNAS http://www.makeuseof.com/tag/turnyourraspberrypiintoanasbox/ QRCodesonthePi. http://linuxg.net/scanqrcodesinubuntuwithlibdecodeqrsimpletest/ http://linuxaria.com/pills/qrcodeinlinux?lang=en Qreator??? http://ralgozino.wordpress.com/2011/06/13/howtocreateanddecodeaqrcodeinpythonusingqrtools/ ZBarhttps://github.com/herbyme/zbarQRCodeChecker. XBOX360Ring/RFTransmitterHack. http://www.astrorats.org/blog/2013/07/29/xbox360rfmoduleandtheraspberrypi/ RFIDIdeas http://www.raspberrypi.org/phpBB3/viewtopic.php?f=37&t=55321&p=419718 PiPresentshttps://github.com/KenT2/pipresentsnext http://pipresents.wordpress.com

OnthebackburnerStufftotrywhenpartsarrive!:) 4
LEDINDICATOR(Somegoodstuffhere)
http://www.howtogeek.com/140063/buildanledindicatorwitharaspberrypiforemailweatheroranythi ng/

CheapPIRSensors.
http://www.raspberrypispy.co.uk/2013/01/cheappirsensorsandtheraspberrypipart1/

BerryClip
http://www.youtube.com/watch?v=r4kHfQ0cJI&feature=emsubs_digest

HowtousePiasalowpowernetworkstoragedevice.
http://www.howtogeek.com/139433/howtoturnaraspberrypiintoalowpowernetworkstoragedevice/

SteepenMotorController?
I ordered two from 4tronix_uk on eBay and they arrived the next day. There are additional details in the Stepper Motor 28BJY-48 Datasheet
http://www.raspberrypispy.co.uk/2012/07/steppermotorcontrolinpython/

UltrasonicDistanceMeter
http://www.raspberrypispy.co.uk/2012/12/ultrasonicdistancemeasurementusingpythonpart1/

StuffIdliketobuyifIhadthecash. 4
PILiteLEDMatrix
http://cpc.farnell.com/ciseco/b040/piliteledmatrixraspberrypi/dp/SC13018?in_merch=New%20Produc ts&MER=ebb4500001002

RapiroRobotKit
http://www.kickstarter.com/projects/shota/rapirothehumanoidrobotkitforyourraspberryp

Frindo
http://robotbits.co.uk/robotkits/frindorobotkit/prod_162.html

GeneralLinks.

OfficialPiStuff
http://www.raspberrypi.org/TheofficialSite. http://www.themagpi.com/TheMagazine http://www.raspians.com/RaspberryCommunityProjects OCRGuides/RecepieSheetsGuidesandTutorials http://pibeginners.com/PiBeginnersYoutubeClips. http://downloads.raspberrypi.org/Raspberry_Pi_Education_Manual.pdfPiEducationManual.

PythonandProgramming
http://www.codecademy.com/Agreatprgrammingplacetostart. http://pythondictionary.codeit.co.uk/PythonDicitonary/Resource. http://www.pythoncode.co.ukGoodexamples/tutorials/questions.(BasedonPython3) http://www.ictvideohelp.co.uk/python.htmlPythonVideos. http://usingpython.com/UsingPython http://www.pythontutor.com/visualize.html#code=#Enteryourpythonprogramhere.%0A#Press'Visualize Execution'toseeitrunninglinebyline! http://www.tutorialspoint.com/python/index.htmSeemslikeasimpleresourcewithexamples. http://www.staff.city.ac.uk/afl/tinybasic/index.htmlTinyBasic http://inventwithpython.comSomegoodguidesofPython/Pygame. http://pythonbooks.revolunet.com/Agoodselectionofpythonbooks.

LinuxGeneral
http://elinux.org/RPi_HubGreatsourceforPiinfo/hardware. http://linuxmanpages.comLinuxCommands,nofuss. http://unix.stackexchange.com/LinuxQ&AForums.

YoutubeLinks/Channels
GigaFide/Tinkernut RaspberryPiTutorialshttp://www.youtube.com/user/RaspberryPiTutorials RaspberryPiIVBeginners http://www.youtube.com/user/raspberrypitutorials OCRPiTutorials

Foreword

Myfatherdiedsuddenlyat66.Thisdocumentwouldnotexistwithouthim.Hedidnoteffectitdirectly,(or probablyevenknowofitsexistence)WhenIwasaboyIwantedtoworkwithcomputers,likedaddy.I alsoseemedtohaveaknackattakingthingsappart.LuckilyformeDadneverhidhistoolsorthe screwdrivers,theywerealwaysacouplealwayspresentintheDrawofDoom,(EVERYhousehasone, usuallyasmalldrawfullofbits,fuses,atorch,batteriesandotherassortedguff.)Imadegooduseofthem tofulfilmycuriosityofwhatwasinsidethings!Indirectsupportoftengoesunnoticed,butThanksDadI oweyou! Thisdocumenthasbeenalabouroflove.IvespentfartoolongmessingwithPisandnotwritingstuff down.Ihopethisguideisuseful.Itwillbeforme,buthopefullyitwillgetpassedintothehandsof students.Thosewithmoretimetoexperienceandmesswiththesystem,tocontinuetoinnovate,design, createandbestofalldream!Idontmeantotreadonanyonestoesandalotofthisiscopiedand/or pastedfromtweb. Thisdocumentisascaffold,itwilltakeyoutonumerouswebsites,istotallyfulloferrors/mistakesandhalf completedinstructions,butlikeIsayithascometogetheroverayearandIplantokeepaddingtoit.If youfindamistakeorwishtoaddtoitthenEmailme,Illfixit.(Similarlyifyouwantanythingthatis explicityyoursandyoudontwantsharingthenagainemailme!) ThisdocumentisverymuchNOTmyownwork,justTONSofstuffthatIvecopiedfromotherpeoplessites andhardwork.Assuchpleaseshareandsharealike,thatswhattheoriginalauthorswouldwant!(Not thecreativecommonslinkatthetop!) IdliketosayTHANKStoeveryonetheguys(andgals)attheRaspberryPiorganisationthatdaredtocreate, seeaprojectthroughandhopefullyreaptherewards.Thepeoplewhohavecreatedindividualprojects/ tutorialsetcthatIvelovinglyfollowedandallthosewhooffertonsofhelpandsupportontheforums. Onapersonalnote,thanks,itsbeenjusttheboot(upthea*se)Ineededtolearnsomenewstuff,Linux, PythonandforthefirsttimesinceUni,pickbackupmyMultimeter!Lettheprojectsbegin!AlthoughIm notveryinnovativemyselfIlovetakingotherpeoplesideas,givingthemago,andmaybecombining them! Thankstoallthosewhohavespentthetimelisteningtomerabbitonabouthowgoodtheselittleboards are.ToLloydforkeepingmebusywithtechnicalquestions,Arronforhelpingmefindanswersand toleratingmyLinuxstupidityandLewisfortheblindbeliefthatIcouldgetLinuxrunningonhisNetbook.I hopeyoubothdowellinthefuture. FinallyanapologytomywifeasImsathereinthesmallhoursofthemorningwhenIshouldbeinbed, knowingthatImgoingtobeknackeredtomorrow,butImkeepingmynogginbusyandthatsimportant too!Asthisdocumentapproaches200pagesIwonderjusthowmanyhoursIvespentdabbling!Bugger. Keeponhacking. MrR.

Contents

7
2 4

*RandomLinkstoSort.* OnthebackburnerStufftotrywhenpartsarrive!:) LEDINDICATOR(Somegoodstuffhere) CheapPIRSensors. BerryClip HowtousePiasalowpowernetworkstoragedevice. SteepenMotorController? UltrasonicDistanceMeter StuffIdliketobuyifIhadthecash. PILiteLEDMatrix RapiroRobotKit Frindo *GeneralLinks.* OfficialPiStuff* PythonandProgramming* LinuxGeneral* YoutubeLinks/Channels* Foreword* Contents *FAQs* BackYourcardupoften!(everycoupleofweeks!) Whathappensif(when)youcorruptyourmemorycard! Constantkeyyyyyyyyyyyyyyyyyyyyyyyyyboardpresses CorruptMemorycard ConstantReboots. RebootswhenyouplugsomethingUSBin! FallingofftheNetworkRandomly AptgetupdateFails. SSHontheschoolsystem??? TheHardware HowtocheckwhatRPi.GPIOversionyouhave HowtocheckyourRaspberryPiRevisionnumber? *DISTROs.* BackinguptheMemorycardusingthePI(working) SetupRaspbianMemorySplitandconfig. UpdateandInstallupdatedpackages! RecommendedPackagestoInstall(Youllprobablyneedthemlater!) RPiupdateFirmware sudorpiupdate *GitHubsWorthCloning* BackingupfilestoGDrive(Tested) *PCSoftwaretogetfamiliarwith* SSHKitttySSHorPutty

6 7 15

18

20

24 7

WIN32Imager 7Zip AdvancedIPScanner UltraVNC(Portable) Geany/NinjaIDE.(versionsavailableforbothWindozeandPI!) WinSCP Xming/XmingPortable(notgotthisworkingforme!:() MobaXTermWorksaswellasVNC UsefulLinuxCommands* cd~ ls mv cp mkdir rm ifconfig hcitool nano vi less aptgetinstall aptgetpurge aptcachesearch history dmesg grep > wget help du df R ps && & depmod file cat Anoteaboutthecommandprompt InstallingSoftware/Drivers VI(Calledusingvi)aBasicTextEditorlikeNANO! Editafile,lookatit,stopediting UsingGREPProperly. Basicsyntax AdditionalArguments SYSTEM SettingaStaticIP(networkaddress) HowtoChangeYourRaspberryPi(orOtherLinuxDevices)Hostname 26

30

WhyDoIWanttoDoThis? ChangingtheHostonyourPi SettingupWiFi* Settingupadhocwifi *SchoolSiteProxyInfo(toremember) EditthisfiletosetPermanentlyAcrossAllProfiles. AllowprogramsotherthanBashaccesstoa(school)networkunderProxy. TemporarilyfromtheLXTerminal(notidealandonlyworksforROOT!) ChangingtheFontSizeoftheTerminalText sudodpkgreconfigureconsolesetup ChoosingwhichprogramsrunwhenthePiboots SettingupVNC* VNChttp://myraspberrypiexperience.blogspot.co.uk/p/settingupvnc.html RunningVNCServeratStartup SoundonthePi.* CheckAlsa&removePulse! Testthesoundusing ForceHDMIsoundusing MakingthePiSpeak* SOXTheSwissKnifeofWAV/RawaudioonLinux MPG321 TurningyourRaspberryPiintoanFMTransmitter* VoiceRecognitiononthePiusingGoogleVoiceAPI AskingWolframAlphaQuestions TextToSpeech CombiningSpeechtoTextandTexttoSpeech. *MountingaUSBtheEasyWay!* ...Orthehardway PrintingonaPi.* MakingaProgramLOOPFOREVER* Makingaprogramrepeateverysooften(CRONJobs!)* HARDWARE Cases RaspberryPiGPIOLayoutRevision2 GPIOStuff ConnectingaPitotheoutsideworld PINBasics MakinganLEDFlash *LedBORGhttp://www.piborg.org/ledborg Rev2,20130910or3.6.11+build#538 Usage 45

ControllingLedBorg TosetthecolourfromaPythonscript: Tosetthecolourfromaterminaltype: Tosetthecolourfromaterminalwiththebasicdrivertype: TodisableLedBorgfromaterminaltype: ToenableLedBorgfromaterminaltype: Managingbootoptions Singing/ScreamingJellyBaby(ProbablyworkswithFruitPastelstoo!) Makesoundplaybackthroughtheheadphonesocket PiCameraModule HowtousetheRaspberryPicamerasoftware Examplecommands ToshootvideowiththeRaspberryPiCamera BerrycamPhotos(Tested) TimeLapsePhotos TimeLapseVideofromStills. ConvertingtheVideooutput ExtraTricksbyBillTidey WatermarkingwithanotherGraphic! UsingthePiCameramodulewithMotion CreepyFaceTracking(PartlyTested) CheapPIRSensorsandtheRaspberryPiPart1(untested) RobotArmStuff. RobotArmBasics RobotArmwithPS3Pad RobotArmWithWiiMote RobotArmGUI(inPython)WIP 7SegmentDisplayProject(Oneofmyfirst!) ** Chipsfordrivingmotors LCDSetup Cheap3.5LCDDisplay. HARDWAREControllers GraphicsTesting/VisualJoystickTest WiimoteBasics* Gettingthedrivers/setup RunningWiiMoteasaMouse. WiiMoteButtonMappings WIIMoteInfo CreatingCustomWiiMoteConfigs UsingWiiMotesinPythonProjects XBox360Pad* InstalltheXBoxPadDrivers. Createamappingfile 84

10

AlternativeSetupForXBMC. Callthemappingusing UsingaPS3controller* Dualshock3andRaspberryPI PS3Move??? PS3JoystickButtonsandAxes QJoyPadTurningJoystickCommandsintoKeypresses. HARDWAREUSBDevices* WIFIADAPTER??? TPLinkwn725n(V2) EdimaxDongle PS3CameraTestunderXDE. PS3EyetoyCameraStreaming FaceRecognitiononthePi. GUVCVIEW CMAKE OPENCV InstallthefacerecognitionAPI InstalltheRecoProgram FINALLY... RemovingtheIRFilteronTheEyetoy UsingMultipleCameraswithMotion Retaliation(USBRocketMOD!) RetaliationModificationtoScript.(TOREDOtouseKEYBOARD!) TVHeadTestforXBMC SOFTWARE GitHubsWhyTheyRock! Howtocloneyourrepotoyourlocalmachine? CompilingYourOwnVersionofSoftware(Rollyourown!) Grab Configure Make MakeInstall SOFTWAREInterfacing PiWall(WORKING!) Settinguptheunits. Networkconfiguration Testingthesoftware LoopinganVideoonthescreens. MulticastingInputfromthePiCamera(untested!) Fritzing PICar UsingTwitter 98

109

111

11

CreatingAnArrayofFollowers(PartlyTested) CreatingaPythonScriptthatcanTweet(Tested) CreatingaPythonScriptthatcanTweetImages(Tested) CreateaPythonScriptthatcanTweetImagesViaRaspicam,watermarkthemandTweet Them CreatingaPythonScripttoOutputSystemInfo TweetingonaSetInterval ReadOutTweets(Untested) TweetingWebcamPics(PartTested) ReadingTweetsfroma#Tag CreatingaTweetBot SOFTWAREGAMES 123 AgoodlistofGamesthatrunonthePi SDLDispManx Q3ArenaonRASPPI(Build) Quake3QuickInstallSchoolBuild SchoolBuildErrorsolutions ORfixthepermissionssononrootusescanaccess/dev/input/miceand/dev/input/mouse0 asfollows. Createnewfilein"/etc/udev/rules.d/99input.rules" Addanewgroupandaddyouruser(s)toit(myloginisjust'pi') Soundthroughheadphones ShowFPSinGame Quake3ConfigFileGuide FullversionofQuake3. Q3Models,Levels,MapsandExtras Q3ConsoleManual Quake2onthePi. InstallingQuake2onPi InstallingDOOM1/2 OPTIONAL:CreateaWADspecificlauncher OPTIONAL2:CreatealaucherformultiplekindsofDoom InstallingAliensTCandAliensDoom3.0(AVP)inChocolateDoom. InstructionsforLANplay InstallingMinecraftonthePi. CustomTexturesPacks PythonScriptsforMinecraft. Rendering3DModelsintheMinecraftWorld MakingtheOBJFiles. Viewing3DMeshesonaPi. wgethttp://jestermon.weebly.com/uploads/1/6/2/1/1621282/pyobjviewer.zip ListofMinecraftBlocks MinecraftTwitter(untested) InstallingDescentonthePi(untested) 12

SOFTWAREGamesEmulation ANoteaboutROMS RetroPieEmcompassingMostEmulators. RetroPieXBoxPad RetroPieExitGamesUsingYourControllers RetroPieInstallingROMs MAME NES SnesEmulatorSNES9x ScummVM DGen DGenManual. DGenBuildInstructions TweakingDGen SonicLevelSelect DGenCONTROLS SOFTWAREProjects *SiriProxyAsUser SiriProxyInstall SiriProxyPlugins AddingyourownSiriCommands SiriProxyAsRoot UltrasonicDistanceMonitor TakingScreenshotsontheRaspberryPi SimpleSambaShare* SMBGET(testedandworking!) SAMBAServeronthePi. *SOFTWAREXBMC* BootingtoBlackScreen Windows7andAddingSources HowtoaddSources/Repos/Addons CustomXMLforbetterremoteusage(atleastonourbigtelly!!!) FixingTVScraperError SettingupaSharedLibrary FirstsetuptheSQLDB. Edittheadvancedsettings.xml RemoteControls. AccessingRegionLockedContent.:) GetiPlayer USEFULBITSOFPYTHON RunningAConsoleCommandViaPython PassingArgumentstoPythonprograms ChangingTerminalTextColours/EffectsViaPython QuickPythonPygameJoystickAxisDetection(TestedandRechecked.)

148

154

174

187

13

UsingPygametodetectJoystickPresses PiClub Session1BasicSetup(Network)andMinecraft(anEasyWin) Whatworked Session2USBRocketLaunchers Issues Session3Quake3andEmulation(DGEN?) Suggestions: WhatWorked.: Whatdidntwork: Session4BreakoutBoard(s),Wiringbits? Suggestions: WhatWorked: WhatDidntWork Session4.5Fail. Session5RobotArm. WhatWorked Whatdidntwork. Session6PiCamera. WhatWorked Whatdidntwork. Session6.5AShortPiClubduetomeetingsandothercommitments. WhatWorked Whatdidntwork Session7MinecraftHackingonthePiusingPythonScripts? Session8PiFM(PirateRadio!) Session9Twittering COSTOFSTUFF/PRICEGUIDE LinuxMiniGuide(forLaptop/PC) HowtoEnableSSHonLinuxMint15/14/13/12 VNConLinuxtoPi

192

196 198

14

FAQs

15

BackYourcardupoften!(everycoupleofweeks!)
Ivehadcardsdieafewtime,probablysomethingImdoing,couldbedodgyhardware.Buteventuallythe cardwilldie.Itsallgoodthoughasyoudidbackupright?Ifyouloselotsofstuffitsyourownfault. LuckilyformeIvegotahandyguidelikethisthatkeepsmeuptodateandhelpssoIdontforget anything!!!WICKED.IfImagoodsoldierIllbackupaftereveryPiClubsession(andkeepwhatson thecardincasethekidsmesstheirsuptoo!)Onewordofwarning,pleasetrytokeeptothesamebrand ofmemorycardasan8GBSandiskcardwillNOTbesamesizeasa8GBTranscendcard,itmightonly beafewMB,butitsenoughtoNOTallowyoutoinstallthebackupimageyoumade!

Whathappensif(when)youcorruptyourmemorycard!
GRRRR:CAUTIONifusingcrappy/cheapPSU/Cablesyouwillprobablyendupwithacorruptmemory card(duetorebootsetc!)Thiscancausemuchheartache,backupoften.Ispeakfromexperience.But Ivealwaysgotthisdocumenttofallbackon!!!Noteifitallgoeshorriblywrongandyoumessupyour card,youcanrescueitbyusingaLiveLinuxDistroe.g.Ubuntu(orMint)thiswillletyou(hopefully)grab andrescueallthestufffromthememorycard(justuseacardreader!)butasitalsohasGPartedonit, youcanformatyourmemorycardbacktosomethingWindozewillrecognise!

Constantkeyyyyyyyyyyyyyyyyyyyyyyyyyboardpresses
Ifyoustartgettingweirdkeyboardpressesitsduetothecombinationofhardware,namelythekeyboard andprobablytheHub.Ivehadthisseveraltimes,IgenerallyplugthekeyboardstraightintothePi, everythingelseintothehub!

CorruptMemorycard
Ifyouvegotaamemorycardthatkeepsbecomingcorruptitmightbeduetododgysectors, recommendationsisthatyougetanewcard.IhaveaSandiskSDHC8GBclass4.Wouldbefinefora fewinstalls,butthenwouldseemtocorrput.Youllknowwhenitbecomescorruptasitllstartscrolling errorsupthepageandlotsofredwarnings,youmayalsogeterrorsonbootsectorsandwillaskyouto runfsk! GoingtogiveaTrascend8GBClass10agoinstead!

ConstantReboots.
IhadthistodaywithastudentsPI....itjustkeptrebooting.Itfailedatsomepointwhilebooting,seemed tohavetoacheckofthefilesystemonthememorycard,,findanerrorandreboot(adinfinitum).Turned outthiswasadodgypowercable(betweenthePiandtheUSBfromtheComputerpoweringit!)Thanks forthisoneLloyd.

RebootswhenyouplugsomethingUSBin!
Manydevices,oftenWIFIdonglesetccancausethePitorebootwheninserted.Somedevicesarefine (ittendstobethelowerpowerones!)MostUSBPendrivesdontcausethesystemtoreboot(oftenyou mighthavetodothekeyboard/mouse/memorystickshuffleifyoudonthaveahubhandy!HoweverI 15

discoveredtodaythatVerbatimBlueUSBdidcausethePitoreboot!

FallingofftheNetworkRandomly
IhadthiswthaaPirunningpoweredbyaPC,turnsoutitwasthecablethatwassupplyingpower. SomecablesjustdoNOTwork.Tookmeawhile,IsuspectedthePi,ormemorycard,howeveritwas justthecable.ThePiwouldappearonthenetworkforawhile,mayberunafewcommands,thenwould justdropoff.Youdgetanoccasionalerroronboot.

AptgetupdateFails.
ifaptgetupdatefails,itcouldbeforafewreasons.Firstcheck/etc/apt/apt.confandcheckyourproxyis notstillset,secondcheck/etc/bash.bashrcandchecktheproxylines(usuallyaddedattheend). Howeverifitcanconnect,butfailswhenbuilding,orcomesupwithReadingpackagelists...Error! Itmightbesomethinghasbecomealittlecorrupt.Wellworthtryingthefollowing.Fixeditforme. Run
sudoaptgetclean

Itwilloftentellyouwheretheerroroccured,e.g.
E:Erroroccurredwhileprocessinglibwwwmechanizeperl(NewVersion2) orE:Erroroccurredwhileprocessinggnoemoe(NewVersion2)

SoafterabitofgooglingIranthis
sudorm/var/lib/apt/lists/mirrordirector.raspbian.org_raspbian_dists_wheezy_main_binaryarmhf_Packages

howeveryoumighthavetorun.
sudorm/var/lib/apt/lists/*vf sudoaptgetupdate

16

SSHontheschoolsystem???
MostmanagednetworksatschoolwillnotallowstudentstohaveaccesstoSSH,itwillbeconsidereda securityrisk.HoweverIknowthatitdoeswork(asIcanrunextrasoftwareonmyLaptop!)Howeverif youwantkidstohavethebenefitsofSSH(andtheyllbedoinglotsofcopyandpastingofcode!)whynot getthemusingaLiveUSBofLinux(Fullblownlinux,eitherUbuntuorMint!)Iverecentlybeendoingsome testingofLinuxdistros,mainlyduetoanoverzealousstudentwipinghisnetbookinafitofrage!The netbookanAcerAspireOne(225)orsimilarwouldhappilybootaLiveUSBoflinux,butwouldnotinstall thebootloadersowhenyoutriedaninstallyoujustgotleftwithablankscreenmaybewithaflashing cursor!HoweverwetestedlotsofversionoftheLiveUSB(Ubuntu)inthehopeoneofthemwouldwork. Verion9wentonokay,butdidntisntallthenetworkcarddriversusefulNOT.Howeverinallfairness, Mintwentonflawlessly,andworkedoutofthebox.Thestudentseemedmuchhappierusingthan windoze.SomuchsothatIvebeendabblingwithitalleveningandImtypingthisonmyschoollaptop (runningaLiveUSB(2GBtinystickburntwithWin32Imager))andamquitelikingit.Itsresponsiveand stable(wellFirefoxis,Chromium(whichItriedinstalling)notsomuch,butatleastunlikeWindows wouldntcrashoutcompletely,butwoulddiscreetlykillthepageinquestion!HoweverItriedanaptget updateandupgrade,thisnolongerfitonthe2GBstick(bewarned!) IhavemanagedtopilferacoupleofoldlaptopsthatIintendtohookuptotheschoolnetworkrunning LiveUSBversionsofMINT,andseehowtheygo.Intheorythey/etc/apt/apt.confand/etc/bash.bashrc editsshouldbeenoughtogetthemupandrunning!:)

17

TheHardware

18

AllthisdocumentisdesignedtoworkonaRaspberryPiModelB(preferablyversion2.0),butsomemay workwiththe256MBVersion.

ImguessingifyouvereadingthisyoueitherhaveaPi,aninterestinone,oratleastheldone!Please note,version1hasablackheadphonesocket,andnomountholes.Version2hasablueheadphone socketandmountholesinall4cornersofhteboard.(version1picturedablove) ThekeyspecsofRapsberryPi(a.k.aRasPi)are: Linuxbasedoperatingsystem 700MHzARM11CPU 256MB(or512MB)RAM SDCardStorage 2USBports CompositeandHDMIVideoout Stereoaudioout 8GPIOpins WiredEthernet

18

HowtocheckwhatRPi.GPIOversionyouhave
ThisworksforallversionsofRPi.GPIO
find/usr|grepigpio

Andtheoutputwilllooksomethinglikethis(althoughtherewillbemoreofit)

Youcanseeallthoselineswith0.5.3a.egginfotellingmeIhaveversion0.5.3a.

HowtocheckyourRaspberryPiRevisionnumber?
TheresawaytoseewhatyourPiRevisionis
cat/proc/cpuinfo

Youcanseethisgiveslotsofinfo.NearthebottomisRevision:000f ThistellsmeIhaveaRev2Pi,butitsabitclunky.Thereareseveraldifferentrev.codesfordifferentPi modelsandmanufacturers(heresalistofthem).Wecouldwritesomecodetocheckthecpuinfoand extractthebitwewant,compareitwithknownrevisioncodesetc.Butwedontneedanyofthatbecause, fromRPi.GPIO0.4.0aonwards(September2012)wecanuseabuiltinRPi.GPIOvariablewhichdoesit allforus.

19

DISTROs.

20

NOOBSSELECTER(RECOMMENDED)http://www.raspberrypi.org/downloads Raspbian(Wheezy)(RECOMMENDED)http://www.raspberrypi.org/downloads Raspbianhttp://www.raspbian.org/orhttp://www.raspbian.org/HexxehImages Loginpi Passwordraspberry ArchLinuxhttp://archlinuxarm.org/packages RASPBMChttp://www.raspbmc.com/ XBianhttp://xbian.org/download/

20

BackinguptheMemorycardusingthePI(working)
http://learn.adafruit.com/adafruitraspberrypilesson1preparingandsdcardforyourraspberrypi/make abackupimage Usewgettogetthefileoffpastebin.
wgethttp://pastebin.com/raw.php?i=48fr9BAS

Thenrenamethefilebackup.sh
mvraw.php?i=<tab>rpi_clone.sh

Ifyou'renotsurethatsdaistherightcard,youcanrunthiscommandtolistthecardsconnectedtoyour Pi.
sudofdiskl

TheSDcardslotwithyourrunningPisystemwillshowupas/dev/mmcblk0.Yourblankcardwillbe listedas/dev/sda1(orpossibly/dev/sdb1,ifyouhavemorethanoneUSBcardreadersattachedtothe Pi). Notethatyoudon'tenterthe'1'ifyourcardislistedas'/dev/sda1',thenyouwouldstillenter'sda'when yourunthescript('sda'isthenameofthecard,'sda1'isthenameofthefirstpartitiononthecard). Ok,sonowyoushouldbereadytorunthecommands


chmod+xrpiclone.sh sudo./rpi_clonesdaf

Asnotedearlier,thefirstparameterpassedtothescriptisisthenameofthetargetSDcard,inthiscase 'sda'.Theftellsthescripttoentirelyreformatthecard. Thescriptwillaskyouifyou'resureyouwanttoinitializethedestinationcard.Type'y',andhitthereturn key.

Ieditedthescipttomakeanmrorpibackup.sh(usingnano),ifyoueditoutthereadcommandscarefully youcanmakethescriptrunwithoutintervention.Thatalsomeansyoucanclonetomultiplecardsone afteranother. dofdiskl(Ifoundyouhadtohavethecardinthereaderfirst,thenconnecttohub!)fdiskshoudlshow yourdisks.E.g.sda1,thensdb1etc. Youcanthenrunusing


sudo./mrorpibackup.shsdbf&&sudo./mrorpibackup.shsdaf

21

SetupRaspbianMemorySplitandconfig.
raspiconfig

Iwouldrecommenda256/256splitandyoucancomfortablyoverclockto900MHz(Medium)setting.

UpdateandInstallupdatedpackages!
(Firsttimeyouruntheseitmighttakeawhile,maybeanhourorso!)
sudoaptgetupdate sudoaptgetupgradey sudoaptgetinstallygitdialog sudoaptgetdistupgrade

Orrunbothatonce.
sudoaptgetupdate&&sudoaptgetdistupgrade

RecommendedPackagestoInstall(Youllprobablyneedthemlater!)
sudoaptgetupdate
sudoaptgetinstallusbmountespeakmpg321ffmpegimagemagickfbisoxsambasambacommonbingitcore tightvncservergeanyespeakcupsxboxdrvwminputwmguijstestgtkbluetoothbluezutilsbluezcompat bluezhcidumplibusbdevlibbluetoothdevlibsdldevjoystickcheckinstallpyqt4devtoolspythonsetuptools pythoncwiidpythonpippythondevpythoncwiiddialogmotionflacy

sudoreboot

RPiupdateFirmware
AneasierwaytoupdatethefirmwareofyourRaspberryPi.(notworkingatschool,proxyissue?)

Preparations
Youneedgitinstalledtousethistoo.Toinstallrun:
sudoaptgetinstallgitcore

Installing
Toinstallthetool,runthefollowingcommand:
sudowgethttp://goo.gl/1BOfJO/usr/bin/rpiupdate&&sudochmod+x/usr/bin/rpiupdate

Updating
Then,toupdateyourfirmware,justrunthefollowingcommand:
sudorpiupdate

22

GitHubsWorthCloning
InstallthesoftwaretomanageGITHUBS
sudoaptgetinstallgitcore

ThenclonetheGITusing.(sometimesyouhavetoremovethesoffthehttpstogetaccesstothefiles!)
gitclone<git>

https://github.com/rpl/pythonwiimotehacks.gitWiiMoteHacks. https://github.com/brooksc/mcpipy.gitMinecraftPythonScripts. https://github.com/martinohanlon/minecraftrenderObj.gitMinecraftObj https://github.com/raspberrypi/quake3.gitQuake3. https://github.com/chep/snes9xrpiSnes9xrpi https://github.com/peterlavelle/maplinarmMaplinRobotArm. https://github.com/walac/pyusb.gitPythonUSBLibs(neededforRobotArmandRocketLauncher!) https://github.com/petrockblog/RetroPieSetupRetroPie(EmulationStation!) https://github.com/dozencrows/motionMotionforUsewiththePiCamera.

BackingupfilestoGDrive(Tested)
http://raspberrywebserver.com/serveradmin/backupyourpitoyourgoogledrive.html#.UjkKbFhmu1s.tw itter ThetroublewiththisisthatitsyncswithGDrive,i.e.notonlywillituploadtoGDrive,butitwill asloLEECHdownallyourGDrivedocs! HoweverthisscriptcouldbeusefulforZippingtheentirecontentofthehomedirectoryforuselater!!!

SaveasBackup.sh use cmodxBackup.sh tomakeitexecutable.

#!/bin/bash tarcrvfbackup_$(date+%y.%m.%d).tar/home/pi exclude="/home/pi/google_drive" gzipbackup_$(date+%y.%m.%d).tar mvbackup_$(date+%y.%m.%d).tar.gz./google_drive cd./google_drive ./grive cd..

23

PCSoftwaretogetfamiliarwith

24

Alltheseappshaveportableversions(soyoudonthavetoinstallanything,andcanrunfromamemory stick!)

SSHKitttySSHorPutty
ThiswillallowyoutoremotleyconnecttoyourPi,allyouhavetoknowistheipaddressofyourpi (ifconfig),thentryconnectingtoit.MEGAusefulandwillrunonjustaboutanysystem(thereareportable versionskickingabouttoo!).NoteifSSHingfromLinux(e.g.LiveCD),justgototheterminalandusessh pi:raspberry@<ipaddress>thecomputershouldthentryconnecting,youmighthavetoacceptakeyor similarandenteryourpassword

WIN32Imager
Youwillprobablyusethiseveryonceinawhiletoflashyourcardswhenyouscrewthemup,orfinda newOSyouwishtotryout!Deadeasytorun,justmakesureyouinstalltheIMGfiletothememorycard andnotaHDD,manyimagescomebundledwiththisinaZipFile!Idiscoveredrecentlythatthis programisalsoreallygoodatproducingLIVEUSBsofLinuxDistros,youdownloadaLinuxISO,youll havetobrowseforthefile(showallfiles)asitdoesntlistit,butthenyouanselecttheUSBanditwill produceaworkingcopy.TestedforbothUbuntu(variousversions)andLinuxMint!

7Zip
WellworthamentionasitletyouUnzip,Uncompact,UncompressjustaboutanythingincludingTARs.

AdvancedIPScanner
IfyouwanttoremotetoyourPiandyoudontknowtheIPaddressasitssetupwithDHCPandnot STATICIPaddress.

UltraVNC(Portable)
AtsomepointyoumightwanttorunyourPIheadlessandyetstillhaveaccesstoXandallthewonders oftheGUI(seeguidelaterforsettingupVNC),butthisappisprettygoodandfree.

Geany/NinjaIDE.(versionsavailableforbothWindozeandPI!)
IfyourecodinginPythonitsprobablyagoodplacetostart,aversatileIDE.
aptgetinstallninjaide aptgetinstallgeany

WinSCP
VerygoodforsimilarFTPforPI,greatforgettingfileson/offaPiQuickly!

24

Xming/XmingPortable(notgotthisworkingforme!:()
ForthisIusetheportableversion,whichallowsyoutonotinstall,runtheXming+putty.batfile.Starts Xming(fromthesystemtraystartanewPuttysession)ensureunderSSHthatX11isselected(notgot thistoworkyet!)

MobaXTermWorksaswellasVNC
Freeforpersonaluse.

First,you willneed to download and extract a copy of MobaXterm (as of 2/9/2013 the current version is 6.5). Onceyouhave extractedthefiles,doubleclickonMobaXterm_Personal_6.1 Click on the Sessions button at the top of the window.ChooseNew Session.ChooseSSHas thesessiontype.IntheHost field enter the IP address of your RasPi. Leave the port set to 22. Youcanalsoatthispointentertheusernamethatyouwill be using. Make sure that X11Forwarding is checked. Choose LXDEdesktopforthe remoteenvironmenttype.Clickon OKatthebottom. Once you click on OK you will see an X11 window open on your desktop. You may have to move it out of theway to enter credentials into the SSHwindow.Onceyouentercredentials and choosewhetheror notyou wanttosaveyourpasswordyou shouldthen(afteracoupleofmoments)seethedesktopofyourRasPi. NOTE:I amusing the Raspian wheezy OS on my Raspberry Pi. However, the instructionsabove willmostlikelyworkfora majorityofLinuxdistributionsaslongasXDMCPloginisenabled.

25

UsefulLinuxCommands
Command
chmod

26

Args R775

Usage. Sometimesfilesneedtheirpropertieschanging, readonlyandsuchlike.Tosortthatuse


sudochmodR775<filepath> +r=read,+w=write,+x=executable,R=recursive.

cd~ ls

~ ls/lsusb/-l

Takesyoutoyourhomedir. Lists,eitherfiles/folder/devices(lsusbgoodcheckingfor usbdevices)lwillprintoutthefileattributestoo,e.g.write, executableetc. Renameafile,mv<file1.ext><newname.ext> Copythefilefromonelocationtoanother. MakeaDirectorywithinyourcurrentdirectory. Delete/Removeafile(usetherfiftryingtodeleteafolder withcontentsoffiles!). Getyourcurrentnetworkinfo. Checkforbluetoothdevicesandwhatshappening. Bringsupsimpletexteditorforyoutomesswithconfig filesetc. BringsuptheVIeditor,analternativetoNanoandshows linenumbers. Youknowwhenyourunsomethinganditscrolls12pages oftextupthescreen,welltheLESScommandletsyou lookthroughitapageatatime!<pressanykeyto continue> choosesomesoftwaretoinstall. removesapackagefromyoursystem!ANDallits settings/configetc. Youknowyouvejustupdatedyourpackageslist,wellyou cansearchthecache!!!e.g.aptcachesearchchrom,not youmaywanttouse|less GivesyouthepreviouscommandstypedattheBASH! Youcanrunanyofthesecommandsusing !<commandno> e.g.!333wouldruncommand333fromthelist! dmesgprintsoutallthemessagesfromthekernelsince thePiwaslastpoweredON!,thiscanbealot.Usingthe 26

mv cp

<old><new> cp<current> <new> <foldername> <filename> ifconfig dev/scan <filename> <filename> <xzy>|less

mkdir rm

ifconfig hcitool nano

vi

less

aptgetinstall aptgetpurge

<package> <package> <keyword>

aptcache search

history

history

dmesg

dmesg|grep^ <searchterm>

greptoolyoucanchannelthistextthroughitandthen searchit!
grep >

grep^<term> <filename> <url>


wget help | less du

searchthroughwhateveryoutryingtopushthroughgrep. Usingthissimplesymbolyoucandumptheoutputfrom thebashstraightintoaspecifiedfileforlookingatlater! Greatifyoujustawnattograpafileorzipofftheinternet. Greatforgettinghelponcommands. Givesyoucurrentdiskusage,goodforfindingouthow muchspaceyouhaveleft(numbersinbytesIthink!) ShowsyouthesizeoffolderonthePI,goodforweeding outbigprograms/blockagesetc. Risusedtomeanrecursive,meaningnotjustappliedto thefile/folder,butallofitscontentstoo!!! Listsalltheprogramsrunningonyourpi.UsetheGrepto filterdownthelonglist!!! Letsyourunonecommand,waitforittofinishthenrunthe second,eg.aptgetupdate&&aptgetupgrado Willallowyoutorunacommandorprograminthe backgroundandstartsomethingelse!(runwiththe&) oncerunningpressenterandthecommandlinewillbe yoursagain.
S o m e t i m e s y o u w i l l b e r e q u i r e d t o a d d d r i v e r s m a n u a l l y t o L i n u x ( o f t e n f o r w o n k y h a r d w a r e ! ) t h e s e o f t e n c o m e i n t h e f o r m o f . k o f i l e s ( w h e n u n t a r d ) T h e w i l l o f t e n n e e d t o b e c o p i e d t o t h e r i g h t f o l d e r e . g .

wget help du

df

df | less

chmod -R xyz

ps

ps | grep <xyz>

&&

<c1> && <c2>

&

<c1> &

depmod

depmod -a

/lib/modules/3.6.11/kernel/drivers/... but then you need to update the OS to know youve put it there! That is what this command does, at least thats what I think it does! file cat file<xyz> cat[filename]| less.
i n f o r m s y o u w h a t f o r m a t y o u r f i l e i s . W i l l j u s t c h u r n o u t t h e c o n t e n t s o f a f i l e t o t h e p r o m p t f o r q u i c k v i e w i n g .

27

Anoteaboutthecommandprompt
Whenusingthecommandprompt,thecoloursofheadingsmeandifferentthings.

Alsobytypingfile<xyz>itwilltellyouwhatformatthefileis!

InstallingSoftware/Drivers
Manytimesinthisdocumentyouwillcomeacrossaptgetwhichisoneparticularwayofinstalling updatestosoftwareanddrivers...Howevertherearealternativemanagersoutthere. Aptitude(baseonaptget)willruninoroutsideofX. SynapticAsoftwarevisualinstallerdesignedtobeusedwithinX.

VI(Calledusingvi)aBasicTextEditorlikeNANO!
Edit a file, look at it, stop editing Edit a file from command prompt Edit a file from command prompt for reading only Edit a file from within vi Edit a new file from within vi, discard changes to current file Reload current file, discarding changes Go forwards a page Go backwards a page Move around single lines or characters Save changes Save changes and override protected (read-only) files Save changes and exit vi Quit Quit and discard changes vi <filename> vi -R <filename>

:e <filename> :e! <filename>

:e!

Ctrl+F (or PgDn) Ctrl+B (or PgUp) Arrow keys

:w :w!

ZZ :q :q!

28

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

:help :help set

UsingGREPProperly.
Grepisaverypowerfultool.Icanbeusedtofindthingswithafile,alotoffiles,orseveral directoriesoffiles.

Basicsyntax
grep<something><infile> e.g.
grep'string'*.txt

Usefulforfindingthewordstringinall.txtfilesinafolder,butcouldbemadebetter.

AdditionalArguments
color=auto=Makesiteasytoreadprettycolours! R:Recursive(lookatallthefoldersinsideyourfoldertoo!) i:ignorecase,sowillfindalloccurencesofstringSTRINGStringorvariants.

n:Prefixeachlineofoutputwiththe1basedlinenumberwithinitsinputfile. HPrintthefilenameforeachmatch.Thisisthedefaultwhenthereismorethanonefiletosearch.

so...using
grepcolor=autoiRnHstring*.txt

Willreturneverythinginallyourfolders(drilleddownfromcurrentlocation),tellyouthefileitcamefrom, thelinenumberandbeprettilycoloured!
Anicesimpleguidewithmoreexampleshere

29

SYSTEM

30

SettingaStaticIP(networkaddress)
#FindoutwhataddressyourrouterassignedtoyourRPi.
ifconfig

#EditthenetworksettingstouseaSTATICIPaddress. #NOTE:TomakeiteasyusethesamesettingsyourrouterassignedtoyourRPi.
sudonano/etc/network/interfaces

#CommentouttheDHCPentry.MaketheSTATICentrylooksomethinglikethis: #NOTE:TweaktheaddressforyourSTATICIPaddress.
autoeth0 ifaceeth0inetstatic address192.168.1.xxx netmask255.255.255.0 broadcast192.168.1.0 network192.168.1.255 gateway192.168.1.xxx

#ReboottheRPi reboot

HowtoChangeYourRaspberryPi(orOtherLinuxDevices)Hostname

ThedefaulthostnamefortheRaspberryPiis,creativelyenough,raspberrypi.Whatifyouwanta differenthostnameoryouwanttoavoidhostnameconflictsonyourlocalnetwork?Readonasweshow youhowtoquicklychangethehostnameofaLinuxbaseddevice.

WhyDoIWanttoDoThis?
Therearetwoprimaryreasonswhyyouwouldwanttotakeafewminutestoeditthelocalhostnameofa Linuxdeviceonyournetwork.Themostcommonreasonwouldsimplybecustomizationitsfunto personalizethings.RatherthanleaveyourRaspberryPimusicstationasplainoldraspberrypi,for example,youcouldrenameittojukebox. Theotherreasonyouwouldwanttocustomizethelocalhostistoavoidnameconflicts.Ifyou,for example,havepurchasedandsetupthreeRaspberryPiunits,allthreeofthem(assumingadefault Raspbianinstallation)willattempttoclaimthelocalhostnameraspberrypi.

30

Thefirstonewillsucceedandthenexttwowillfailtoresolvetheirhostnames,leavingthemblankinyour routersdevicelist(asseeninthescreenshotabove)andunreachableviahostnamebasedprotocolslike Sambafilesharing. Fortunatelyitssupersimple,assumingyouknowwheretoperformafewquickedits,tochangethe hostnameofyourRaspberryPi(andmostotherLinuxbaseddevicesyouhavefullaccessto).For demonstrationpurposeswellbeperformingthechangeonastockRaspbianinstallation,butthesame fileeditswillworkonDebian,Ubuntu,andmostotherLinuxplatforms.

ChangingtheHostonyourPi
WehavesomanyRaspberryPiunitsaroundtheofficethatabunchofthemarenowinconflict.Today weregoingtofixthatbyassigninguniquenamestoeachPiunitbasedontheircurrentfunction.Aperfect candidateforthisrenamingisourawesomeRaspberryPiweatherstationitwillbemucheasierto identifyitonthenetworkoncewechangethehostnametoweatherstation. ThefirststepistoeitheropenuptheterminalonthedeviceortoSSHintothedeviceandopenupa remoteterminal.Ourdeviceisheadlessandcurrentlyrunning,sowelltaketheremoteterminalroute andconnecttoitviaSSH. Attheterminal,typethefollowingcommandtoopenthehostsfile:
sudonano/etc/hosts

Yourhostsfilewilllooklikeso:

Leavealloftheentriesaloneexceptfortheverylastentrylabeled127.0.1.1withthehostname raspberrypi.Thisistheonlylineyouwanttoedit.Replaceraspberrypiwithwhateverhostnameyou desire.Wereplaceditonourdevicewithweatherstation.PressCTRL+Xtoclosetheeditoragreeto overwritetheexistingfileandsaveit. Backattheterminal,typethefollowingcommandtoopenthehostnamefile:


sudonano/etc/hostname

Thisfileonlycontainsyourcurrenthostname: 31

Replacethedefaultraspberrypiwiththesamehostnameyouputinthepreviousstep(e.g. weatherstation).Again,pressCTRL+Xtoclosetheeditor,agreetooverwritetheexistingfileandsaveit. Finally,weneedtocommitthechangestothesystemandrebootthesystemforthechangestotake effect.Attheterminal,enterthefollowingcommandtocommitthechanges:


sudo/etc/init.d/hostname.sh

Followthatcommandwith:
sudoreboot

Oncethesystemcomesbackonline,youcancheckthedevicelistinyourroutertoseeifthenew hostnamehasproperlyresolved:

Success!Nowinsteadofwanderingthenetworkwithoutaname,ourlittleRaspberryPiweatherstation hasahostnameallitsown.

SettingupWiFi
http://pingbin.com/2012/12/setupwifiraspberrypi/

Settingupadhocwifi
Toactuallybeabletousewifioutdoors,Ifolloweddebian'sdocumentationonsettingupanadhoc network: RASPBERRYPI
sudonano/etc/network/interfaces: autowlan0 ifacewlan0inetstatic address192.168.1.1 netmask255.255.255.0 gateway192.168.1.2 wirelesschannel1 wirelessessidMYNETWORK wirelessmodeadhoc

32

Onthelinuxlaptop:usegnomenetworkmanagertoconnecttoMYNETWORK,butsetamanualIP addressof192.168.1.2,withagatewayof192.168.1.1.TakenotethatadhocisNOTsupportedinallof linuxwifidrivers.(Ralink2500doesnotsupportit,neitherdomostRealtekchips)

SchoolSiteProxyInfo(toremember)
EditthisfiletosetPermanentlyAcrossAllProfiles.
sudonano/etc/apt/apt.conf

Addthefollowinglines:
Acquire::http::proxyhttp://10.173.0.28:9090/ Acquire::ftp::proxyhttp://10.173.0.28:9090/ Acquire::https::proxyhttp://10.173.0.28:9090/

(ifyoucopyandpaste,checkthegoacrossproperly!) saveinNanousingctrl+o,enter,thenquitctrl+x)

AllowprogramsotherthanBashaccesstoa(school)networkunderProxy.
InadditointoenableinthingslikeMidorietc(notjustthebashusethis),issuspectGitClonewillnotwork withoutthisadditiontoo! EditthefollowingfilewithNANO(N.B.Ithinkthisisneededtousedgitclonebehindaproxy!)
sudonano/etc/bash.bashrc

addtothebottom
exporthttp_proxy=http://10.173.0.28:9090/ exporthttps_proxy=http://10.173.0.28:9090/ exportftp_proxy=http://10.173.0.28:9090/

TemporarilyfromtheLXTerminal(notidealandonlyworksforROOT!)
exporthttp_proxy=http://10.173.0.28:9090 exportftp_proxy=http://10.173.0.28:9090 exporthttps_proxy=http://10.173.0.28:9090

UseifconfigtocheckonyourPiscurrentnetworkstatusandthentryasudoaptgetupdatetoseeifitcan connectandupdate!.

ChangingtheFontSizeoftheTerminalText
Runthiscommandandthenstepthroughthemenus.IcanrecommendTerminusFont 16x12makesitabiteasiertoread!(thankstoLloydforthisone!)

33

sudodpkgreconfigureconsolesetup

UTF8 GuessOptimalCharacterSet ChooseTerminus 16x32

ChoosingwhichprogramsrunwhenthePiboots
/etc/rc.localisascriptontheRaspberryPiwhichrunswhenLinuxfirstboots.Toeditit,youwillneedroot privileges:
sudonano/etc/rc.local

IfyouwanttorunoneofyourPythonscriptsatstartup,addthistotheendofrc.local:
python<yourscriptname>.py

Tostopascriptrunning,eitherdeletethelineitison,orcommentitout(adda#atthebeginningofthe line).

34

SettingupVNC
VNChttp://myraspberrypiexperience.blogspot.co.uk/p/settingupvnc.html
sudoaptgetinstalltightvncserver vncserver:1geometry1280x800depth16pixelformatrgb565

useAdvancedIPScannertofindtheIPaddress(althoughislistedbeforeyoulogin!) UseSSHtoruntheVNCcommand. UseUltraVLC(settoultramodewiththeIPfollowedby:1(thisistheconnectionnumberyousetup)

RunningVNCServeratStartup
http://learn.adafruit.com/adafruitraspberrypilesson7remotecontrolwithvnc/runningvncserveratstartup

Step1. OpenaTerminalsessiononthePi,orconnectusingSSH.AnewterminalorSSHsessionwill automaticallystartyouoffinyourhomedirectoryof/home/pi.Ifyouarenotinthisdirectory,changetoit bytyping:


cd/home/pi

Thencdtothe.configdirectorybytyping:
cd.config

Notethe'.'atthestartofthefoldername.Thismakesitahiddenfolderthatwillnotshowupwhenyou type'ls'. Step2. Issuethecommandbelowtocreateanewdirectoryinside.configcalled'autostart'.


mkdirautostart

cdintothatnewdirectorybytyping:
cdautostart

Step3. Allthatremainsistoeditanewconfigurationfile.Sotypethefollowingcommandtoopenthenanoeditor onthenewfile:


nanotightvnc.desktop

Editthecontentsofthefilewiththefollowingtext.
[DesktopEntry] Type=Application Name=TightVNC Exec=vncserver:1 StartupNotify=false

TypectrlXandthenYtosavethechangestothefile. Thatsallthereistoit.ThenexttimeyoureboottheVNCserverwillrestartautomatically.

35

SoundonthePi.
SoundonthePiisafunny,funnything.TheALSAsupportisntgreat,butitseemstowork*sometimes*

CheckAlsa&removePulse!
FirstensurethelatestAlsastuffisinstalled.
sudoaptgetinstallalsatoolsalsautilsmpg321 sudoaptgetpurgeremovepulseaudio

Testthesoundusing
sudoaplay/usr/share/sounds/alsa/Front_Center.wav

ForceHDMIsoundusing
sudoamixercsetnumid=3<n>

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

MakingthePiSpeak
ItispossibletomakethePispeaktoyou(thinkMSVoice)Simplyinstallespeak
sudoaptgetupdate sudoaptgetinstallespeak

thecallthecommandusing
espeakHelloWorld

Youcanfindmoreinfoaboutusingespeak,thevariousvoicesetchere. Thereareothermorecomplicatedprogramsyoucanusee.g.Festival(reasonswhyarelistedhere http://www.element14.com/community/blogs/mirandasoft/2013/04/13/raspberrypiprojectdedicatedspe echsynthesizerwithoutgui

SOXTheSwissKnifeofWAV/RawaudioonLinux
sudoaptgetinstallsox. Thisprogramwillallowyoutoconvert/trimchopetcWAVorRAWaudiofiles. IfoundthisusefulinthePiRateRadioprojectlistedlaterwhereIneededtoconvertaudioto22050and single(mono)channelforbroadcastingovertheFM!

36

sox<inputfile>r22050<outputfile>

oryoucouldimportsoundfromespeak(seeabove)thenPIPEthisintosox
sudoespeakstdoutStickanythinginhere|soxtwavr22050test.wavchannel1

Thesoxtoolneedstoknowwhatitisreceiving,hencethetwav,thenextinnoculousisactuallythe inputfromthePIPE,r22050resamplestheaudio. furtherinstuctionscanbefoundherehttp://billposer.org/Linguistics/Computation/SoxTutorial.html imporingsoundfromamic


soxtalsahw:1,0r22050testmic.wavsilence100.5%11.01%&

MPG321
ThishandytoolletsyouconvertMP3sintoWAVsforusewithprogramslikeSOX
sudoaptgetinstallmpg321 sudompg321w<outputfile><inputfile>

Idontknowwhytheargumentsseembackwards!

37

TurningyourRaspberryPiintoanFMTransmitter
http://www.daveconroy.com/howtoturnyourraspberrypiintoafmtransmitter/ Grabthecode
wgethttp://www.daveconroy.com/SampleCode/Pifm.tar.gz tarzxvfPifm.tar.gz
AttachtheAntennae Findan8inchpieceofplainwire,andattachittotheGPIO4 portonyourPi.Technicallytheisstepisoptional,butmy transmissionrangewentfrom200ftto8incheswithoutit. Usethepicturebelowasareference.

Atschoolthismadeadifferenceofedgeofmy roomtotheentirebuilding!!!!
Step3RuntheCode

Usage:sudo./pifmwavfile.wav[freq][samplerate] Thesecondcommandlineargumentisthe frequencytotransmiton,asanumberinMhz.For example,thiswilltransmiton100.1FM sudo./pifmsound.wav100.1 Youcanusewhateverfrequencyyou'dlike(88>108).

Ifyouremakingyourwoenaudiotobewpalyedbackoutoftheis,thenyouneedtouse22050sampling, andmakeitmono.Imnotsureifthatslimitationofthepifmprogram?ButaquickconvertusingSOX willdothejob!


sox<inputfile>r22050<outputfile>

Orifyouwanttoplaybackanmp3thenmpg321thenpipeintoSox.
sudompg321w<outputfile><inputfile>

sudompg321s<inputfile>|soxr22050<outputfile> sudo./pifm<outfputfile>101 WritingaScripttoMonitorMicInput

while[true] do #espeakstdout"test1234567890"|soxtwavr22050test3.wav&&./pif$ #espeakstdout"thisisjustanothertesttoseeifthislittleprogramw$ sudosoxtalsahw:1,0r22050testmic.wavsilence100.5%11.01%& ./pifmtestmic.wav101 #rmtestmic.wav

38

done

ABetterLiveMicSolution
http://www.raspberrypi.org/phpBB3/viewtopic.php?t=33526
a r e c o r d f S 1 6 _ L E r 2 2 0 5 0 D p l u g h w : 1 , 0 | s u d o . / p i f m 1 0 1 2 2 0 5 0

Alrightso:
a r e c o r d

Programweareusingtorecordaudio.
f S 1 6 _ L E

Output16bitdata.NeededthiswayforPiFMtoreadit.
r 2 2 0 5 0

Thisspecifiessamplingratetooutputrecording.22,050isagoodbalanceforspeedandquality.
D p l u g h w : 1 , 0

Thisiswhereyoumayneedtomodify.The'1'specifiescardnumberand'0'isthedevicenumberIthink.Tofindthis outforyourdevice,use

a r e c o r d l

toseealloftheaudiodevicesconnected.

Hereitmeanstoprintoutputtostandardout.
|

Pipethestandardoutfrompreviouscommandtonextcommand'sstandardinput.
s u d o . / p i f m 1 0 0 . 1 2 2 0 5 0

Thisisexplainedinthelinkatthetop.''meansusestandardinputfor"file"(Rememberwepipedit).'100.1'isthe frequencyinMhztotransmitand'22050'isthesamplingrateoftheinput.Actuallyifyouchangethesamplingrate loweritwilloutputalowpitchsoundandhigherwilldoahighpitchsound,kindofavoicechanger.

39

VoiceRecognitiononthePiusingGoogleVoiceAPI
http://blog.oscarliang.net/raspberrypivoicerecognitionworkslikesiri/

sudoaptgetinstallffmpeg

CreateascriptcalledSpeech2text.sh

#!/bin/bash echo"Recording...PressCtrl+CtoStop." arecordD"plughw:1,0"qfcdtwav|ffmpegloglevel panicyiar16000acodecflacfile.flac>/dev/null2>&1 echo"Processing..." wgetqU"Mozilla/5.0"postfilefile.flacheader "ContentType:audio/xflacrate=16000"O "http://www.google.com/speechapi/v1/recognize?lang=en us&client=chromium"|cutd\"f12>stt.txt echon"YouSaid:" catstt.txt rmfile.flac>/dev/null2>&1

Andtomakeitexecutable.
chmod+xspeech2text.sh

Torunit
./speech2text.sh

AskingWolframAlphaQuestions
wgethttps://pypi.python.org/packages/source/w/wolframalpha/wolframalpha1.0.2.zip unzipwolframalpha1.0.2.zip sudoaptgetinstallpythonsetuptoolseasy_installpip sudopythonsetup.pybuild sudopythonsetup.pyinstall

GettingtheAPP_ID

TogetauniqueWolframAlphaAppID,signuphereforaWolframAlphaApplicationID. YoushouldnowbesignedintotheWolframAlphaDeveloperPortaland,ontheMyAppstab,click theGetanAppIDbuttonandfillouttheGetaNewAppIDform.UseanyApplicationnameand descriptionyoulike.ClicktheGetAppIDbutton.

40

41

#!/usr/bin/python importwolframalpha importsys #GetafreeAPIkeyherehttp://products.wolframalpha.com/api/ #ThisisafakeID,goandgetyourown,instructionsonmyblog. app_id='6GG85YHGPWRKTG2L' client=wolframalpha.Client(app_id)

Saveasqueryprocess.py
Youmayhavetochmod775it.

query=''.join(sys.argv[1:]) res=client.query(query) iflen(res.pods)>0: texts="" pod=res.pods[1] ifpod.text: texts=pod.text else: texts="Ihavenoanswerforthat" #toskipasciicharacterincaseoferror texts=texts.encode('ascii','ignore') printtexts else: print"Sorry,Iamnotsure."

testthescriptusing
sudo./queryprocess.pyWhatisthecapitalcityofGermany

TextToSpeech Fromtheprocessedquery,wearereturnedwithananswerintextformat.Whatweneedtodonow isturningthetexttoaudiospeech.ThereareafewoptionsavailablelikeCepstralorFestival,butI choseGooglesspeechserviceduetoitsexcellentquality.Hereisagoodintroductionsofthese softwarementioned. Firstofall,toplayaudioweneedtoinstallmplayer:


sudoaptgetinstallmplayer

Wehavethissimplebashscript.ItdownloadstheMP3fileviatheURLandplaysit.Copyandcallit text2speech.sh #!/bin/bash say(){localIFS=+/usr/bin/mplayeraoalsa reallyquietnoconsolecontrols "http://translate.google.com/translate_tts?tl=en &q=$*"} say$*

42

Andtomakeitexecutable.
sudochmod+xtext2speech.sh

Totestit,youcantry
./text2speech.sh"MynameisOscarandIamtestingtheaudio."

Ifiterrorstry
sudonano/etc/mplayer/mplayer.conf

Andputinthelineattheend:
nolirc=yes

#!/bin/bash INPUT=$* STRINGNUM=0 ary=($INPUT) forkeyin"${!ary[@]}" do SHORTTMP[$STRINGNUM]="${SHORTTMP[$STRINGNUM]} ${ary[$key]}" LENGTH=$(echo${#SHORTTMP[$STRINGNUM]}) if[["$LENGTH"lt"100"]]then SHORT[$STRINGNUM]=${SHORTTMP[$STRINGNUM]} else STRINGNUM=$(($STRINGNUM+1)) SHORTTMP[$STRINGNUM]="${ary[$key]}" SHORT[$STRINGNUM]="${ary[$key]}" fi done forkeyin"${!SHORT[@]}" do say(){localIFS=+/usr/bin/mplayeraoalsareallyquiet noconsolecontrols "http://translate.google.com/translate_tts?tl=en&q=${SHORT[$key]}" } say$* done

Extendedscriptforlongerpiecesoftext. Saveoverthetopoftext2speech.sh

CombiningSpeechtoTextandTexttoSpeech.

#!/bin/bash echo"Recording...PressCtrl+CtoStop." ./speech2text.sh Savethescriptasmain.sh QUESTION=$(catstt.txt) echo"Me:",$QUESTION ANSWER=$(pythonqueryprocess.py$QUESTION) echo"Robot:",$ANSWER ./text2speech.sh$ANSWER

43

sudochmod775text2speech.sh ./main.sh

AlternativeGoogleVoiceSettings/Script
http://www.daveconroy.com/turnraspberrypitranslatorspeechrecognitionplayback60languages/

echo"RecordingyourSpeech(Ctrl+CtoTranscribe)" arecordDplughw:0,0qfcdtwavd0r16000|flacfbestsamplerate16000sodaveconroy.flac echo"ConvertingSpeechtoText..." wgetqU"Mozilla/5.0"postfiledaveconroy.flacheader"ContentType:audio/xflacrate=16000"O "http://www.google.com/speechapi/v1/recognize?lang=enus&client=chromium"|cutd\"f12>stt.txt echo"YouSaid:" value=`catstt.txt` echo"$value"

MicrosoftTranslationandGoogleTexttoSpeech
Nowthatwecanrecordourvoiceandconvertitintotext,weneedtotranslateittoourdesiredforeignlanguage.Iwouldlove tobeabletouseGooglesTranslatetoolforthis,butunfortunatelythereisa20$signupfeeforuseofthisAPI.Iplanon purchasingthisformyself,butIwantedtomakethisprojectfreesoeveryonehadanopportunitytotryit. Asanalternative,wewillbeusingMicrosoftstranslateservicewhichcurrentlyisstillfreeforpublicuse.Thelistofsupported languagesandtheircorrespondingcodescanbefoundhere.Inourpreviousexampleweusedasimpleshellscript,butfor thetranslationandplaybackprocessIvewrittenamorepowerfulpythonscript. Allofthiscodecanbefoundonmygithubrepository(contributionswelcome!). Letsfirstcreatethefile: sudonanoPiTranslate.py andaddthefollowingcontents

44

importjson importrequests importurllib importsubprocess importargparse parser=argparse.ArgumentParser(description='ThisisademoscriptbyDaveConroy.com.') parser.add_argument('o','origin_language',help='OriginLanguage',required=True) parser.add_argument('d','destination_language',help='DestinationLanguage',required=True) parser.add_argument('t','text_to_translate',help='TexttoTranslate',required=True) args=parser.parse_args() ##showvalues## print("Origin:%s"%args.origin_language) print("Destination:%s"%args.destination_language) print("Text:%s"%args.text_to_translate) text=args.text_to_translate origin_language=args.origin_language destination_language=args.destination_language defspeakOriginText(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) defspeakDestinationText(phrase): googleSpeechURL="http://translate.google.com/translate_tts?tl="+destination_language+"&q="+phrase printgoogleSpeechURL subprocess.call(["mplayer",googleSpeechURL],shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) args={ 'client_id':'',#yourclientidhere 'client_secret':'',#yourazuresecrethere 'scope':'http://api.microsofttranslator.com', 'grant_type':'client_credentials' } oauth_url='https://datamarket.accesscontrol.windows.net/v2/OAuth213' 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

Forthescripttorunweneedtoimportafewpythonlibrariesandamediaplayer. sudoaptgetinstallpythonpipmplayer sudopipinstallrequests

ThelastthingweneedtodobeforewecanrunthescriptissignupforaMicrosoftAzureMarketplaceAPIkey.Todoso, simplyvisitthemarketplace,registeranapplication,andthenenteryourclientidandsecretpasscodeintothescriptabove. Nowwecanrunthescript: sudopythonPiTranslate.pyoendest"hellomynameisdavidconroy"

Thescripthas3requiredinputs: oorignationlanguage ddestinationlanguage ttexttotranslate

PuttingitallTogether
Itisactuallyveryeasytocombinethetwoscriptswecreatedinthistutorial.Infact,itonlytakesonelineofcodetobeaddedto thebottomofstt.shshellscriptwecreatedearlier(assumingPiTranslate.pyandstt.shareinthesamedirectory). sudonanostt.sh

p y t h o n P i T r a n s l a t e . p y o e n d e s t " $ v a l u e "

Forthoseofyouwhoskippedaroundinthistutorial,hereistheentirescriptagainwiththatlineadded: echo"RecordingyourSpeech(Ctrl+CtoTranscribe)" arecordDplughw:0,0fcdtwavd0qr16000|flacsfbestsamplerate16000odaveconroy.flac echo"ConvertingSpeechtoText..." wgetqU"Mozilla/5.0"postfiledaveconroy.flacheader"ContentType:audio/xflacrate=16000"O "http://www.google.com/speechapi/v1/recognize?lang=enus&client=chromium"|cutd\"f12>stt.txt echo"YouSaid:" value=`catstt.txt` echo"$value" #translatefromEnglishtoSpanishandplayoverspeakers pythonPiTranslate.pyoendest"$value" Now,runtheSpeechToTextscriptagain,anditwilltranslateitfromEnglishtoSpanishbydefault. ./stt.sh

BoththeoriginanddestinationlanguageshavetobesupportedbyMicrosoftTranslateandGoogleTranslateinorderforthis scripttowork. LanguageCodes: Microsoft Google

46

MountingaUSBtheEasyWay!
InstallalittleappcalledUSBMount, sudoaptgetinstallusbmount TheUSBHDDorPendriveshouldthenappearas/media/usb[num]startingfromzero. Typedftofindtheexactpath.

...Orthehardway
http://elinux.org/RPi_Adding_USB_Drives

PrintingonaPi.
Guide FirstinstallCUPSLinuxPrintDrivers
sudoaptgetinstallcups

AddthePiusertothelpadmingroup(foradministratingprinters!)
sudousermodaGlpadminpi

Useaninternetbrowsertobrowseto
http://127.0.0.1:631

Youwillbepromptedforausernameandpasswordenteryournormalpiusernameandpassword SettingupanAirServer(forPrinting)SeeHere N.B.WhenIdidthistheprintmarginswerealltocock,mightbeworthcheckingthis.

MakingaProgramLOOPFOREVER
OntheRaspberryPimasterjustcreateasimplebashscript(youcouldsaveitas"forever")...

47

whiletrue do #Putanythingyoulikeinhere!!!! #avconvreimovie.avivcodeccopyanfaviudp://239.0.1.23:1234 done Don'tforgettoeithermakethescriptexecutableorrunitbyprependingthenameofthebashscriptwithsh,eg"sh forever".

Makingaprogramrepeateverysooften(CRONJobs!)
CRONisaverycoolwayofmakingaprocess,program,orscriptrunatsettimes.ThePicomessetup withnoCRONtaskrunning,howeveryoucaneditwhatyouwantittodoonaregularbasisusing
sudocrontabe

Itisveryimportanttoensurethesudocommandisused! Onceyouareinthefileyoucanthenaddthefollowingline,justchangethedirectorytopointtowhere yourfileissaved.(thisexampleissettorepeatevery60minutes,itthenrunsthecommandpython <pathofscript>)


*/60****python/home/pi/twitter/TweetTemp.py TheCronjobtakestheformof. 12345/root/backup.sh Where,

1:Minute(059) 2:Hours(023) 3:Day(031) 4:Month(012[12==December]) 5:Dayoftheweek(07[7or0==sunday]) /path/to/commandScriptorcommandnametoschedule

48

HARDWARE
Cases

45

SometimesyoullwanttoputyourPiinacase. Forschoolstrysomethinglikethe http://www.skpang.co.uk/catalog/coverwithbread boardareaforraspberrypilargep1101.html whichisclearandhasspace/included breadboardifyouregoingtodosomeelectronics.

orthePiBowisverypopularandmakesiteasyto gettoyourPi! http://shop.pimoroni.com/(theynowdoacouple ofaddonsifyouhavethecameramodule!)I preferTOXICtorainbow!

orifyouhaveplentyoflegothenbuildyourown, fullPDFinstructionshere! https://sites.google.com/a/mandell.org/raspberrypi /pimac Youdonthavetobetoocareful,usewhatyouve got,itjustgivesyouaroughidea!

49

FormediacentresIlikejustplainblack!

50

RaspberryPiGPIOLayoutRevision2
ByMatt |PublishedMarch10,2013|Fullsizeis1000471pixels

GPIOStuff
http://www.raspberrypi.org/archives/1417 http://log.liminastudio.com/writing/tutorials/tutorialhowtouseyourraspberrypilikeanarduino http://www.youtube.com/watch?feature=player_embedded&v=q_NvDTZIaS4#! http://jeremyblythe.blogspot.co.uk/2012/07/raspberrypigpioandmotion.html http://flask.pocoo.org/docs/quickstart/

51

ConnectingaPitotheoutsideworld
ForthisIrecommendusingaPiCobblerKitandabreadboard,bell(singlestrand)wire.Somegummie sweet!(testedwithJellyBabies!)

PINBasics
Firstthingisfirst,therearetonofwaystoconnectupaPitobreadboardsetc.Iwouldrecommendusing aCobblerKitorsimilar.WhenaddressingGPIOsinthelaterscriptsyouarenotaddressingthePIN number,butyoureusingthesepinouts.(GPIO.BOARD)thefirstdiagramorGPIO.

Moreherehttp://elinux.org/RPi_Lowlevel_peripherals

52

MakinganLEDFlash
TomakeasinglesimpleLEDFlash,youwirearesistorto+3.3v(pin1),thenconnecttheresistortothe LED(curvedside),thenconnecttheflatsidetowhicheverpinyouwanttouseGPIO7isaneasyone. Thisisthe7thPinastheygo1,2alongthetop,3,4then5,6then7.TheonlyWEIRDbitisthatyoure turningtheLEDONwhenyousetthispintoFALSE(0) Thispythonscriptshoulddoit.
fromtimeimportsleep importRPi.GPIOasGPIO GPIO.setmode(GPIO.BOARD) #Setyourpinsaseitherinputsoroutputs!(INorOUT) GPIO.setup(11,GPIO.OUT) while1: #TurntheLEDON! GPIO.output(11,False) sleep(1) #TurntheLEDOFF! GPIO.output(11,True) sleep(1)

NowtrycreatingathreecolouredLEDsetup.

53

LedBORGhttp://www.piborg.org/ledborg
Rev 2, 2013-09-10 or 3.6.11+ build #538
mkdir~/ledborgsetup cd~/ledborgsetup wgetOsetup.zip http://www.piborg.org/downloads/ledborg/raspbian20130910rev 2.zip unzipsetup.zip chmod+xinstall.sh ./install.sh

Usage
Colouroptions ThecoloursonanLedBorgaresetaslevelsofred,greenandbluereferredtoasRGB Theavailablelevelsare: 0>Meanschannelisoff 1>Meanschannelisat50% 2>Meanschannelisat100%

Forexample: RGBof200meansthatredisonfull,greenisoffandblueisoff,producingRED RGBof210meansthatredisonfull,greenisonhalfandblueisoff,producingORANGE RGBof202meansthatredisonfull,greenisoffandblueisonfull,producingMAGENTA RGBof021meansthatredisoff,greenisonfullandblueisonhalf,producingSPRINGGREEN RGBof222meansthatredisonfull,greenisonfullandblueisonfull,producingWHITE RGBof000meansthatredisoff,greenisoffandblueisoff,sinceallareoffthisturnsLedBorgoff(pseudoblack) Allcoloursagainstnumbers:


100 010 001 200 020 002 211 121 112 110 011 101 220 022 202 221 122 212 000 120 012 111 021 102 222 210 201

FortableswithnamesandHTMLcodesseehere

ControllingLedBorg
TosetthecolourfromtheGUI: FindtheGUIicononthedesktopwhereitwillbecalledLedBorgwithaPiBorglogo Alternativelyitcanbefoundbybrowsingto/home/piwhereitwillbecalledledborg_gui RuntheGUIbydoubleclickingonit IfadialogboxappearsaskingyouwhattodoselectExecute Clickonaboxtochangetothecolouritshows YoucanclickonDemoModetorunexamplesequences,includingturningLedBorgintoaCPUusagemeter!

54

TosetthecolourfromaPythonscript:
LedBorg=open('/dev/ledborg','w') LedBorg.write('RGB') delLedBorg replacingRGBwiththedesiredlevels(seeabove)

Tosetthecolourfromaterminaltype:
echo"RGB">/dev/ledborg replacingRGBwiththedesiredlevels(seeabove)

Tosetthecolourfromaterminalwiththebasicdrivertype:
~/ledborgbasicRGB replacingRGBwiththedesiredlevels(seeabove),notethat50%optionsarenotavailabletothebasicdriverand 100%willbeusedinstead(only8coloursincludingoff)

TodisableLedBorgfromaterminaltype:
sudo/etc/init.d/ledborg.shstop NotethatthiswillfreetheGPIOpinsforuse,butwillnotaffectiftheLedBorgdriverisstartedatboottime

ToenableLedBorgfromaterminaltype:
sudo/etc/init.d/ledborg.shstart NotethatthiswillstartusingtheGPIOpins,butwillnotaffectiftheLedBorgdriverisstartedatboottime

Managingbootoptions
Tosetthebootupcolourfromaterminaltype: echo"RGB">/home/pi/ledborg_bootcolour replacingRGBwiththedesiredlevels(seeabove) TostopLedBorgfromautoloadingfromaterminaltype: sudoupdaterc.dledborg.shremove NotethatthiswillstopLedBorgusingtheGPIOpinsduringboot,howevertheenableLedBorginstructionsabovewill beneedtobeusedbeforetryingtosetacolour ToenableLedBorgautoloadingfromaterminaltype: sudoupdaterc.dledborg.shdefaults100 NotethatthiswillstartusingtheGPIOpinsduringboot,loadingthecolourspecifiedby/home/pi/ledborg_bootcolour

55

Singing/ScreamingJellyBaby(ProbablyworkswithFruitPastelstoo!)
http://www.ocr.org.uk/Images/125881recipecardsingingjellybaby.pdf Onceconnected,stripapairofdecentlengthwiresandconnecttopins3and25.Striptheotherendof thewires(about2cm)andstickintotheJellyBabytomaketheswitch.Theguidesuggestsyou downloadmpg321andanMP3,thiswasblockedatschool,soIjustgotittowritewhatevermessage theylikedontheend.Ialsofoundthe1secondtimedelaywasFARtoolong.Settoatenthofthetime formoreaccuracy! wgethttps://github.com/RobBishop/RaspberryPiRecipes/raw/master/la.mp3 OriginalScript #Firstweneedtoimportthelibrariesthat #weneed #Importthetimelibrarysothatwecanmake #theprogrampauseforafixedamountoftime
importtime

RevisedScript
importtime importRPi.GPIOasGPIO importos GPIO.cleanup() GPIO.setmode(GPIO.BOARD)

#ImporttheRaspberryPiGPIOlibrariesthat #allowustoconnecttheRaspberryPito #otherphysicaldevicesviatheGeneral #PurposeInputOutput(GPIO)pins


importRPi.GPIOasGPIO

#Setpin3ontheGPIOheadertobeaninput
GPIO.setup(3,GPIO.IN) whileTrue: ifGPIO.input(3)==False: #os.system(mpg321la.mp3&) printOuch!Stopit! time.sleep(0.1)

#Importtheoslibrarysothatwecanmake #ourprogramcallotherprogramsthatrunon #theRaspberryPi


importos

#NowweneedtosetuptheGeneralPurpose #InputOuput(GPIO)pins #Clearthecurrentsetupsothatwecan #startfromscratch


GPIO.cleanup()

#SetuptheGPIOlibraryto #useRaspberryPiboardpin #numbers


GPIO.setmode(GPIO.BOARD)

#Setpin3ontheGPIOheadertobeaninput
GPIO.setup(3,GPIO.IN)

#Thislooprunsforeverandplaysthemp3 #filewhenthetwowiresaretouching
whileTrue:

#Checktoseeifpin3ontheGPIO #headerisconnectedtothegroundpin
ifGPIO.input(3)==False:

#Ifitsconnectedtoground #thenplaythemp3file
os.system(mpg321la.mp3&)

#Waitforasecondbeforerepeating #theloop
time.sleep(1)

56

Itsworthnotingthoughthatthecommand
os.system(<something>)

Allowsyoutorunanycommandorprogramyoucanfromtheterminal(welaunchedquake3)
os.system(./quake3/ioquake3.arm)

IfyoudowanttogettheMP3working,youmighthavetoforcethesoundthroughtheheadphonesocket. AlsoononePiIthoughttheGPIOPythonlibrarieswerentinstalled,howeverinhindsightIthinkthismay havebeenatypothatcausedit,notasitwasactuallymissing.Howeverjustincaseyoucanalwaysuse an


aptcachesearchGPIO

IbelievethepythonlibraryiscalledPythonGPIOorsimilar(usethesearch!).Justdoan
aptgetinstall

usingtheresultyoufound!.

Makesoundplaybackthroughtheheadphonesocket
Bydefaulttheoutputissettoautomaticallyselecttheinterface(HDMIifavailableotherwiseanalog).Youcanforceit touseaspecificinterfaceusing: sudoamixercsetnumid=3<n> Where<n>istherequiredinterface:0=auto,1=analog,2=hdmi.ToforcetheRaspberryPitousetheanalogoutput: sudoamixercsetnumid=31 YouwillneedtorunthemodprobecommandagainwhenyourPiisrebooted/restarted. PlayingAWAVFile InordertoplayaWAVfileweneedafiletoplay.TypethefollowingcommandtodownloadatestWAVfile: sudowgethttp://www.freespecialeffects.co.uk/soundfx/sirens/police_s.wav Nowwecanplayit: sudoaplaypolice_s.wav sudoalsamixer #CheckAudioVolume.

57

PiCameraModule
Initialinstallationandsetup. http://www.youtube.com/watch?feature=player_embedded&v=GImeVqHQzsE http://www.linuxuser.co.uk/tutorials/picameraquickinstallationguide

HowtousetheRaspberryPicamerasoftware
raspividisacommandlineapplicationthatallowsyoutocapturevideowiththecameramodule,whiletheapplication raspistillallowsyoutocaptureimages. ooroutputspecifiestheoutputfilenameandtortimeoutspecifiestheamountoftimethatthepreviewwillbe displayedinmilliseconds.Notethatthissetto5sbydefaultandthatraspistillwillcapturethefinalframeofthe previewperiod. dordemorunsthedemomodethatwillcyclethroughthevariousimageeffectsthatareavailable.

Examplecommands
Captureanimageinjpegformat: raspistilloimage.jpg

Toquicklyviewtheimagefromthecommandpromptinstallfbiandusethesimplecommand
sudoaptgetinstallfbi fbiimage.jpg

Thiswilldisplaytheimageonthescreenandyouwillbeabletousethe+andkeystozoominandout.
Capturea5svideoinh264format: raspividovideo.h264 Capturea10svideo: raspividovideo.h264t10000 Capturea10svideoindemomode: raspividovideo.h264t10000d Toseealistofpossibleoptionsforrunningraspividorraspistill,youcanrun: raspivid|less raspistill|less Usethearrowkeystoscrollandtypeqtoexit.

ToshootvideowiththeRaspberryPiCamera
Fromthecommandline,type
raspividofilename.h264t20000

wherefilenameisafilenameofyourchoice. Thiswillstoretheoutput.h264streaminafilecalledfilename.h264andwillstoprecordingafter20000 milliseconds(20s).(Itdefaultsto1080p@30framespersecond). 58

Thereareacoupleofotherusefullittleoptionsyoumightwanttoknowabout.Bydefault,theimageis flippedvertically,meaningyouseeamirrorimageofwhatyoufilmed. Dependingonwhichwayroundyouholdthecamera,youmightwanttoflipiteitherhorizontally,vertically orboth.Youcandothatbyaddingvfand/orhftothecommand,likethis


raspividofilename.h264t20000vfhfor raspividofilename.h264t20000vfor raspividofilename.h264t20000hf

59

BerrycamPhotos(Tested)
http://www.fotosyn.com/berrycamsupport/?app Saveallthis as Berrycam.py thenrun using
sudopython berrycam.py& #!/usr/bin/envpython # #BerryCam.py #BerryCamRaspberryPiCameraControllerforusewithiOSdevices # #CreatedbyJamesMooreon22/05/2013. #Copyright(c)2013Fotosyn.Allrightsreserved. # #RaspberryPiisatrademarkoftheRaspberryPiFoundation. #IOSisatrademarkorregisteredtrademarkofCiscointheU.S.andothercountriesandisusedbyAppleInc. underlicense. importSimpleHTTPServer,SocketServer importurlparse importos PORT=8000#CHangethisifyouwishtolistenonadifferentport classBerryCamHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): defdo_GET(self): #Parsequerydata parsedParams=urlparse.urlparse(self.path) queryParsed=urlparse.parse_qs(parsedParams.query) #Add'berrycam'prefixtoURLtoperformquery ifparsedParams.path=="/berrycam": awb="'"+queryParsed['awb'][0]+"'"#SetAWBmode mm="'"+queryParsed['mm'][0]+"'"#Setmeteringmode ev=queryParsed['ev'][0]#SetEVcompensation ex="'"+queryParsed['ex'][0]+"'"#Setexposuremode sh=queryParsed['sh'][0]#Setimagesharpness br=queryParsed['br'][0]#Setimagebrightness co=queryParsed['co'][0]#Setimagecontrast sa=queryParsed['sa'][0]#Setimagesaturation #iso=queryParsed['iso'][0]#SetcaptureISONOTYETIMPLEMENTED ifx="'"+queryParsed['ifx'][0]+"'"#Setimageeffect #cfx="'"+queryParsed['cfx'][0]+"'"#SetcoloureffectNOTYETIMPLEMENTEDINBERRYCAM #rot=queryParsed['rot'][0]#SetimagerotationNOTYETIMPLEMENTEDINBERRYCAM 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)#Takethevaluespassed,divideby4andmultiplytogetnewsize #fileheight=1944#((1944/4)*filesize)#Takethevaluespassed,divideby4andmultiplytogetnewsize #Exposuremodeoptions: #off,auto,night,nightpreview,backlight,spotlight,sports,snow,beach,verylong,fixedfps,antishake,fireworks #AWBmodeoptions: #off,auto,sun,cloud,shade,tungsten,fluorescent,incandescent,flash,horizon #ImageEffectmodeoptions: #none,negative,solarise,sketch,denoise,emboss,oilpaint,hatch,gpen,pastel,watercolour,film,blur,saturation,coloursw ap,washedout,posterise,colourpoint,colourbalance,cartoon #MeteringModeoptions: #average,spot,backlit,matrix directory='berrycam/'+str(filefolder) ifnotos.path.exists(directory): os.makedirs(directory)

soitrunsin the background.

60

#Builduparaspistillcommandlinestring command="raspistillv"#InitiatecommandforRaspicam command+="awb"+str(awb)#DefineWB command+="mm"+str(mm)#DefineMeteringMode command+="ev"+str(ev)#DefinetheExposureAdjustment command+="ex"+str(ex)#DefineExposureMode command+="sh"+str(sh)#DefineImageSharpness command+="br"+str(br)#DefineImageBrightness command+="co"+str(co)#DefineImageContrast command+="sa"+str(sa)#DefineImageSaturation #command+="ISO"+str(iso)#DefineImageISONOTYETIMPLEMENTED command+="ifx"+str(ifx)#DefineImageEffect #command+="cfx"+str(cfx)#DefineColourEffectNOTYETIMPLEMENTEDINBERRYCAM #command+="rot"+str(rot)#DefineImageRotationNOTYETIMPLEMENTEDINBERRYCAM command+="q"+str(filequality)#DefineImageQuality command+="w"+str(filewidth)#Defineoutputimagewidth command+="h"+str(fileheight)#Defineoutputimageheight #command+="o/berrycam/"+str(filefolder)+"/IMG"+str(fileseq)+".jpg" command+="oberrycam/"+str(filefolder)+"/IMG"+str(fileseq)+".jpg" #command+="xIFD1.Make="+str(exifmake)#DefineMakeforESIFData'RaspberryPi' ifhflip=="1": command+="hf" else: command+="" os.system(command) self.processRequest(queryParsed) else: #Defaulttoserveupalocalfile SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) defprocessRequest(self,query): self.send_response(200)

httpd=SocketServer.TCPServer(("",PORT),BerryCamHandler) print"BERRYCAMListeningonport",PORT print"PleaseensureyourBerryCamAppisinstalledandrunningonyouriOSDevice" httpd.serve_forever()

61

TimeLapsePhotos
Anothergreatfeatureoftheutilityistheeasycaptureofaseriesofimagesoveraspecified periodoftime.Youcouldwriteyourownsoftwaretodothisbutforspeedyoucantbeatthe timelapseoptionsprovided: raspistillomyimage_%d.jpgtl2000t25000 Thetloptionsetsthetimebetweenphotos(inmilliseconds)andthetoptionsetsthetotaltime thesequencewilllast.Sointhisexampleaphotowillbetakeneverytwoseconds(2000ms)fora totaltimeoftwentyfiveseconds(25000ms). Inthisexamplewetakeaphotoeveryminute(60000milliseconds)foratotaltimeof2hours(2x 60x60x1000milliseconds): raspistillomyimage_%d.jpgtl60000t7200000 The%dresultsinasequenceofnumberedimagesbeingproduced.Inthiscaseyouwouldget imagesnamed: myimage_1.jpg myimage_2.jpg myimage_3.jpg myimage_4.jpg ... Ifyouchangethe%dto%04dyoucanpadthenumberswithzeroestoalwaysgivefour digits.Imuchpreferthisasitgivesyouasequencethatlookslike: myimage_0001.jpg myimage_0002.jpg myimage_0003.jpg myimage_0004.jpg ...

TimeLapseVideofromStills.
http://www.raspberrypispy.co.uk/2013/05/creatingtimelapsevideoswiththeraspberrypicamera/
Step1Takingthetimelapsedphotos Thiscommandwilltakeaphotoevery60seconds(60000milliseconds)for2hours(7200000milliseconds)resultingin asequenceof120images. raspistillomyimage_%04d.jpgtl60000t7200000 The%04dwillresultinafourdigitnumberappearingineachfilename. myimage_0001.jpg myimage_0002.jpg ... myimage_0119.jpg myimage_0120.jpg

62

Step2CombineimagesintoMP4video Onceyouvegotyourimagesequenceyouwillneedamethodtostitchthemtogether.Idecidedtouseavconv.You caninstallthisusefullibrarywiththefollowingcommand: sudoaptgetyinstalllibavtools Toconstructthevideofilefromyourimagesequenceyouusethecommandshownbelow.Althoughitappearson multiplelinesforreadabilityitshouldbeenteredasasinglelineonthecommandline: avconvr10imyimage_%04d.jpgr10vcodeclibx264crf20g15timelapse.mp4 Thevideowillbethefullresolutionofthedefaultimagesize(25921944). Tocroptheimagesandcreateamorestandard1280720resolutionvideoyoucanusethefollowingcommand: avconvr10itimelapse_%04d.jpgr10vcodeclibx264crf20g15vf crop=2592:1458,scale=1280:720timelapse.mp4 Thevfoptiondefinesavideofilter.Inthiscasetwofilterswhichcroptheincomingimageto25921458andthen scalethemto1280720. Theroptiontellsavconvtocreateavideowithaframespersecondof10.Itappearstwicetopreventavconvdropping framesthatitthinksaresimilar. Thecrfoptiontellsavconvtoaimforaqualitylevelof20whichisagoodstartingpoint.Lowersvaluesarebetterbut willincreasethefilesize. ThegoptionsetstheGOPvalue.TheYouTubeAdvancedEncodingSettingspagerecommendsthattheGOP shouldbesettohalftheframeratesothisissetto15. TheconversionprocessisveryslowonthePicomparedtodoingthesamethingonadesktopPC.Forlong sequenceswithhundredsofframesIwouldrecommenddownloadinganappropriateversionofLibavonyourdesktop orlaptopandbuildyourMP4filesmuchfaster!

63

ConvertingtheVideooutput
http://raspi.tv/2013/howtoshootvideoandconvertittosomethingyoucaneditinpinnacleandotherpr ograms
ffmpegr30ivideo_in.h264vcodeccopyvideo_out.mp4

ExtraTricksbyBillTidey
BillpostedthesetipsinthePiforumsandtheyweretoogoodnottoshare ffmpegflavfiiaevalsrc=0r30itest.h264shortestc:vcopyc:aaacstrictexperimentaltesto.mp4 addsasilentaudiochannelassomevideoeditorsdontworkwithoutthis. ffmpegitest.mp3r30itest.h264shortestc:vcopyc:aaacstrictexperimentaltesto.mp4 addsarealaudiotrackwherethetest.mp3shouldnormallybelongerthanthevideoastheoutputis theshortest.

64

WatermarkingwithanotherGraphic!
Firstlyinstallawonderfulgempieceofsoftwarecalled imagemagick,ifitworksintheGIMPorPhotoshopyou canprobablydosomethingsimilarwithimagemagick fromthecommandline.ThisisaVERYcomplex beasty!WithmorearugmentsthanIdcaretoguess. ButIthoughthell,letsdivein.
sudoaptgetinstallimagemagick

FullmanualforImageMagickhere.

IcreatedanicelittleMROPilogoincooltext(andsavedit!),didnttrythisonthePi,butusedWinSCPto getitonthePi. IalreadyhadsomestockimagesonthePi(inafolder!),Iputthelogointheretoo! FirstIfoundIhadtoresizethelogoasthecapturedimagesfromthePicameraare2592x1944pixels Iusedthecommand


convertCT_Pi_Logo.png1000%CTI_Pi_Big.png

Whichconvertedtheimage(IcouldgofromJPGtoPNGifIwanted!),butalsoincreasedthesizetenfold (1000%)Ifoundthisabitmassiveandwentfor(500%intheend!)Theadaptiveresizegavememuch betterquality!


convertCT_Pi_Logo.pngadaptiveresize500%CTI_Pi_Big.png

Ithentriedvariouscommandstomovethelogoround.(noticethelogoiscalledfirst,toputontopofthe otherimage,ifyoudoittheotherwayrounditcropsdownthelargeimagetosmall!Iusedthecomposite commandtoputthemtogether.Ifoundyoucouldusegravitysouthtodefinehowlowonthepage(I assumeNorthisatthetop!) compositeCTI_Pi_Big.pngmyimage_11.jpggravitysouthtest.png Amuchbetterwayofdoingthiswastouseexactpixelcoordinates(starting0,0inthetopleft!) SofinallyIused compositegeometry+100+1700CTI_Pi_Big.pngmyimage_11.jpgtest.png toputtheimageinthebottomleftcorner!

UsingthePiCameramodulewithMotion
SeemyguideforsettingupmotionforthePS3camerforfurtherdetails.Howevertousetheraspberrypi 65

camerayouneedamodifiedversionofMotion(motionmmal)andacustomconfigfile.Itriedcompilingit fromsourcebutcouldnotgetitwork(configure/make/makeinstall).Notonlywoulditnotworkitrefused todetectthespecialconfigfilerequired.SoIused


sudoaptgetpurgemotion

Tocleanitfromthesystem,thenusedthebinaryavailablehere(Dropboxblockedatschool)butyoucan downloadthetarball. IcopiedthefilestothePi(intheirownfolder)andhadsomesuccessusing


sudo./motionncmotionmmal.conf

wherethenmeansyouSHOULDbeabletostopthecamerafromthecommandpromptratherthan runningitasaserviceandcletsyouchoosethecustomconfigfile.Ihadsomesuccesswiththis, howeveritdidseemtocrashthePionseveraloccasions(thekeyboardstoppedworking!)Willdofurther tests,itwasalsounresponsiveacrossmylocalnetwork(whereIwishtoviewthecameraresultsviathe browser!) Thekeycommandinthe.conffiletoaccessthePicamerais mmalcam_namevc.ril.camera ....not /dev/video0

66

CreepyFaceTracking(PartlyTested)
http://learn.adafruit.com/downloads/pdf/creepyfacetrackingportrait.pdf http://learn.adafruit.com/creepyfacetrackingportrait/software https://www.youtube.com/watch?v=3rhnfBSjj6w

BinaryInstallation Executethefollowingcommandstogetthe binaries:


mkdir~/creepyportrait cd~/creepyportrait wget https://github.com/tdicola/creepyportrait/ra w/master/creepyportrait_1.0_raspberrypi.tar .gz tarxvfcreepyportrait_1.0_raspberrypi.tar.gz sudo./install_dependencies.sh Answeryestothequestionsaboutupdatingandinstallingpackagesthatcomeupwhen theinstall_dependencies.shscriptisrun.ThisscriptisprovidedinopenFrameworksandwillinstallallthe necessarylibrariesforrunningopenFrameworksapplicationslikethecreepyportrait.

Usage
ToruntheprogramfirstmakesureeithertheRaspberryPicameraorawebcamisattachedtoyour RaspberryPi. Note:Ifyou'reusingtheRaspberryPicameraforthefirsttime,makesuretofollowtheseinstructionsto enableitwiththeraspiconfigcommand. Firstruntheprogramwithnocommandlineparametersbyexecuting: ./creepyportrait Youshouldseetheprogramusageandanerrormessageaboutnovideodevicebeingselected.Ifyou're usingawebcam,notethedeviceIDnumberofthewebcamyouwanttouse. ToruntheprogramwiththeRaspberryPicameraexecute: ./creepyportraitpi Ortoruntheprogramwithawebcamexecute: ./creepyportrait(videodeviceID) Where(videodeviceID)istheIDofthewebcamfromabove.Forexampleifyou'reusingdeviceID0you wouldexecute'./creepyportrait0'(withoutquotes). Itshouldtakeabout3060secondsfortheprogramtostartanddisplaytheskull.Youshouldalsoseevideo fromyourcameraintheupperleftcorner,andevery~2secondsagreenboxappearoverthelargest detectedfaceinthevideo.Makesureyouhaveadecentamountoflightonyourfaceorelsethedetection won'tbeveryreliable.

67

YoucanpressthefollowingbuttonsontheRaspberryPi'skeyboardtocontroltheapplication: VHideorshowthevideointheupperleftcorner. MIfyou'rerunningwithmorethanone3Dmodel(seefurtherbelow),changebetween renderingdifferentmodels.OntheRaspberryPi,fornowonlyonemodelcanbeloadedin memoryatatime. EscapeorCtrlCClosetheapplication.

Youcanruntheprogramwithadifferent3Dmodelbyspecifyingitinasecondcommandlineparameter. Thepossiblevaluesare: skull jackevil jackhappy all

Skullisthedefaultmodel.UnfortunatelyevenontheRaspberryPimodelBthereisn'tenoughmemoryto loadallmodelsatonce,sopickyourfavoriteoneanduseitwhenyourunonthePi. ForexampletorunwiththeeviljackolanternusingtheRaspberryPicamerayouwouldexecute: ./creepyportraitpijackevil ContinueonifyouwanttodownloadandcompileopenFrameworksandthecodeforthecreepyportrait.If youjustwanttorunthecreepyportraityoucanstophere,you'redone!

FixingRaspVid/RaspImageforHeadlessstreaming http://www.darkoperator.com/blog/2013/5/23/fixinraspistillandraspividforheadlessstreamingonthe.ht ml

68

CheapPIRSensorsandtheRaspberryPiPart1(untested)

http://www.raspberrypispy.co.uk/2013/01/cheappirsensorsandtheraspberrypipart1/

AgreatlittlesensoryoucanaddtoyourRaspberryPiprojectsisaPIRmodule.These5VPassiveInfra RedsensorsareavailableforafewpoundsfromeBay.Theycanbepoweredfrom5Vandoutput3Vso canbeconnecteddirectlytopinsonthePisGPIOheaderwithoutanyothercomponents. Themodulesetsasingleoutputpinhighwheneveritdetectsmovementwithinitsfieldofview.Itholds thispinHigh(3.3V)foraminimumperiodoftime.Ifcontinuousmovementisdetectedtheoutputpinwill stayHigh.WhenthetimehaselapsedandnomoremovementisdetectedtheoutputpinreturnsLow (0V). Iamcurrentlyusingoneinanalarmsystemanditworksgreatforsuchasmallandcheapdevice. PIRConnections HereisadiagramshowingthepinoutonthePIRmoduleandhowIconnectedittomyRaspberryPi:

PIRModule

Thedevicehastwovariableresistorsthatyoucanadjusttotweaktheperformanceofthemodule.

TrimmingControls

69

Thefirstone(lefthandsideonthephoto) determinesthesensitivityofthedevice.The defaultsettingisusually50%. Thesecondcontrol(righthandsideonthephoto andusuallymarkedtimeonthePCB)allowsyou toadjusttheamountoftimetheoutputpinstays at3V(high)whenitistriggeredbymovement. Thiscanbesetfromafewsecondsto200 seconds.Thedefaultsettingisusuallyafew seconds. TheunitsavailableoneBayvaryinspecification buttheyareallverysimilar. PythonExampleScript Ifyouconnectyourmoduleasshowninthe diagramabovethefollowingPythonscriptwill allowyoutogetstarted.Cutandpastethescript belowintoatextfileandtransfertothePior downloadthescriptdirectlyusingthislink.

#!/usr/bin/python #++++++++++++++++++++++ #|R|a|s|p|b|e|r|r|y|P|i||S|p|y|.|c|o|.|u|k| #++++++++++++++++++++++ # #pir_1.py #DetectmovementusingaPIRmodule # #Author:MattHawkins #Date:21/01/2013 #ImportrequiredPythonlibraries importRPi.GPIOasGPIO importtime #UseBCMGPIOreferences #insteadofphysicalpinnumbers GPIO.setmode(GPIO.BCM) #DefineGPIOtouseonPi GPIO_PIR=7 print"PIRModuleTest(CTRLCtoexit)" #Setpinasinput GPIO.setup(GPIO_PIR,GPIO.IN) Current_State=0 Previous_State=0 try: print"WaitingforPIRtosettle..." #LoopuntilPIRoutputis0 whileGPIO.input(GPIO_PIR)==1: Current_State=0 print"Ready" #LoopuntilusersquitswithCTRLC whileTrue: #ReadPIRstate Current_State=GPIO.input(GPIO_PIR) ifCurrent_State==1andPrevious_State==0: #PIRistriggered print"Motiondetected!" #Recordpreviousstate Previous_State=1 elifCurrent_State==0andPrevious_State==1: #PIRhasreturnedtoreadystate print"Ready" Previous_State=0 #Waitfor10milliseconds time.sleep(0.01) exceptKeyboardInterrupt: print"Quit" #ResetGPIOsettings GPIO.cleanup()

#Echo

70

This script can also be downloaded onto your Pi directly using this command line : 1
wgethttp://www.raspberrypispy.co.uk/archive/python/pir_1.py

This can then be run using : 1


sudopythonpir_1.py

WhenrunthescriptwaitsfortheoutputpintogoLow.Itthenprintsamessagetothescreeneverytime theoutputstatechanges.Thisiseitherwhenmovementisdetected(outputchangestoHigh)orthe deviceseesnomovement(outoutchangestoLow). Trychangingtheresettimebyturningthetimeresistorclockwisebyafewdegrees.Runthescript again,triggerthedeviceandthenwaittoseehowlongittakestogobacktothereadystate. Photos HeresomemoredetailedphotosofthePIRpinsandtwotrimmingcontrols:

71

RobotArmStuff.
(see)MagPiEditon3Page14

http://cymplecy.wordpress.com/2012/08/26/scratchcontrollingthegpioonaraspberrypi/ https://github.com/peterlavelle/maplinarm http://notbrainsurgery.livejournal.com/38622.htmlAlternativeapproachbysendingbitsofdata. http://www.mybigideas.co.uk/RPi/RobotArm/RobotArmwithPS3Pad. http://www.instructables.com/id/RaspberryPiandWiimotecontrolledRobotArm/#step1Robotarm withWiiMote https://sites.google.com/site/pydatalog/python/pipforwindowsPIPManagerforWindows?

72

RobotArmBasics
http://www.wikihow.com/UseaUSBRoboticArmwithaRaspberryPi(Maplin)
#ROBOTARMCONTROLPROGRAM #importtheUSBandTimelibrarysintoPython importusb.core,usb.util,time #Allocatethename'RoboArm'totheUSBdevice RoboArm=usb.core.find(idVendor=0x1267,idProduct=0x000) #Checkifthearmisdetectedandwarnifnot ifRoboArmisNone: raiseValueError("Armnotfound") #Createavariableforduration Duration=1 #Defineaproceduretoexecuteeachmovement defMoveArm(Duration,ArmCmd): #Startthemovement RoboArm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,3) #Stopthemovementafterwaitingaspecifiedduration time.sleep(Duration) ArmCmd=[0,0,0] RoboArm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,3) #Doaquicktestofallthejoints. MoveArm(1,[0,2,0])#Rotatebaseclockwise MoveArm(1,[64,0,0])#Shoulderup MoveArm(1,[128,0,0])#Shoulderdown MoveArm(1,[16,0,0])#Elbowup MoveArm(1,[32,0,0])#Elbowdown MoveArm(1,[4,0,0])#Wristup MoveArm(1,[8,0,0])#Wristdown MoveArm(1,[2,0,0])#Gripopen MoveArm(1,[1,0,0])#Gripclose MoveArm(1,[0,0,1])#Lighton MoveArm(1,[0,0,0])#Lightoff

Savethefollowing codeinarm.pythen runusingsudopython arm.py

73

RobotArmwithPS3Pad
#!/usr/bin/envpython importpygame importusb.core importtime pygame.init() #Waitforajoystick whilepygame.joystick.get_count()==0: print'waitingforjoystickcount=%i'%pygame.joystick.get_count() time.sleep(10) pygame.joystick.quit() pygame.joystick.init() j=pygame.joystick.Joystick(0) j.init() print'InitializedJoystick:%s'%j.get_name() armFound=False whilenotarmFound: dev=usb.core.find(idVendor=0x1267,idProduct=0x0000) ifdevisNone: print'Armnotfound.Waiting' time.sleep(10) else: armFound=True #thisarmshouldjusthaveoneconfiguration... dev.set_configuration() #HowfartomovetheJoyStickbeforeithasaneffect(0.60=60%) threshold=0.60 #Keymappings PS3_BUTTON_SELECT=0 PS3_AXIS_LEFT_HORIZONTAL=0 PS3_AXIS_LEFT_VERTICAL=1 PS3_AXIS_RIGHT_HORIZONTAL=2 PS3_AXIS_RIGHT_VERTICAL=3 PS3_AXIS_X=17 PS3_AXIS_CIRCLE=18 PS3_AXIS_R1=15 PS3_AXIS_R2=13 #RobotArmdefaults command=(0,0,0) lc=0 shoulder=0 base=0 elbow=0 wristup=0 wristdown=0 grip_open=0 grip_close=0 grip_command=0 wrist_command=0 shoulder_command=0 base_command=0 elbow_command=0 #ARMcontrolrelatedstuff defsetcommand(axis_val): ifaxis_val>threshold: return1 elifaxis_val<threshold:

IusetodriveaUSBRobot ARMfrommyRaspberry PiusingaPlayStation3 controller.IgottheARM fromMaplinsintheUK (Code:A37JN)anditsa OWIEDGE535Robotic kit. Mostofthetoolsrequired tocontroltheRobotARM fromaRaspberryPi comepreinstalledonthe latestimages,however youwillneedtoinstall PyUSBtosend commandstotheARM.
sudoaptgetinstall pythonlibusb0.14 gitclone https://github.com/walac/pyu sb.git cdpyusb sudopython setup.pyinstall

WiththePyUSBmodule installedandaPS3 controllerattacheditsjust asimplecaseofrunning thefollowingscriptto controlitsmovements. Theanaloguesticks controltheARM movement,withthe R1/R2buttonsmovingthe wristandtheXandCircle keysoperatingthegripper. ThisassumesthePS3 Padiswired.

74

return2 elifabs(axis_val)<threshold: return0 defbuildcommand(shoulc,basec,elbowc,wristc,gripc,lightc): byte1=shoulc+elbowc+wristc+gripc comm_bytes=(byte1,basec,lightc) returncomm_bytes defprocessArm(event): globalcommand,lc,shoulder,base,elbow,wristup,wristdown,grip_open,grip_close, grip_command,wrist_command,shoulder_command,base_command,elbow_command ifevent.type==pygame.JOYBUTTONDOWN: ifevent.button==PS3_BUTTON_SELECT: iflc==0: lc=1 else: lc=0 elifevent.type==pygame.JOYAXISMOTION: ifevent.axis==PS3_AXIS_LEFT_VERTICAL: shoulder=event.value elifevent.axis==PS3_AXIS_LEFT_HORIZONTAL: base=event.value elifevent.axis==PS3_AXIS_RIGHT_VERTICAL: elbow=event.value elifevent.axis==PS3_AXIS_R1: wristup=event.value elifevent.axis==PS3_AXIS_R2: wristdown=event.value elifevent.axis==PS3_AXIS_X: grip_open=event.value elifevent.axis==PS3_AXIS_CIRCLE: grip_close=event.value #Areweopeningorclosingthegripper? ifgrip_open>threshold: grip_command=1 elifgrip_close>threshold: grip_command=2 else: grip_command=0 #Andthesameforthewrist,arewemovingupordown? ifwristup>threshold: wrist_command=1*4 elifwristdown>threshold: wrist_command=2*4 else: wrist_command=0 shoulder_command=setcommand(shoulder)*64 base_command=setcommand(base) elbow_command=setcommand(elbow)*16 #Workoutwhattosendouttotherobot newcommand=buildcommand(shoulder_command,base_command, elbow_command,wrist_command,grip_command,lc) #Ifthecommandhaschanged,sendoutthenewone ifnewcommand!=command: dev.ctrl_transfer(0x40,6,0x100,0,newcommand,1000) command=newcommand

try: #Loopforwever whileTrue: #Sleepsowedon'teatupalltheCPUtime time.sleep(0.1) #readinevents events=pygame.event.get() #andprocessthem

75

foreventinevents: processArm(event) exceptKeyboardInterrupt: j.quit()

76

RobotArmWithWiiMote
sudoaptgetinstalllibusbdev sudoaptgetinstallpythonpip sudopipinstallpyusb sudoaptgetinstallbluezpythoncwii

#++++++++++++++++++++++++++ #|T|A|Y|L|O|R||B|O|A|R|D|M|A|N||||R|P|I||A|R|M| #++++++++++++++++++++++++++ '''Firstweneedtoimportsomefiles(Thesefilescontainallthecommandsneededforourprogram) Wehaveusb.coreandusb.utiltheseareusedtocontroltheusbportforourarm Nextwehavecwiidwhichcommunicateswiththewiimote Andwehavethetimelibarywhichallowsustosloworpausethings''' importusb.core,usb.util,cwiid,time #Giveourrobotarmaneasynamesothatweonlyneedtospecifyallthejunkrequiredfortheusbconnectiononce print'Makesurethearmisreadytogo.' print'' Armc=1750 Arm=None while(Arm==None): #Thisconnectstotheusb Arm=usb.core.find(idVendor=0x1267,idProduct=0x0000) #Thiswillwaitforasecond,andtheniftheprogramcouldnotconnect,ittellsusandtriesagain Armc=Armc+1 if(Armc==2000): print'CouldnotconnecttoArm,doublecheckitsconnections.' print'Programwillcontinuewhenconnectionisestablished...' print'' Armc=Armc/2000 continue #SetupourarmtransferprotocolthroughtheusbanddefineaValuewecanchangetocontrolthearm Duration=1 ArmLight=0 #Createdelayvariablethatwecanuse(Seconds) Delay=.1 Counter=9999 defArmMove(Duration,ArmCmd): #StartMovement Arm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,1000) time.sleep(Duration) #StopMovement ArmCmd=[0,0,ArmLight] Arm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,1000) #Establishaconnectionwiththewiimote print'Connectedtoarmsuccessfully.' print'' print'Press1and2onthewiimoteatthesametime.' #Connecttomoteandifitdoesn'tconnectthenittellsusandtriesagain time.sleep(3) print'' print'EstablishingConnection...5' time.sleep(1)

77

print'EstablishingConnection...4' time.sleep(1) print'EstablishingConnection...3' Wii=None while(Wii==None): try: Wii=cwiid.Wiimote() exceptRuntimeError: print'Errorconnectingtothewiimote,press1and2.' print'EstablishingConnection...2' time.sleep(1) print'EstablishingConnection...1' time.sleep(1) print'' #Onceaconnectionhasbeenestablishedwiththetwodevicestherestoftheprogramwillcontinueotherwise,itwillkeepontryingto connecttothetwodevices #RumbletoindicateconnectionandturnontheLED Wii.rumble=1#1=on,0=off print'ConnectionEstablished.' print'Pressanybuttontocontinue...' print'' '''Eachnumberturnsondifferentledsonthewiimote ex)ifWii.led=1,thenLED1ison 2=LED2 3=LED3 4=LED4 5=LED1,3 6=LED2,3 7=LED1,2,3 8=LED4 9=LED1,4 10=LED2,4 11=LED1,2,4 12=LED3,4 13=LED1,3,4 14=LED2,3,4 15=LED1,2,3,4 Itcountsupinbinaryto15''' time.sleep(1) Wii.rumble=0 Wii.led=15 #Setitsothatwecantellwhenandwhatbuttonsarepushed,andmakeitsothattheaccelerometerinputcanberead Wii.rpt_mode=cwiid.RPT_BTN|cwiid.RPT_ACC|cwiid.RPT_EXT Wii.state whileTrue: #Thisdealswiththeaccelerometer '''createavariablecontainingthexaccelerometervalue (changesifmoteisturnedorflickedleftorright) flatorupsidedown=120,ifturned:90degreescc=95,90degreesc=145''' Accx=(Wii.state['acc'][cwiid.X]) '''createavariablecontainingtheyaccelerometervalue (changeswhenmoteispointedorflickedupordown) flat=120,IRpointingup=95,IRpointingdown=145''' Accy=(Wii.state['acc'][cwiid.Y]) '''createavariablecontainingthezaccelerometervalue (Changeswiththemotesrotation,orwhenpulledbackorflickedup/down) flat=145,90degreesccorc,or90degreesupanddown=120,upsidedown=95''' Accz=(Wii.state['acc'][cwiid.Z])

#Thisdealswiththebuttons,wetelleverybuttonwhatwewantittodo buttons=Wii.state['buttons'] #Getbatterylife(asapercentof100):

78

#Justdeletethenunbersigninnfront #printWii.state['battery']*100/cwiid.BATTERY_MAX #Ifthehomebuttonispressedthenrumbleandquit,pluscloseprogram if(buttons&cwiid.BTN_HOME): print'' print'ClosingConnection...' ArmLight=0 ArmMove(.1,[0,0,0]) Wii.rumble=1 time.sleep(.5) Wii.rumble=0 Wii.led=0 exit(Wii) '''ArmCommandsDefinedbyArmMoveare [0,1,0]RotateBaseClockwise [0,2,0]RotateBaseCClockwise [64,0,0]ShoulderUp [128,0,0]ShoulderDown [16,0,0]ElbowUp [32,0,0]ElbowDown [4,0,0]WristUp [8,0,0]WristDown [2,0,0]GripOpen [1,0,0]GripClose [0,0,1]LightOn [0,0,0]LightOff ex)ArmMove(Durationinseconds,[0,0,0]) ThisexamplewouldstopallmovementandturnofftheLED''' #Checktoseeifotherbuttonsarepressed if(buttons&cwiid.BTN_A): print'Apressed' time.sleep(Delay) ArmMove(.1,[1,0,ArmLight]) if(buttons&cwiid.BTN_B): print'Bpressed' time.sleep(Delay) ArmMove(.1,[2,0,ArmLight]) if(buttons&cwiid.BTN_1): print'1pressed' ArmMove(.1,[16,0,ArmLight]) if(buttons&cwiid.BTN_2): print'2pressed' ArmMove(.1,[32,0,ArmLight]) if(buttons&cwiid.BTN_MINUS): print'Minuspressed' ArmMove(.1,[8,0,ArmLight]) if(buttons&cwiid.BTN_PLUS): print'Pluspressed' ArmMove(.1,[4,0,ArmLight]) if(buttons&cwiid.BTN_UP): print'Uppressed' ArmMove(.1,[64,0,ArmLight]) if(buttons&cwiid.BTN_DOWN): print'Downpressed' ArmMove(.1,[128,0,ArmLight]) if(buttons&cwiid.BTN_LEFT): print'Leftpressed' ArmMove(.1,[0,2,ArmLight])

79

if(buttons&cwiid.BTN_RIGHT): print'Rightpressed' ArmMove(.1,[0,1,ArmLight]) #Herewehandlethenunchuk,alongwiththejoystickandthebuttons while(1): ifWii.state.has_key('nunchuk'): try: #Hereisthedataforthenunchukstick: #Xaxis:LeftMax=25,Middle=125,RightMax=225 NunchukStickX=(Wii.state['nunchuk']['stick'][cwiid.X]) #Yaxis:DownMax=30,Middle=125,UpMax=225 NunchukStickY=(Wii.state['nunchuk']['stick'][cwiid.Y]) #The'NunchukStickX'andthe'NunchukStickY'variablesnowstorethestickvalues #Herewetakecareofallofourdatafortheaccelerometer #Thenunchukhasanaccelerometerthatrecordsinasimilarmannertothewiimote,butthenumberrangeisdifferent #TheXrangeis:70iftilted90degreestotheleftand175iftilted90degreestotheright NAccx=Wii.state['nunchuk']['acc'][cwiid.X] #TheYrangeis:70iftilted90degreesdown(thebuttonspointingdown),and175iftilted90degreesup(buttonspointingup) NAccy=Wii.state['nunchuk']['acc'][cwiid.Y] #Istilldon'tunderstandthezaxiscompletely(onthewiimoteandnunchuk),butasfarasIcantellit'smainchangecomes fromdirectlypullingupthemotewithouttiltingit NAccz=Wii.state['nunchuk']['acc'][cwiid.Z] #Makeitsothatwecancontrolthearmwiththejoystick if(NunchukStickX<60): ArmMove(.1,[0,2,ArmLight]) print'MovingLeft' if(NunchukStickX>190): ArmMove(.1,[0,1,ArmLight]) print'MovingRight' if(NunchukStickY<60): ArmMove(.1,[128,0,ArmLight]) print'MovingDown' if(NunchukStickY>190): ArmMove(.1,[64,0,ArmLight]) print'MovingUp' #MakeitsothatwecancontrolthearmwithtiltFunctions #LefttoRight if(Accx<100andNAccx<90): ArmMove(.1,[0,2,ArmLight]) print'MovingLeft' if(Accx>135andNAccx>150): ArmMove(.1,[0,1,ArmLight]) print'MovingRight' #UpandDown if(Accy<100andNAccy<90): ArmMove(.1,[64,0,0]) print'MovingUp' if(Accy>135andNAccy>150): ArmMove(.1,[128,0,0]) print'MovingDown' #Herewecreateavariabletostorethenunchuckbuttondata #0=nobuttonspressed #1=Zispressed #2=Cispressed #3=BothCandZarepressed

80

ChukBtn=Wii.state['nunchuk']['buttons'] if(ChukBtn==1): print'Zpressed' ArmLight=0 ArmMove(.1,[0,0,ArmLight]) if(ChukBtn==2): print'Nonunchukdetected.' else: if(ArmLight==0): if(Accz>179orAccz<50):print'Cpressed' ArmLight=1 ArmMove(.1,[0,0,ArmLight]) #Ifbotharepressedtheledblinks if(ChukBtn==3): print'CandZpressed' 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]) #Anyotheractionsthatrequiretheuseofthenunchukinanywaymustbeputherefortheerrorhandlingtofunctionproperly break #Thispartdownbelowisthepartthattellsusifnonunchukisconnectedtothewiimote exceptKeyError: ArmLight=1 ArmMove(.1,[0,0,ArmLight]) time.sleep(.5) elif(ArmLight==1): if(Accz>179orAccz<50): ArmLight=0 ArmMove(.1,[0,0,ArmLight]) time.sleep(.5) if(Counter==10000): print'Nonunchukdetected.' Counter=Counter/10000 break Counter=Counter+1 break

RobotArmGUI(inPython)WIP
Hmpf,stillworkingthisout. Youneedtheimageoftherobotarm,600x600 (thecontrolsusethecoordinatesforpositioning
fromtkinterimport* fromtkinterimportttk importtime #importusb.core,usb.util,

81

buttons!) Stillnotsurewhatlambdadoes!!!!

#Codegotfromherehttp://pythondictionary.codeit.co.uk/tkinter #&here http://www.tutorialspoint.com/python/python_gui_programming.htm #Setupourarmtransferprotocolthroughtheusbanddefinea Valuewecanchangetocontrolthearm Duration=1 #Createdelayvariablethatwecanuse(Seconds) Delay=.1 Counter=9999 #INSERTCODETOTESTFORARMHERE(untested) #Thisroutineby http://www.instructables.com/member/Boardmaster/ defArmMove(Duration,ArmCmd): #ArmCommandsDefinedbyArmMoveare ifArmCmd==[0,1,0]: status='RotateBaseClockwise' elifArmCmd==[0,2,0]: status='RotateBaseCClockwise' elifArmCmd==[64,0,0]: status='ShoulderUp' elifArmCmd==[128,0,0]: status='ShoulderDown' elifArmCmd==[16,0,0]: status='ElbowUp' elifArmCmd==[32,0,0]: status='ElbowDown' elifArmCmd==[4,0,0]: status='WristUp' elifArmCmd==[8,0,0]: status='WristDown' elifArmCmd==[2,0,0]: status='GripOpen' elifArmCmd==[1,0,0]: status='GripClose' elifArmCmd==[0,0,1]: status='LightOn' else: status='ALLOFF' print(str(ArmCmd)+''+status) text.insert("@1,1",str(ArmCmd)+''+status+'\n') #StartMovement #Arm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,1000) time.sleep(Duration) #StopMovement ArmCmd=[0,0,0] #Arm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,1000) #DefineaninstanceofTKforthewindow. root=Tk() #Givethewindowatitle. root.title("MRORobotArmController") #SetuptheCanvas,thisisbasedontheRobotArmimage,600x600 can1=Canvas(root,width=600,height=600) can1.pack()#Placesthecanvas #Definewheretheimageisfortherobotarm. filename=PhotoImage(file="robot.gif") #PuttheimageontheCanvase,thefirst2argsarecoords... #theanchorsayswhichpartoftheimagethesearerelativeto,NW (topleft!) image=can1.create_image(0,0,anchor=NW,image=filename) #Definebasebuttons but_baseleft=Button(root,text="BASE\nLEFT", 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

but_baseright=Button(root,text="BASE\nRIGHT", command=lambda:ArmMove(0.1,[0,1,0])) but_baseright.pack() but_baseright.place(bordermode=OUTSIDE,height=50,width=50, x=500,y=450) #Defineshoulderbuttons but_shoulderup=Button(root,text="SHOULDER\nUP",font='Ariel 6',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\nDOWN", font='Ariel6',command=lambda:ArmMove(0.1,[128,0,0])) but_shoulderdown.pack() but_shoulderdown.place(bordermode=OUTSIDE,height=50, width=50,x=150,y=300) #Defineelbowbuttons but_elbowup=Button(root,text="ELBOW\nLEFT",font='Ariel 8',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\nRIGHT",font='Ariel 8',command=lambda:ArmMove(0.1,[32,0,0])) but_elbowdown.pack() but_elbowdown.place(bordermode=OUTSIDE,height=50, width=50,x=525,y=180) #Definewristbuttons but_wristup=Button(root,text="WRIST\nUP",font='Ariel 8',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\nDOWN",font='Ariel 8',command=lambda:ArmMove(0.1,[8,0,0])) but_wristdown.pack() but_wristdown.place(bordermode=OUTSIDE,height=50,width=50, x=300,y=70) #Definegrip but_gripopen=Button(root,text="GRIP\nOPEN",font='Ariel 8',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\nCLOSE",font='Ariel 8',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) #ThisalwaysneedstobeattheEND! root.mainloop()

83

7SegmentDisplayProject(Oneofmyfirst!)
Using4543BCD(BinaryCodedDecimal)Chips(x2for10sandUnitsDisplay)Feedthesamedatato bothchipsDA,DB,DC,DD,differentLatches(LDandLD2onotherchip!).

84

ForthischosecommonCatchode.

85

Chipsfordrivingmotors
http://www.hobbytronics.co.uk/motorcontrol/hbridgedriversn754410
http://www.fanjita.org/serendipity/archives/61RaspberryRoverpart2TheHardware.html#extended

LCDSetup
UsingstandardLCDdisplaystogetoutputfromthePi(CheapDisplaysOrderedfromEbay/China)

http://www.raspberrypispy.co.uk/2012/07/16x2lcdmodulecontrolusingpython/ http://www.raspberrypispy.co.uk/2012/08/16x2lcdmodulecontrolwithbacklightswitch/

86

Cheap3.5LCDDisplay.

http://www.raspberrypispy.co.uk/2012/11/cheapminiaturelcdscreen/ http://www.raspberrypi.org/phpBB3/viewtopic.php?f=64&t=17651

Worksatreat,usedafunky littlePSUIboughtfrom Wilkinsons(foraround5I thinkthatswitchesDC Voltagesupto12volts. Bargain.

UsedthestandardsetuptochangetheFONTtosomethingmorereadable.
sudodpkgreconfigureconsolesetup

MakingitrunoffaUSB???http://www.raspberrypi.org/phpBB3/viewtopic.php?f=64&t=17651

87

HARDWAREControllers
sudoaptgetinstalljstestgtk

84

GraphicsTesting/VisualJoystickTest
ThiswillthenappearinXunderoneofthemenus.Worksquitewellforvisualtesting.

WiimoteBasics
Gettingthedrivers/setup
EnsureBluetoothisinstalled
sudoaptgetinstallbluetooth

Run'bluetoothstatus'from
servicebluetoothstatus

Shouldsay'started' InstallCWiiD&WMInput
sudoaptgetinstallpythoncwiidwminputwmgui

Runthehcitool
sudohcitooldev

Thisshouldshowadevice(hcisummat...ifitdoesn'ttrypluggingbluetoothintoPInothub!orareboot!) Runascan
sudohcitoolscan

ThisshouldlistyourwiimoteasNintendoRVL Usethisscripttotest getthescriptwgethttp://www.raspberrypispy.co.uk/archive/python/wii_remote_1.py Runthescriptpythonwii_remote_1.py

88

RunningWiiMoteasaMouse.
FirstyouneedtoeditafilesothatitdetectstheGyrosetc.
sudonano/etc/cwiid/wminput/ir_ptr

FindFindtheselines:
Plugin.ir_ptr.X=~ABS_X Plugin.ir_ptr.Y=~ABS_Y andreplacethemwith: Plugin.ir_ptr.X=ABS_X Plugin.ir_ptr.Y=ABS_Y

(ensureyoursensorbarispluggedin!) Finallyrunthis(thedmeansitrunsasadaemon,daemonsgood,demonsbad!)
wminputdc<configfilenamefrom/etc/cwiid/wminput>

orthisonefornooutput.
nohupwminputd

WiiMoteButtonMappings
NotetheRIGHTbuttonshouldbe512!!!

ABetterDiagram

89

WIIMoteInfo
https://help.ubuntu.com/community/CWiiD http://www.raspberrypi.org/phpBB3/viewtopic.php?f=9&t=1233 UsingtheWiimotehttp://talk.maemo.org/showthread.php?t=60178 http://www.brianhensley.net/2012/08/wiicontrollerraspberrypipython.html http://linux.die.net/man/1/wminput http://abstrakraft.org/cwiid/wiki/ConfigScriptEtcScriptstoinstall.(needtoknowtheMACaddressofWII Mote) http://www.raspberrypispy.co.uk/2013/02/nintendowiiremotepythonandtheraspberrypi/

90

CreatingCustomWiiMoteConfigs
cd/etc/cwiid/wminput/

Edit/Copy/Messwiththescripts(sudonanodefault)default
sudonanofps_configallowsfornunchuck,justsaveyourconfigassomethingdifferent.

Daemonsallowyoutorunstuffonstart. YoucanedittheBluetoothDaemon(runsonstart)
sudonano/etc/init.d/bluetooth

(doctrl+Wandsearchforwminput,addc<config>forittorunaspecificconfig. https://github.com/rpl/pythonwiimotehacks

UsingWiiMotesinPythonProjects
Forafewstepbystepguides http://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/robot/getting_started/ thisscriptisagreatplacetostart.
wgethttp://www.raspberrypispy.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 #ConnectaNintendoWiiRemoteviaBluetooth #andreadthebuttonstatesinPython. # #ProjectURL: #http://www.raspberrypispy.co.uk/?p=1101 # #Author:MattHawkins #Date:30/01/2013 # #ImportrequiredPythonlibraries # importcwiid importtime button_delay=0.1 print'Press1+2onyourWiiRemotenow...' time.sleep(1) #ConnecttotheWiiRemote.Ifittimesout

91

#thenquit. try: wii=cwiid.Wiimote() exceptRuntimeError: print"Erroropeningwiimoteconnection" quit() print'WiiRemoteconnected...\n' print'Presssomebuttons!\n' print'PressPLUSandMINUStogethertodisconnectandquit.\n' wii.rpt_mode=cwiid.RPT_BTN whileTrue: buttons=wii.state['buttons'] #IfPlusandMinusbuttonspressed #togetherthenrumbleandquit. if(buttonscwiid.BTN_PLUScwiid.BTN_MINUS==0): print'\nClosingconnection...' wii.rumble=1 time.sleep(1) wii.rumble=0 exit(wii) #Checkifotherbuttonsarepressedby #doingabitwiseANDofthebuttonsnumber #andthepredefinedconstantforthatbutton. if(buttons&cwiid.BTN_LEFT): print'Leftpressed' time.sleep(button_delay) if(buttons&cwiid.BTN_RIGHT): print'Rightpressed' time.sleep(button_delay) if(buttons&cwiid.BTN_UP): print'Uppressed' time.sleep(button_delay) if(buttons&cwiid.BTN_DOWN): print'Downpressed' time.sleep(button_delay) if(buttons&cwiid.BTN_1): print'Button1pressed' time.sleep(button_delay)

92

if(buttons&cwiid.BTN_2): print'Button2pressed' time.sleep(button_delay) if(buttons&cwiid.BTN_A): print'ButtonApressed' time.sleep(button_delay) if(buttons&cwiid.BTN_B): print'ButtonBpressed' time.sleep(button_delay) if(buttons&cwiid.BTN_HOME): print'HomeButtonpressed' time.sleep(button_delay) if(buttons&cwiid.BTN_MINUS): print'MinusButtonpressed' time.sleep(button_delay) if(buttons&cwiid.BTN_PLUS): print'PlusButtonpressed' time.sleep(button_delay)

93

XBox360Pad
InstalltheXBoxPadDrivers.
sudoaptgetinstallxboxdrv

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

Createamappingfile
(createadirectorytoputthemappingsin)
cd~ mkdirXbox cdXbox sudonanobasic_config
[xboxdrv] silent=true deadzone=6000 dpadasbutton=true triggerasbutton=true [uiaxismap] #MaptheRightsticklikeamouse. x2=REL_X:10 y2=REL_Y:10 #Maptheleftstickaskeys x1=KEY_A:KEY_D y1=KEY_W:KEY_S #Mapthe4colouredbuttons [uibuttonmap] a=KEY_LEFTSHIFT b=BTN_C x=BTN_EXTRA y=KEY_C #MaptheBumperButtons [uibuttonmap] lb=BTN_RIGHT rb=KEY_SPACE #MaptheTriggers. [uibuttonmap] lt=KEY_Z rt=BTN_LEFT #MaptheDPAD [uibuttonmap] dl=KEY_4 dr=KEY_2 du=REL_WHEEL:1:150 dd=REL_WHEEL:1:150 [uibuttonmap] back=KEY_TAB start=KEY_ESC GUIDE=BTN_HOME

Anexamplemappingfilecanlooksomethinglike this... (LeftStickactslikeKeys,WASD) (RightStickactslikemousex2,y2) (copyandpastethefollowing!)

94

AlternativeJoystickSetup. Foranalternative(forusewithpygameetc)use ABSValues(notREL)


[uiaxismap] #RightsticktoABS x2=ABS_X y2=ABS_Y #LeftsticktoMouse x1=REL_X:10 y1=REL_Y:10 [uibuttonmap] a=BTN_A b=BTN_B x=BTN_X y=BTN_Y

AlternativeSetupForXBMC.
#XBMCConfiguration #================== # #ThisconfigurationfilethatwithXBMCbyemulatingawireless #Xbox360controllerconnectedtothexpadkerneldriver.Itusesthe #configurationfilesthatcomewithXBMC,soitshouldworkoutof #theboxwithoutanyfurtherconfigurationofXBMC. # # [xboxdrv] uiclear=true extradevices=false extraevents=false deadzone=6000 devicename="Xbox360WirelessReceiver" [uibuttonmap] #A=BTN_A A=KEY_ENTER #B=BTN_B B=KEY_BACKSPACE X=KEY_X Y=KEY_ESC #SteuerkreuzLinksmachtA,SteuerkreuzRechtsmachtB #DU=BTN_0 DU=KEY_UP #DD=BTN_1 DD=KEY_DOWN #DL=BTN_LEFT DL=KEY_LEFT #DR=BTN_RIGHT

95

DR=KEY_RIGHT START=BTN_START GUIDE=BTN_MODE BACK=BTN_BACK LB=BTN_TL RB=BTN_TR #TL=BTN_THUMBL TL=BTN_RIGHT #TR=BTN_THUMBR TR=BTN_LEFT RT=KEY_EQUAL LT=KEY_MINUS [uiaxismap] #x2=REL_RX:10 #y2=REL_RY:10 x1=REL_X:10 y1=REL_Y:10

#Therespfiltermovestheneutralpositiontozerotoworkarounda #buginXBMC,thatcausesboguseventswhenneutralpositionis #elsewhere.Itlosesabitofprecisioninthetriggerasresult,but #thatisn'tnoticable. LT^resp:127:255=ABS_Z RT^resp:127:255=ABS_RZ #EOF#

Callthemappingusing
sudoxboxdrvconfigbasic_config

Runitinthebackgrounusingtheabovewithan&attheend. Alternativecalling
1)Startxboxdrvviaforexample(immycasefor2controllers): sudoxboxdrvwid0silentdeadzone4500uibuttonmapguide=KEY_ESCled8priorityrealtime fourwayrestrictoruiaxismapx1^resp:32000:4000:0:4000:32000,y1^resp:32000:4000:0:4000:32000& sudoxboxdrvwid1silentdeadzone4500uibuttonmapguide=KEY_ESCled9priorityrealtime fourwayrestrictoruiaxismapx1^resp:32000:4000:0:4000:32000,y1^resp:32000:4000:0:4000:32000& "led...","fourwayrestrictor","uiaxismap..."shouldnotbeneeded,butIplayedaLOTwithnearlyall settings,becauseofanotherproblem.Ifoundout,that"deadzone"isinfactneededforsomegames whenplayingwiththeanalogstick.

Killallrunningversionsusingthekillallcommand.
sudokillallxboxdrv

96

97

UsingaPS3controller
In one of my earlier posts, I enabled control of a robotic arm through a PS3 sixaxis controller. To do this, we need to install the qtsixa package. sudoaptgetupdate sudoaptgetinstallqtsixa

http://bootingrpi.blogspot.co.uk/2012/08/dualshock3andraspberrypi.html http://www.raspians.com/Knowledgebase/ps3dualshockcontrollerinstallontheraspberrypi/ https://help.ubuntu.com/community/Sixaxis

Dualshock3andRaspberryPI
GettingSonyDualshock3gamepadtoworkinRaspberryPionRaspbian(DebianWheezy).

Firstofall,I'llneedabluetoothdongle,sinceRaspberyPidoesn'thavebuiltinone,listingofcompatible dongleyoucanfindhere. So,installdependenciesfirst


sudoaptgetinstallbluezutilsbluezcompatbluezhcidumpcheckinstalllibusbdevlibbluetoothdevjoystick

Ittakesawhile. Afteralltype"hciconfig"inconsole,youshouldseesomethinglikethis. pi@raspberrypi~$hciconfig hci0:Type:BR/EDRBus:USB BDAddress:00:1F:81:00:06:20ACLMTU:1021:4SCOMTU:180:1 UPRUNNINGPSCAN RXbytes:1260acl:0sco:0events:46errors:0 TXbytes:452acl:0sco:0commands:45errors:0 ifnot,yourdongleseemsnottoberecognizedbysystem. Sonow,weneedtopairingthedonglewiththegamepadusingthistool. downloadandcompileit.
sudoaptgetinstallpyqt4devtools sudowgethttp://www.pabr.org/sixlinux/sixpair.c gccosixpairsixpair.clusb

98

Afterthisyoushouldhaveaexecutablefile"s i x p a i r " . NowconnectyourDualshockviaaUSBcabletoRaspberryPiandlaunchthisfilewithsudo.


sudo./sixpair

CurrentBluetoothmaster:DE:AD:BE:EF:00:00 Settingmasterbd_addrto:00:1F:81:00:06:20 Ifyouseethis,itwassuccessful. InstallaSixaxisJoystickManager.Downloadalastarchiveandcompileonlyimportantforuspart. sudowgethttp://sourceforge.net/projects/qtsixa/files/QtSixA%201.5.1/QtSixA1.5.1src.tar.gz


sudotarxfvzQtSixA1.5.1src.tar.gz cdQtSixA1.5.1/sixad make sudomkdirp/var/lib/sixad/profiles sudomakeinstall

thelastcommandmakeautomaticallyapackageforyou,soyoucanlatersimpleuninstallit,ifyouwon't itoruseadifferentsystem,type"sudomakeinstall"insteadof"sudocheckinstall" Nowtestit,forthislaunchtemporaryasixaddaemon.


sudosixadstart

Thenpressa"PS"buttononDualshockgamepad,ifyoufeelavibration,itworks,congratulations! Afterallyoucanmake"sixad"daemonstartingatboottime.
sudoupdaterc.dsixaddefaults

reboot

Ifyouhaveanytroublewithrecognition,youcandebugyourDualshockcontrollerwith"jstest".
sudojstest/dev/input/js0

PS3Move???
http://www.pabr.org/linmctool/linmctool.en.html

PS3JoystickButtonsandAxes

99

Buttons 4-15 are reported as axes as well as buttons. The axis corresponding to a button can be used to determine how hard the user is pressing on the button, ranging from 0 when there is no press, to -1 for a hard press. For these buttons, the axis number is the same as the button number.

ps3joy.pyalsoexposesthejoystick'sthreeaxisaccelerometerandthesingleaxisgyroscope: Axis 16 17 18 19 Description Right-Left (positive is left) Forward-Backward (positive is forward) Up-Down (positive is up) Yaw axis (positive is clockwise)

QJoyPadTurningJoystickCommandsintoKeypresses.
#Ithinktheliqt4devisVERYimportanthere! DownloadtheQJoyPadfiles
sudoaptgetinstalllibxtstdevlibqt4devbuildessential wgethttp://downloads.sourceforge.net/qjoypad/qjoypad4.1.0.tar.gz tarxvfqjoypad4.1.0.tar.gz cdqjoypad4.1.0.tar.gz/src ../configure make sudomakeinstall

100

Justrun
qjoypad

(shouldshowupinthesystemtraywithalittlegamepadicon.) ManualHerehttp://qjoypad.sourceforge.net/doc/doc_index.html

101

HARDWAREUSBDevices
WIFIADAPTER???
TPLinkwn725n(V2)

98

http://www.raspberrypi.org/phpBB3/viewtopic.php?f=26&t=29752 http://blog.elevendroids.com/2012/12/precompiledtplinkwl725ndriverfor3227kernel/
1.copy8188eu.koto /lib/modules/3.6.11+/kernel/driver/net/wireless 2.sudodepmoda 3.modprobe8188eu 4.ifconfig Rollyourowndriverfromthissource. https://github.com/lwfinger/rtl8188eu ClonetheGithub gitclonehttp://github.com/lwfinger/rtl8188eu(NoteItookthesoffthehttp) RASPBMCVersionherehttps://dl.dropboxusercontent.com/u/99979776/8188eu.ko http://smhaziq.blogspot.co.uk/2013/06/compilingtplinkwn725nv2driverin.html

EdimaxDongle
http://www.savagehomeautomation.com/projects/raspberrypiinstallingtheedimaxew7811unusbwifi adapte.html

QuickWebcamMonitorGuideviaMotion
sudoaptgetinstallmotion sudonano/etc/motion/motion.conf ChangeDaemonoffTODaemonon Changewebcam_localhost=onTOwebcam_localhost=off Thenctrl+x,Yandthenentertosave Thendo:sudonano/etc/default/motion Changestart_daemon_motion=noTOstart_darmon_motion=yes Thenctrl+x,Yandthenentertosave. Thentype:sudoservicemotionstart Thentypeifconfigandpickoutthenumberthatwilllooklike192.168.x.xxx.ThisisyourlocalIPaddressof thePI. Gotoabrowserandtypeitini.e.192.168.1.101thenput:8081.soitwilllooklike 192.168.1.101:8081.Thenyouwillseewhatyourwebcamsees. 102

PS3CameraTestunderXDE.
YoucanuseGuvcview,(thiswillonlyworkwhenusingthePi,notviaSSH!)
sudoaptgetinstallguvcview

OnceinstalledstartupX(ifyouhaventalready)youshouldnowfindalinkundermenu(soundand video),runtheapp,shouldcomeupwithapreviewwindowandasettingswindow.Ifoundthismore responsivethanMOTION(seebelow)andagreatwaytotesttheeyetoy.(onlyseemedtowork320x240 butfor2whocares!)

PS3EyetoyCameraStreaming
N.B.ThisONLYworkedformewiththecamerapluggedintothePI,nottheHUB! YoumayalsohavetodoHexxehsrpiupdate(togetthelatestfirmware!) JustmanagedtogetmyPS3EyecameraworkingwiththePi,sothoughtI'dsharehowit'sdoneinDebian.The followingstepswillgetthecameraandPiworkingtogetherasasimplemotiondetectiondevicewithawebstream thatyoucanviewonyourlocalnetwork: 1.Installthe'motion'package(http://www.lavrsen.dk/foswiki/bin/view/Motion/WebHome): sudoaptgetinstallmotion 2.Installtheffmpegpackage: sudoaptgetinstallffmpeg 3.Editthe/etc/motion/motion.conffileandchangethefollowingsettingfrom'on'to'off'.Thisisoptional,butwill allowthecameratobeviewedusinganotherPConyourlocalnetwork: webcam_localhostoff 4.Ifyouwishtohavebasiccontroloverthecamerafromawebbrowser(seestep11)thenyoucanchangethe followingsettinginthesamefileto'off': control_localhostoff 5.SincethePS3Eyecameraiscapableofcapturingataresolutionof640x480,wecanmakethefollowingfurther changestothe/etc/motion.conffile:

ffmpeg_video_codecmsmpeg4
width640 height480
# T e x t i s p l a c e d i n l o w e r l e f t c o r n e r t e x t _ l e f t S E C U R I T Y C A M E R A % t O f f i c e I n s t a l l w p u t s o c a n F T P f i l e s . # C o m m a n d t o b e e x e c u t e d w h e n a p i c t u r e ( . p p m | . j p g ) i s s a v e d ( d e f a u l t : n o n e ) # T h e f i l e n a m e o f t h e p i c t u r e i s a p p e n d e d a s a n a r g u m e n t f o r t h e c o m m a n d . o n _ p i c t u r e _ s a v e w p u t f t p : / / U S E R N A M E : P A S S W O R D @ R E M O T E S E R V E R % f

103

6.PlugyourPS3EyecameraintoaUSBportonthePi. 7.FindouttheIPAddressofyourPiandmakeanoteofitforstep10: ifconfig Thiswillgivethefollowingoutput:


e t h 0 L i n k e n c a p : E t h e r n e t H W a d d r x x : x x : x x : x x : x x : x x i n e t a d d r : 1 9 2 . 1 6 8 . 3 2 . 4 7 B c a s t : 1 9 2 . 1 6 8 . 3 2 . 2 5 5 M a s k : 2 5 5 . 2 5 5 . 2 5 5 . 0 i n e t 6 a d d r : f e 8 0 : : b a 2 7 : e b f f : f e 4 0 : 3 5 7 a / 6 4 S c o p e : L i n k U P B R O A D C A S T R U N N I N G M U L T I C A S T M T U : 1 5 0 0 M e t r i c : 1 R X p a c k e t s : 3 1 8 0 0 e r r o r s : 0 d r o p p e d : 0 o v e r r u n s : 0 f r a m e : 0 T X p a c k e t s : 2 7 1 0 8 e r r o r s : 0 d r o p p e d : 0 o v e r r u n s : 0 c a r r i e r : 0 c o l l i s i o n s : 0 t x q u e u e l e n : 1 0 0 0 R X b y t e s : 2 0 1 7 4 9 1 9 ( 1 9 . 2 M i B ) T X b y t e s : 2 9 8 3 8 7 5 0 ( 2 8 . 4 M i B )

Theaddressintheaboveexampleis192.168.32.47. 8.Startupthemotionapplication.NotethatithasnoGUIandcanberunfromthecommandlinewhenyoufirststart upthePi.Itdoesn'tneedtorunwithinstartx: sudomotionn 9.Thiswillrunthesoftwareincommandlinemode,displayingstartupinformationanderrorsdirectlytotheconsole.It alsoallowsittobestoppedusingCtrlC.Ifyouwanttorunthesoftwareinthebackgroundasa'daemon',simplytype 'motion'withoutthenswitch. 10.Ifeverythinghasworkedokay,youshouldbeabletogotoanothercomputeronyournetworkandbrowsetoyour Pi'saddresstoseethecameraoutput: http://192.168.32.47:8081 UsingyourPi'saddressofcourse! 11.YoucanalsobrowsetothefeedonthePiitself,althoughthiswillonlyworkinChromeandnotMidori. 12.Ifyoubrowsetothe'controlport'addressbelow,youalsogetrudimentarycontroloverthemotionsoftware: http://192.168.32.47:8080 13.Sincethisisamotiondetectionpackage,itautomaticallydetectsmovementonthecameraandcreates'.jpg' imageand'.swf'videosnapshotseachtimeitseesmovementonthecamera.Thesearestoredinthefollowing directory: /tmp/motion 14.Notethatthesefileswillbuildupquitequicklyifthecameraispointedatsomethingthatmovesalot,somake sureyouhaveplentyofspaceonyoursdcard.Also,sincethefilesarestoredin/tmp,theywillbedeletedeachtime yourebootyourPi.

FurtherReadingherehttp://chris.gg/2012/07/usingaps3eyetoywiththeraspberrypi/ (runningasadaemon!) Agreatwaytoviewyourimages/swfvideosistouseWinSCPanddigthemoutofthe /root/tmp/motionfolder(unlessyouchangedit!) 104

FaceRecognitiononthePi.
Tutorialandguidefoundhere Itsabitdisjointedinplaces,someofthecodeisabitunclear(inthewrongplace)ornotquitethere,this hasadifficultyofHARD!ButIhavelearnlotsalongtheway!:)

GUVCVIEW
Firstgetthewebcamworkingwithguvcview(seeabove
sudoaptgetinstallupdate&&aptgetinstallupdatey sudoaptgetinstallguvcview

CMAKE
NextinstallCMAKE(thisallowsyoutocompileccodeonthepi!)
sudoaptgetupdate sudoaptgetinstallcmake

OPENCV
InstallthecodetorunOpenCVoncecompiledfromPython
sudoaptgetupdate sudoaptgetinstalllibopencvdev sudoaptgetinstallpythonopencv

Testingthisinstalledisalittlemorecomplicated!FirstgoheretofindthecodeforOpenCV MakeanewfoldercallitOpenCV
mkdirOpenCV sudonanodisplayimage.cpp

pastethefollowingcodein(dontusethelink,someofthecodeismissingCVparts!)
#include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> #include<iostream> usingnamespacecv usingnamespacestd intmain(intargc,char**argv) { if(argc!=2) { cout<<"Usage:display_imageImageToLoadAndDisplay"<<endl return1 } Matimage image=imread(argv[1],CV_LOAD_IMAGE_COLOR)//Readthefile if(!image.data)//Checkforinvalidinput { cout<<"Couldnotopenorfindtheimage"<<std::endl

105

return1 } namedWindow("Displaywindow",CV_WINDOW_AUTOSIZE)//Createawindowfordisplay. imshow("Displaywindow",image)//Showourimageinsideit. waitKey(0)//Waitforakeystrokeinthewindow return0 }

Makeanotherfileformakeinstructions.
sudonanoCMakeLists.txt

pastethefollowingcodeintoit.
cmake_minimum_required(VERSION2.8) project(displayimage) find_package(OpenCVREQUIRED) add_executable(displayimagedisplay_image.cpp) target_link_libraries(displayimage${OpenCV_LIBS})

Saveit(thisisthefilethatgivethecompilerthesettingstouse,youllbechaningthisseveraltimes) Findareasonablesizedimageonthenet(ajpgimagearound300x300),Iused
wget<url>

tograbthefile,thenrenameitusing
mv<filename.jpg>sample.jpg

toputitalltogetherfinally,compilethec,maketheinstructionfile(executable)andrunthecode.
cmake. make ./displayimagesample.jpg

Ifallhasworkedyourpicture*should*appearonthescreen!

InstallthefacerecognitionAPI
Downloadthelibfacerecfile,unzip,compileandmake.
wgethttps://github.com/bytefish/libfacerec/zipball/v0.04 unzipv0.04 rmv0.04 cdlibfacerec cmake. make

Thissoundsbonkersbuttotestifitsallinstalledokwegobacktoyourdisplayimageexample.Editthe makefiletoincludethelibfacereclibraries.(Looksomethinglikethis!)
cmake_minimum_required(VERSION2.8) project(reco)

106

find_package(OpenCVREQUIRED) add_executable(displayimagedisplay_image.cpp) target_link_libraries(displayimage/home/pi/libfacerec/bytefishlibfacerece1b143d/libopencv_facerec.a ${OpenCV_LIBS})

Compileandmakeagaintotestitworks.
cmake. make ./displayimagesample.jpg

Hopefullythiswillwork,ifitdoesthingsaregoingwell.

GatheringPhotos YouhavetotrainthePitoKNOWwhoitslookingat.Todothisitneedsasetofportraitphotos(30suggested). Theyshouldbeheadshots,faceon.HoweveryoucanjustsavealargeselectionofphotosandthengetthePito sort,prepandpreenthem.DumptheinitialphotosintheOpenCVfolder.(ensuretheyreallcalleda1.jpg,a2.jpgetc.) TimeforanotherCProgram,Prepare EdittheCMakeLists.txtfileagainwith cmake_minimum_required(VERSION 2.8) project( prepare ) find_package( OpenCV REQUIRED ) add_executable( prepare preparePhoto.cpp ) target_link_libraries( prepare ${OpenCV_LIBS} ) usewgettogathertheprogram. wgethttp://raufast.org/download/preparePhoto.cpp cmake. make ./prepare0.3100hs8001 This will probably crash out a few times, just delete the offending file and re-run. It saved all of my files as hsX.jpg. Youll 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 Thisisdifficulttogetright,butyouneedtogenerateaCSVfilethatwillbeusedlaterbythereco(recognition software).Itrieddoingthismanuallybutcouldntgetitwork.Theresascriptyoucanrun.(availablefromhere) N.B.(You can do this just using WinSCP, highlight all the files, use copy to clipboard, use nano to create a new .csv file, paste in, use ;0 as the delimiter on each line!) But the script will probably work better for most folk. #!/usr/bin/envpython importsys importos.path #ThisisatinyscripttohelpyoucreatingaCSVfilefromaface #databasewithasimilarhierarchie: #

107

#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__": iflen(sys.argv)!=2: print"usage:create_csv<base_path>" sys.exit(1) BASE_PATH=sys.argv[1] SEPARATOR="" label=0 fordirname,dirnames,filenamesinos.walk(BASE_PATH): forsubdirnameindirnames: subject_path=os.path.join(dirname,subdirname) forfilenameinos.listdir(subject_path): abs_path="%s/%s"%(subject_path,filename) print"%s%s%d"%(abs_path,SEPARATOR,label) label=label+1

IdumpedthisintheFacesfolder,thenranusing
pythoncreate_csv.py/home/pi/OpenCv/Faces>faces.csv

IlatermovedthiscsvbackoutintotheOpenCvFolder(easier)

InstalltheRecoProgram
EditouroldfriendtheCMakeLists.txt.
cmake_minimum_required(VERSION2.8) project(reco) find_package(OpenCVREQUIRED) add_executable(recofaceReco.cpp) link_directories(/home/pi/libfacerec/bytefishlibfacerece1b143d) target_link_libraries(reco/home/pi/libfacerec/bytefishlibfacerece1b143d/libopencv_facerec.a${OpenCV_LIBS}) wgethttp://raufast.org/download/faceReco.cpp cmake. make.

108

FINALLY...
RunthedamnthingfromX(onthePI)
./recofaces.csv15500

IwilldosomefurthertestingonthisandgetsomephotosofmyselfandperhapsanotherindividualandseewhatIcan getworking.Aninterestingidea/conceptthough!ItwasabletorecogniseatleastonepictureofAngelinaJolieI used!Furthertestingwithipadtofollow!

RemovingtheIRFilteronTheEyetoy
http://createdigitalmotion.com/2009/08/trickoutyourps3eyewebcambestcamforvisionaugmentedr eality/ Thisvideodemonstrateshowtodisassemble,removeIRFilterandreassemble!)

UsingMultipleCameraswithMotion
Todothisyouneedtoaddathreadpercamera.
sudonano/etc/motion/motion.conf

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

etc... Youneedaconfig(conf)foreachcamerayouintendtouse. createthethread1.conffileusing


sudonano/etc/motion/thread1.conf

Itonlyreallyneedsthefollowingcode.
videodevice/dev/video0 text_leftUSBWebcam1 target_dir/home/ndmaque/motion/images/webcam2 webcam_port8081

Similarlycreatethread2.conf
sudonano/etc/motion/thread2.conf videodevice/dev/video1 text_leftUSBWebcam2 target_dir/home/ndmaque/motion/images/webcam2 webcam_port8082

Noticehowtheyhavedifferentportssoyoucanaccessthemseperately,(notethesepartedevices!) 109

http://www.lavrsen.dk/foswiki/bin/view/Motion/MotionGuideOneLargeDocument http://throughtheinterface.typepad.com/through_the_interface/2012/09/creatingamotiondetectingsecu ritycamwitharaspberrypipart2.html

Retaliation(USBRocketMOD!)

RocketLauncherhttp://itr8r.tumblr.com/post/31840231144/raspberrypiretaliation Retaliationhttps://github.com/codedance/Retaliation#readme RetaliationinScratchhttp://itr8r.tumblr.com/post/40413865818/scratchretaliation N.B.YoucanplugtherocketlauncherintothePi,butitwillprobablyerror,ortryaHUB,butitwillneed somepowergoingtoit.1amp?FireFAILSonmysetup(Isuspectduetoitbeingknackeredorlackof power!)Willtestatschoolwhengetchance! Thepythonusbyummoduleisnotnewenoughtoworkwiththeretaliationcode.Insteaddownloadthe sourcefor1.0frompyusb. Untarintoadirectory,theninstallpyusbwith:


sudoaptgetinstallpythonlibusb0.14 gitclonehttps://github.com/walac/pyusb.git cdpyusb sudopythonsetup.pyinstall

Step2Downloadretaliation:
sudowgethttps://raw.github.com/codedance/Retaliation/master/retaliation.py sudochmod+xretaliation.py

Step3Connectandtest Connectthemissilelauncher(IusedapoweredUSBhub)andtestwithacommandsuchas
sudo./retaliation.pyzero sudo./retaliation.pyleft1000

Step4Modifythescriptasneededforyouroffice&enjoy

RetaliationModificationtoScript.(TOREDOtouseKEYBOARD!)

110

TVHeadTestforXBMC
IgotaAugustDVBT205TVCaptureUSBStick/Dongle.HeardtheyarecompatiblewithRPi etc,andfanciedgivingLiveTV/PVR/Streamingago. Ididsomegeneralreadingaroundtheselinks. https://github.com/ambrosa/DVBRealtekRTL2832U2.2.210tunermod_kernel3.0.0

http://www.raspberrypi.org/phpBB3/viewtopic.php?t=18090 http://forum.stmlabs.com/showthread.php?tid=2912 http://www.raspberrypi.org/phpBB3/viewtopic.php?t=18090 http://www.packtpub.com/article/usingpvrwithraspbmc

GettingthedevicerecognisedinLinux. Firstensuresomedependantsareinstalled(incaseofcompilingetc)
sudoaptgetinstallmakegccpkgconfiglibavahiclientdevlibssldevbuildessential

GettheAugustDVBT205Driver https://mega.co.nz/#!nZNkRJzS!Mx3BSGwU6BQLFUVkuY4ce0h7IDtKSELDc5USfKsyg3 k
IwasunabletoWGETthisfileasitsaMEGAload(oneyouhavetoclickthroughonandsupplya catchpa. IthenWinSCPdDrivertoPi. Untarit.
sudotarxvf<filename>

Copytocorrectfolder(youcanusemv</path/filename></newpath/filename>),butIthinkIdidinin WinSCP(movedthe.kofile)
/lib/modules/3.6.11/kernel/drivers/media/dvb/dvbusb/

RefreshthedriversinLinuxtopickupthischangeusing
sudodepmoda(toupdateallthedriversetc)

reboot.

NOTE:ThisDongleONLYseemedtoworkifpluggedintothePI!!!
TVHeadbackendhttp://wiki.xbmc.org/index.php?title=PVR/Backend/Tvheadend AccessTVHeadusinghttp://<PiIPAddress>:9981 111

SofarmanagedtogetTVchannelstuned,EPGworking(viawebbrowser)andthenrecorda programints(standardformat)orMKVthatseemsbetter! SomedetailhereaboutwatchingLiveTVthatdoesnotseemtowork. http://forum.xbmc.org/showthread.php?tid=148646&page=34 Stuffstilltodo,getwirelessworkingwithLloydsUSBDongle? AddaHDDandtryrecordingtoit,setthisupasaSambaShare!!!

112

SOFTWARE

109

GitHubsWhyTheyRock!
GitHubsarerepositoriesoffiles/softwarethatarecreated/usedwhenserveralpeopleareworkingon/ updatingasinglesoftwareproject.Othertimesthiscanjustbeacollectionoffile,e.g.Pythonscriptsofa particulartype/collection.Sometimesyoumightwanttoget/collect/grabtheGITsothatyoucan compileyourownversion,orusethecollection. FirstlyinstallthedriversandsoftwaretodealwithGitHubs sudoaptgetinstallgitcore ItcanoftenbehandytoCLONEanentireGitHub!!!

Howtocloneyourrepotoyourlocalmachine?
(in git terminology its 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. Typecommand:
gitcloneADDRESSYOUCOPIED

toupdatenavigatetotherightfolderanduse.
gitpull

Whenyouseeanewscriptpostedontheblog,togetitonyourraspberrypiallyouneedtodoisrunthe followingcommandtogetthelatestupdates: 1. Rungitfetchorigintodownloadthelatestupdates 2. Rungitmergeorigin/mastertoupdatethefilesinyourcurrentdirectorywiththem. gitclonegit://github.com/??????????

113

CompilingYourOwnVersionofSoftware(Rollyourown!)
Grab
FirstlyGrabthesoftwarepackageyouwant(oftenTar.gz,aTarfile(tapearchive)thathasbeen compressedusingGzip) usethecommandwget<filepath>tograbtheTar.gz
wget<fullfilepathinchttp://>

extractthetar.gztoapathusing
tarxvf<filename>

deletetheoriginalfile
rm<filename.tar.gz>

entertheextractedfolder
cd<filename>

Configure
NowtoConfigureyourpackageuse
sudo./configure

Make
NowMAKEthepackage(thisoftentakesages!)
sudomake

MakeInstall
NowdoaMAKEINSTALL,thisinstallsthesoftwareforyourusages?
sudomakeinstall.

114

SOFTWAREInterfacing
PiWall(WORKING!)

111

http://www.piwall.co.uk/information/10createyourowngplmoviepiwall Thiscodesshouldallowyoutoplaybackavideoonavideowallofsevealscreens! (startwithx4!) ThesetupmustconsistofaMasterthateffectivelybroadcaststotheslavetiles 41istopleft 42topright 43bottomleft 44bottomright Iassumethefirst4referstothefactitsax4screens.Theeachoneisaddressedindividually.

Settinguptheunits.
installlibavtoolsoneachpi.
sudoaptgetinstalllibavtools

Copypwlibs1_1.1armhf.debandpwomxplayer_20130815_armhf.debtothehomedirectory. extractdpkgtheboth.
sudodpkgi/home/pi/pwlibs1_1.1_armhf.deb sudodpkgi/home/pi/pwomxplayer_20130815_armhf.deb

Networkconfiguration
EachPineedstohaveadifferentIPaddress(obviously!)andyoualmostcertainlywantthesetobe staticallyassigned.ForthisGuidewe'llassumeaprivateaddressrangeof192.168.0.*ifyouneedtouse anothersetofaddresses,thenadjustaccordingly. Inaproductionenvironment,youmaywanttoconnectthemasterPitoanexistingnetworkthisisbest achievedbyaddingaUSBethernetorWiFiadapterasasecondinterfacetothemaster.Configuringthis secondnetworkinterfaceisbeyondthescopeofthisdocument. Inorderforthemastertocommunicateefficientlywiththetiles,itusesmulticastaddressing(whereeach packetsentbythemasterisreceivedbyallthetiles).Therulesandguidelinesforusingmulticast addressesarecomplexifthenetworkiscompletelyprivatethenitdoesn'treallymatter,butinthisGuide 115

we'lluseoneofthe"administrativelyscoped"addresses,239.0.1.23.Ifyouplantouseareal,shared network,thenspeaktoyournetworkadministratortoagreeanaddress. IfyouareusingaLinuxPCasyourmasteranddontwanttopermanentlyalteryournetworkconfiguration thenexecutethefollowingcommandsafteryouhaveconnectedtotheprivatePiWallnetwork. sudoifconfigeth0192.168.0.???netmask255.255.255.0up sudorouteaddnet224.0.0.0netmask240.0.0.0eth0 Notethatthisenablesthefullmulticastaddressrange,eventhoughwe'llonlybeusingasingleaddress withinthatrange. TomakethisroutingpermanentonaRaspberryPimasterortile,editthenetworkinterfacestanzain"/ etc/network/interfaces",e.g. ifaceeth0inetstatic address192.168.0.??? netmask255.255.255.0 uprouteaddnet224.0.0.0netmask240.0.0.0eth0 Weusuallyuseanaddressof100forthemasterandnumberthetilesfrom1,upwards.

Testingthesoftware
Firsttestatiletoensurethatitisworkingcorrectly.Startbyconnectingakeyboardtothetileand attachingaUSBpendrivethatcontainsamoviethatthestandardomxplayercandisplay.Findthepathof theUSBpendrive,fromthecommandlinetype"df"thiswilllistallthefilesystemsonyourPi.Intheright handcolumn,lookfortheentrythathasapaththatstartswith"/media/",onmysystemitis "/media/18DA7CE4".Prependthispathtothe"movie.avi"argumentinthefollowingcommands.Confirm thatthemoviecanbeplayedbythestandardomxplayerprovidedwiththeRaspbianimagebytyping "omxplayermovie.avi"atthecommandprompt.Nextverifythatpwomxplayercanplaythemovieby typing"pwomxplayermovie.avi".Finallycheckthatpwomxplayercanshowasectionofthevideoby typing"pwomxplayertilecode=42movie.avi"whichshoulddisplayjustthetoprightcorneroftheoriginal movie,butmagnifiedtofillthewholescreen. Nowyou'rereadytotestthemasterinconjunctionwithoneormoretiles.OneachRaspberryPitiletype "pwomxplayertilecode=$nudp://239.0.1.23:1234?buffer=1200000B"(where$n=41isthetopleft,42is thetopright,43isthebottomleftand44isthebottomrightfora4screenPiWall).Onthemastertype "avconvreimovie.avivcodeccopyfavianudp://239.0.1.23:1234"

(possiblewithoutputsound? avconvreimovie.avivcodeccopyfavianudp://239.0.1.23:1234enableoutdev=ALSA

116

The"tilecode"configurationdoesn'tprovidebezelcompensation,forthatyouwillneedtoprovidea detailedPiWallconfigurationfile.Thatwillbethesubjectofafurtherguidetobepublishedlaterthisweek.

LoopinganVideoonthescreens.
OntheRaspberryPimasterjustcreateasimplebashscript(youcouldsaveitas"forever")... whiletrue do avconvreimovie.avivcodeccopyanfaviudp://239.0.1.23:1234 done Don'tforgettoeithermakethescriptexecutableorrunitbyprependingthenameofthebashscriptwithsh,eg"sh forever".

MulticastingInputfromthePiCamera(untested!)
IntheoryitshouldbepossibletoPIPEtheoutputofthePiCameratodisplayonyourvideowallusing somethinglikethis.
raspividot10000vf|avconvrervcodeccopyfavianudp://239.0.1.23:1234

Thet10000mightnotbeneeded(untiltested!) Thevfistheverticalflipofthecameraoutput.

117

Fritzing
http://fritzing.org/forum/thread/1338/

PICar
ThePiCarprojectlikemanyothersnowseemtobedoingcontrolsaremotecontrolledcarusingthe remotehackedtoworkwiththeGPIOpinsontheRPi.Theresevenapythonscriptthatcanberunso thatyoucancontrolthecarthroughScratch.

http://picars.com/ http://picars.com/underthebonnet/ http://picars.com/2012/12/23/picarsandscratchdrivinglesson1/ thispageguidesyouonhowtocreatethePythonfileneededtohookinto Scratch.

118

UsingTwitter
http://blog.kugelfish.com/2012/08/kugelbotorwhattodowithraspberrypi.html https://pypi.python.org/pypi/twitter/ Theprojectslistedhereallrequireyoutohaveatwitteraccount.Isetupaseperateaccountso IcoulddoPiTesting. @AMC_PI letmein(withafewnumbers)Addthistokeepassandremove. Onceyouhavesignedupyouneedtologintohttps://dev.twitter.com,thiswillallowyouaccessto creatingappsaround/usingtwitter.YoullneedtocreateanewAPP. Youwillneedtothencarryoutthefollowingstepsinordertogetaccesskeysandconsumerkeyswhich willallowustoauthenticatethetwitteraccountandapplicationwithouthavingtokeepenteringinlogin data.ThisusestheOAuthprotocolwhichyoucanfindoutmoreaboutusinggoogle! 1. Selectcreateanewapplication 2. Entername,description,website 3. SelectYesIagreetothetermsandconditions 4. Entercaptchainformationandclicksubmit Youwillseethatbydefaulttheaccesslevelissettoreadonly.Wewillneedtochangethistoread/write toenableustopushtweetsouttotheworld.Tochangethissettingscarryoutthefollowingsteps. 1. Selectsettingsalongtopmenutabs 2. UnderapplicationtypeselectReadandWrite 3. EnsurethatAllowthisapplicationtobeusedtoSigninwithTwitterischecked 4. Clicktheupdatethistwitterapplicationssettingsbuttonatthebottomofthepage IfyounowreturntotheDetailstabyouwillseeanumberofspecialkeyswhichinclude,consumer key/secretandaccesstoken/secret.Leavethewebpageopenaswewillneedallofthisinformationina minutetostarttweeting. Onceyouhavedonesothereare4keysbitsofinfoyouneedformostoftheseprojects. ConsumerKey ConsumerSecret AccessToken AccessTokenSecret Thesearejustrandomstringsofletters/numbers,butyouwillneedthemtodoanytwitterwork. AlsoonceyouhavecreatedyourAPP(onthetwittersite)youllhavetochangethesettingsof theapptoeitherreadonlyorread/write.Ifyouchangethesettingsoftheapptheaccess tokenandaccesstokensecretwillchange.Ifoundthisout!Youcanusethesameappsetupin mostofyourPiProjects.

119

CreatingAnArrayofFollowers(PartlyTested)
http://raspi.tv/2013/howtocreateatwitterappontheraspberrypiwithpythontweepypart1

Thisscriptwilljust lookatyour account,workout allyourfollowers andselectoneat random!!!

#!/usr/bin/envpython2.7 #twitterwin.pybyAlexEameshttp://raspi.tv/?p=5281 importtweepy importrandom #Consumerkeysandaccesstokens,usedforOAuth consumer_key='copyyourconsumerkeyhere' consumer_secret='copyyourconsumersecrethere' access_token='copyyouraccesstokenhere' access_token_secret='copyyouraccesstokensecrethere' #OAuthprocess,usingthekeysandtokens auth=tweepy.OAuthHandler(consumer_key,consumer_secret) auth.set_access_token(access_token,access_token_secret) #Creationoftheactualinterface,usingauthentication api=tweepy.API(auth) follow2=api.followers_ids()#givesalistoffollowersids print"youhave%dfollowers"%len(follow2) show_list=str(raw_input("Doyouwanttolistthefollowersarray?")) ifshow_list==('y'or'yes'or'Y'or'Yes'or'YES'): printfollow2 defpick_winner(): random_number=random.randint(0,len(follow2)1) winner=api.get_user(follow2[random_number]) printwinner.screen_name,random_number whileTrue: pick=raw_input("PressEntertopickawinner,Qtoquit.") ifpick==('q'or'Q'or'quit'or'QUIT'or'Quit'): break pick_winner()

120

CreatingaPythonScriptthatcanTweet(Tested)
Createasimplepythonscriptcalled SillyTweeter.py. Usesudochmod+xtomakeit executable. Runusing pythonSillyTweeter.pyThistextwill beoutputtotwitter
N.B.the...aretokeepmytokenssafe! CopyandpasteyourownfromTwitter! #!/usr/bin/envpython importsys fromtwythonimportTwython CONSUMER_KEY='tRrx71zfMENmCV1t......' CONSUMER_SECRET='eMoBaVi8OkoC3j6aDszc4VjXzeuddxV577......' ACCESS_KEY='2161868077KlG5aiRfLuWrweKMpPPO7RFxapWzdHeEV......' ACCESS_SECRET='4HinfnCRL74IRG09c3JCWcy2gcl5QwiBJmbNqbD......' api= Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET) api.update_status(status=sys.argv[1])

CreatingaPythonScriptthatcanTweetImages(Tested)
Calltheprogramlikeyoudidthe lastexample, pythonTweetPhoto.py /home/pi/twitter/test.jpgAny Textyouwanthere onlyinsteadofamessageadd thepathtofileyouwithtooutput!
#!/usr/bin/envpython importsys fromtwythonimportTwython importos CONSUMER_KEY='tRrx71zfMENmCV1t...' CONSUMER_SECRET='eMoBaVi8OkoC3j6aDszc4VjXzeuddxV577...' ACCESS_KEY='2161868077KlG5aiRfLuWrweKMpPPO7RFxapWzdHeEV...' 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

CreateaPythonScriptthatcanTweetImagesViaRaspicam,watermarkthemandTweet Them
sudoaptgetinstallpythonpip
#!/usr/bin/envpython importsys importtime importpicam fromtwythonimportTwython importos CONSUMER_KEY='tRrx71zfMENmCV1tkvVT4Q' CONSUMER_SECRET='eMoBaVi8OkoC3j6aDszc4VjXzeuddxV5776BApo4' ACCESS_KEY='2161868077KlG5aiRfLuWrweKMpPPO7RFxapWzdHeEV7Sqx75' ACCESS_SECRET='4HinfnCRL74IRG09c3JCWcy2gcl5QwiBJmbNqbD7wXoRx' date_bit=time.strftime("%Y_%m_%d") photopath='/home/pi/twitter/'+date_bit+'_photo.jpg' print('Goingtosavefileas:'+photopath) os.system('raspistillotemp.jpgvf') print('Abouttoconvertphoto!') os.system('compositeCTI_Pi_Big.pngtemp.jpggravitysouth'+photopath) print('Justaddedawatermark') 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='PiCamTestFinal')

andthenenter:
sudopipinstall https://github.com/ashtons/picam/zipball/ master#egg=picam importpicam i=picam.takePhoto() i.save(/home/pi/test.jpg)

Youcanusethiscommand,butI couldnotworkouthowtoflipthe image,soinsteadIcanlledthebash commandswithinthescript.This allowedtheuseofimagemagicktoo towatermarkit! MoreonTimeinPython


http://www.cyberciti.biz/faq/howtogetcurrentd atetimeinpython/

CreatingaPythonScripttoOutputSystemInfo
http://cmobberley.com/wordpress/index.php/2013/04/26/raspberrypiconnecttotwitteraccountusingtweepyinstallation andtweetcputemperatureexample/

Itispossibletoadaptthisscriptto outputjustaboutanythingviathe api!Couldbeinteresting.

#!/usr/bin/envpython importos importsys importtweepy CONSUMER_KEY='*****YOURDATA******' CONSUMER_SECRET='*****YOURDATA******' ACCESS_KEY='*****YOURDATA******' ACCESS_SECRET='*****YOURDATA******'

auth=tweepy.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY,ACCESS_SECRET) api=tweepy.API(auth) cmd='/opt/vc/bin/vcgencmdmeasure_temp' line=os.popen(cmd).readline().strip() temp=line.split('=')[1].split("'")[0]

122

api.update_status('MyCurrentProcessorTemperature:'+temp+'C')

TweetingonaSetInterval
(Usingtheaboveexample) Toedittherootcronfileyoumustrunthefollowingcommand.
sudocrontabe

Itisveryimportanttoensurethesudocommandisused! Onceyouareinthefileyoucanthenaddthefollowingline,justchangethedirectorytopointtowhere yourfileissaved.


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

ReadOutTweets(Untested)
http://www.stuffaboutcode.com/2012/10/raspberrypipythontalkingtwitter.html

ThisprocessusesGooglesAPItoreadoutTweets outloud!
Installpythonoauth Iusedleah'spythonoauthmoduletoauthenticatewith twitter. Installdistribute Ifyouhaveneverinstalledpythonmodulesbeforeyouare goingtoneedtoinstallthepythonsetuptools,module, distribute,seeblogpost,pythoninstallingmodules,for infoonhowtodothis. Installgitcore Inordertogetthecodefromgithubyouneedtoinstall gitcoretools. s u d o a p t g e t i n s t a l l g i t c o r e Getthecodefromgit g i t c l o n e h t t p s : / / g i t h u b . c o m / l e a h / p y t h o n o a u t h . g i t Installthemodule c d p y t h o n o a u t h s u d o p y t h o n s e t u p . p y i n s t a l l Installpycurl pycurlisusedtoconnecttothetwitterstreams. s u d o a p t g e t i n s t a l l p y t h o n p y c u r l Installmplayer mplayerisusedtooutputtheaudiostream. s u d o a p t g e t i n s t a l l m p l a y e r Createtalkingtwitterclientprogram n a n o t t c . p y

# ! / u s r / b i n / e n v p y t h o n # A n e x p e r i m e n t a l t a l k i n g t w i t t e r c l i e n t f o r t h e R a s p b e r r y P i # w r i t t e n i n P y t h o n , b y M a r t i n O ' H a n l o n # w w w . s t u f f a b o u t c o d e . c o m f r o m o a u t h . o a u t h i m p o r t O A u t h R e q u e s t , O A u t h S i g n a t u r e M e t h o d _ H M A C _ S H A 1 f r o m h a s h l i b i m p o r t m d 5 i m p o r t j s o n , t i m e , r a n d o m , m a t h , u r l l i b , u r l l i b 2 , p y c u r l , s u b p r o c e s s , s y s # t w i t t e r o a u t h k e y s , g e t y o u r f r o m d e v . t w i t t e r . c o m C O N S U M E R _ K E Y = ' c o n s u m e r k e y ' C O N S U M E R _ S E C R E T = ' c o n s u m e r s e c r e t ' A C C E S S _ T O K E N = ' a c c e s s t o k e n ' A C C E S S _ T O K E N _ S E C R E T = ' a c c e s s t o k e n s e c r e t ' # f u n c t i o n t o d o w n l o a d a f i l e f r o m a u r l , u s e d f o r t e s t i n g d e f d o w n l o a d F i l e ( u r l , f i l e N a m e ) : f p = o p e n ( f i l e N a m e , " w b " ) c u r l = p y c u r l . C u r l ( ) c u r l . s e t o p t ( p y c u r l . U R L , u r l ) c u r l . s e t o p t ( p y c u r l . W R I T E D A T A , f p ) c u r l . p e r f o r m ( ) c u r l . c l o s e ( ) f p . c l o s e ( ) # r e t u r n s t h e a p p r o p r i a t e g o o g l e s p e e c h u r l f o r a p a r t i c u l a r p h r a s e d e f g e t G o o g l e S p e e c h U R L ( p h r a s e ) : g o o g l e T r a n s l a t e U R L = " h t t p : / / t r a n s l a t e . g o o g l e . c o m / t r a n s l a t e _ t t s ? t l = e n & " p a r a m e t e r s = { ' q ' : p h r a s e } d a t a = u r l l i b . u r l e n c o d e ( p a r a m e t e r s ) g o o g l e T r a n s l a t e U R L = " % s % s " % ( g o o g l e T r a n s l a t e U R L , d a t a ) r e t u r n g o o g l e T r a n s l a t e U R L # f u n c t i o n t o d o w n l o a d a n m p 3 f i l e f o r a p a r t i c u l a r p h r a s e , u s e d f o r t e s t i n g d e f d o w n l o a d S p e e c h F r o m T e x t ( p h r a s e , f i l e N a m e ) : g o o g l e S p e e c h U R L = g e t G o o g l e S p e e c h U R L ( p h r a s e )

123

p r i n t g o o g l e S p e e c h U R L d o w n l o a d F i l e ( g o o g l e S p e e c h U R L , f i l e N a m e ) # o u t p u t p h r a s e t o a u d i o u s i n g m p l a y e r d e f s p e a k S p e e c h F r o m T e x t ( p h r a s e ) : g o o g l e S p e e c h U R L = g e t G o o g l e S p e e c h U R L ( p h r a s e ) s u b p r o c e s s . c a l l ( [ " m p l a y e r " , g o o g l e S p e e c h U R L ] , s h e l l = F a l s e , s t d o u t = s u b p r o c e s s . P I P E , s t d e r r = s u b p r o c e s s . P I P E ) # c l a s s f o r m a n a g i n g t o k e n s c l a s s T o k e n ( o b j e c t ) : d e f _ _ i n i t _ _ ( s e l f , k e y , s e c r e t ) : s e l f . k e y = k e y s e l f . s e c r e t = s e c r e t d e f _ g e n e r a t e _ n o n c e ( s e l f ) : r a n d o m _ n u m b e r = ' ' . j o i n ( s t r ( r a n d o m . r a n d i n t ( 0 , 9 ) ) f o r i i n r a n g e ( 4 0 ) ) m = m d 5 ( s t r ( t i m e . t i m e ( ) ) + s t r ( r a n d o m _ n u m b e r ) ) r e t u r n m . h e x d i g e s t ( ) # t a l k i n g t w i t t e r c l i e n t c l a s s T a l k i n g T w i t t e r S t r e a m C l i e n t : d e f _ _ i n i t _ _ ( s e l f , s t r e a m U R L ) : s e l f . s t r e a m U R L = s t r e a m U R L s e l f . b u f f e r = " " s e l f . c o n n = p y c u r l . C u r l ( ) s e l f . c o n n . s e t o p t ( p y c u r l . U R L , s e l f . s t r e a m U R L ) s e l f . c o n n . s e t o p t ( p y c u r l . W R I T E F U N C T I O N , s e l f . o n _ r e c e i v e ) s e l f . c o n n . p e r f o r m ( ) d e f o n _ r e c e i v e ( s e l f , d a t a ) : s y s . s t d o u t . w r i t e ( " . " ) s e l f . b u f f e r + = d a t a i f d a t a . e n d s w i t h ( " \ n " ) a n d s e l f . b u f f e r . s t r i p ( ) : c o n t e n t = j s o n . l o a d s ( s e l f . b u f f e r ) s e l f . b u f f e r = " " # d e b u g o u t p u t j s o n f r o m b u f f e r # p r i n t c o n t e n t i f " f r i e n d s " i n c o n t e n t : s e l f . f r i e n d s = c o n t e n t [ " f r i e n d s " ] i f " t e x t " i n c o n t e n t : p r i n t u " { 0 [ u s e r ] [ n a m e ] } : { 0 [ t e x t ] } " . f o r m a t ( c o n t e n t ) . e n c o d e ( ' u t f 8 ' ) s p e a k S p e e c h F r o m T e x t ( u " A t w e e t f r o m { 0 [ u s e r ] [ n a m e ] } " . f o r m a t ( c o n t e n t ) ) # d o w n l o a d S p e e c h F r o m T e x t ( u " A t w e e t f r o m { 0 [ u s e r ] [ n a m e ] } " . f o r m a t ( c o n t e n t ) , " . / t w e e t . m p 3 " ) s p e a k S p e e c h F r o m T e x t ( u " { 0 [ t e x t ] } " . f o r m a t ( c o n t e n t ) ) # d o w n l o a d S p e e c h F r o m T e x t ( u " { 0 [ t e x t ] } " . f o r m a t ( c o n t e n t ) , " . / t w e e t . m p 3 " ) # g e t t h e u r l n e e d e d t o o p e n t h e t w i t t e r u s e r s t r e a m , i n c l u d i n g s i g n a t u r e a f t e r a u t h e n t i c a t i o n d e f g e t T w i t t e r U s e r S t r e a m U R L ( ) : S T R E A M _ U R L = " h t t p s : / / u s e r s t r e a m . t w i t t e r . c o m / 2 / u s e r . j s o n " a c c e s s _ t o k e n = T o k e n ( A C C E S S _ T O K E N , A C C E S S _ T O K E N _ S E C R E T )

124

c o n s u m e r = T o k e n ( C O N S U M E R _ K E Y , C O N S U M E R _ S E C R E T ) p a r a m e t e r s = { ' o a u t h _ c o n s u m e r _ k e y ' : C O N S U M E R _ K E Y , ' o a u t h _ t o k e n ' : a c c e s s _ t o k e n . k e y , ' o a u t h _ s i g n a t u r e _ m e t h o d ' : ' H M A C S H A 1 ' , ' o a u t h _ t i m e s t a m p ' : s t r ( i n t ( t i m e . t i m e ( ) ) ) , ' o a u t h _ n o n c e ' : a c c e s s _ t o k e n . _ g e n e r a t e _ n o n c e ( ) , ' o a u t h _ v e r s i o n ' : ' 1 . 0 ' , } o a u t h _ r e q u e s t = O A u t h R e q u e s t . f r o m _ t o k e n _ a n d _ c a l l b a c k ( a c c e s s _ t o k e n , h t t p _ u r l = S T R E A M _ U R L , p a r a m e t e r s = p a r a m e t e r s ) s i g n a t u r e _ m e t h o d = O A u t h S i g n a t u r e M e t h o d _ H M A C _ S H A 1 ( ) s i g n a t u r e = s i g n a t u r e _ m e t h o d . b u i l d _ s i g n a t u r e ( o a u t h _ r e q u e s t , c o n s u m e r , a c c e s s _ t o k e n ) p a r a m e t e r s [ ' o a u t h _ s i g n a t u r e ' ] = s i g n a t u r e d a t a = u r l l i b . u r l e n c o d e ( p a r a m e t e r s ) r e t u r n " % s ? % s " % ( S T R E A M _ U R L , d a t a ) # R u n T a l k i n g T w i t t e r C l i e n t c l i e n t = T a l k i n g T w i t t e r S t r e a m C l i e n t ( g e t T w i t t e r U s e r S t r e a m U R L ( ) ) # s o m e u s e f u l d e b u g c o m m a n d s , c o m m e n t o u t r u n n i n g t h e c l i e n t a n d u n c o m m e n t t h e c o m m a n d # g e t t w i t t e r s t r e a m u r l , i n c l u d i n g o a u t h s i g n a t u r e # p r i n t g e t T w i t t e r U s e r S t r e a m U R L ( ) # d o w n l o a d a s p e e c h f i l e f r o m g o o g l e # d o w n l o a d S p e e c h F r o m T e x t ( " h e l l o , h o w a r e y o u t o d a y " , " . / d o w n l o a d e d F i l e . m p 3 " ) # o u t p u t p h r a s e t o a u d i o # s p e a k S p e e c h F r o m T e x t ( " h e l l o , h o w a r e y o u t o d a y " ) # s t a r t t a l k i n g t w i t t e r c l i e n t

TweetingWebcamPics(PartTested)
http://www.makeuseof.com/tag/howtobuildaraspberrypitwitterbot/

Nowletsmakesomethingreallyusefulweregoingtweetwebcampics.Thankfully,Twythonsupports theAPIfunctionupdate_status_with_media,whichmakesthingsrathersimple. PlugaUSBwebcamintoyourdeviceandcheckif itsbeenrecognisedwiththecommand:


sudols/dev/video* #!/usr/bin/envpython importsys fromtwythonimportTwython importos importpygame importpygame.camera frompygame.localsimport* pygame.init() pygame.camera.init() cam=pygame.camera.Camera("/dev/video0",(640,480)) cam.start() image=cam.get_image()

ifyouseevideo0,youreinluck.Iuseda Playstation3PSEyecamanditworkedjustfine withoutanyadditionallegwork. Werealsogoingtousethepygamelibrariesto

125

takeapicture Initialisethecamera,thencallusingcam(setupto use/dev/video0,setresto640x480) Inshort,youveinitialisedthewebcamata specificresolution(youmayneedtoadjustthisis itsareallyoldcam),snappedapicture,and saveditasajpg.Werejustgoingtooverwritethe samewebcam.jpgeachtimetheappisrun. Finally,adjusttheupdate_statuslinetoread:


photo=open('webcam.jpg','rb') api.update_status_with_media(media=photo, status='MyRPibetweetingimagesnow=>')

pygame.image.save(image,'webcam.jpg') CONSUMER_KEY='jmyBuGoaMKS05x85qFCNRw' CONSUMER_SECRET= 'U2Ay9nv0CxdopruNk4DR9aRDyhry98ML7mYMCStdaI' ACCESS_KEY= '354540970nMZVfXJqTbEP8ddj3jwRNs8UMXlZapZpbxiaLg0v' ACCESS_SECRET= 'L9MnMvXLROx76CT9NzjR7PFrtMcIb1U9venQwK1ygY' photo=open('webcam.jpg','rb') api= Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,A CCESS_SECRET) api.update_status_with_media(media=photo,status='MyRPibe tweetingimagesnow=>')

SimilartotheSillyTweeterexample,thisjususes theapitopostapicture.Completecodeforthis exampleishere.

ReadingTweetsfroma#Tag
http://fuenteabierta.teubi.co/2013/01/controllingraspberrypiviatwitter.html

CreatingaTweetBot
http://www.makeuseof.com/tag/howtobuildaraspberrypitwitterbot/

126

SOFTWAREGAMES

123

AgoodlistofGamesthatrunonthePi
http://www.raspberryconnect.com/raspbianpackageslist/item/65raspbiangames

SDLDispManx
Thiswillgiveyoubestemulationandgraphicsblittingaround,itsnotastandardversionofSDL,butis enhanced,workswithQ3,DGenandSNES(notsureaboutemulationstationthough!) GrabcopyoftheGitHub
gitclonegit://github.com/vanfanel/SDL12kmsdispmanx.git cdSDL<tab> ./autogen.sh

runtheMAC_ConfigureDISPMANX.shscript
sudo./MAC_ConfigureDISPMANX.sh

EdittheMakefile
sudonanoMakefile

andaddtoCFLAGS)
I/opt/vc/include/interface/vmcs_host/linux

FinallyMakeandInstall.
sudomake sudomakeinstall

(Justreinstalldefaultlibsdl1.2andeverythingshouldbebacktonormal)
sudoaptgetinstallreinstalllibsdl1.2debian

127

Q3ArenaonRASPPI(Build)
Compileaway(thiswilltakeoveranhour!) http://www.raspbian.org/RaspbianQuake3 1. Make sure you're up-to-date: 2. sudoaptgetupdate
sudoaptgetdistupgrade Reboot.

3. Install required packages:


sudoaptgetinstallgitgccbuildessentiallibsdl1.2dev

4. Download the Quake 3 source code: 5. mkdir~/src


cd~/src gitclonehttps://github.com/raspberrypi/quake3.git cdquake3

6. Edit build.sh in quake3 directory: 7. changeline8tothis:ARM_LIBS=/opt/vc/lib


changeline16tothis:INCLUDES="I/opt/vc/includeI/opt/vc/include/interface/vcos/pthreads" commentoutline19:#CROSS_COMPILE=bcm2708

8. Do a ./build.sh 9. 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 in
build/releaselinuxarm/baseq3: pak0.pk3,pak1.pk3,pak2.pk3,pak3.pk3,pak4.pk3,pak5.pk3,pak6.pk3,pak7.pk3,pak8.pk3

i. Update your permissions for directFB access: ii. sudousermodaGvideo[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 by
this thread on RasPi Forum. Copythecontentsof /home/src/quake3/build/releaselinuxarm/ to /home/pi/quake3

12. Run ./ioquake3.arm. Shoot things.


Assumingyou'restillroot,startthegamewith`./ioquake3.arm`.Startagame,runaroundseehowitfeels.Hopefully itallworks,anditcreatedthecorrectdirectoriesforyou.Navigateto`/root/.q3a/baseq3`andrun Startthegameagain,andtheautoexec.cfgshouldexecuteautomatically.Ifyou'dliketotrytheotherconfigs,drop downtheconsolewiththetildekey`~andtype`execlow.cfg`oranyoftheothers.

128

Quake3QuickInstallSchoolBuild
(estimatedinstalltimearound5minutes!) ensurehaveaptgetupdate&&aptgetupgradeandupgradedfirmware??? cd~ wgethttp://www.raspians.com/uploads/quake3.zip unzipquake3.zip rmquake3.zip cdquake3 #ThiswillnotworkatschoolasDROPBOXisblocked!!!GRRR....AMAZINGUSBAGAIN! wgethttp://dl.dropbox.com/u/1816557/Q3%20Demo%20Paks.zip unzipQ3\Demo\Paks.zip rmQ3\Demo\Paks.zip cd~ sudochmod+x/home/pi/quake3/ioquake3.arm

SchoolBuildErrorsolutions
ifquake3bombsoutwithanerrormessagelike'SDL_Init()''Unabletoopenmouse'.Thiswilleffectother DirectFBapplications/gamesthatneedamouse. Workaroundeithertorunwithnomouse.
CODE:SELECTALL
e x p o r t S D L _ N O M O U S E = 1

ORfixthepermissionssononrootusescanaccess/dev/input/miceand/dev/input/mouse0asfollows. Createnewfilein"/etc/udev/rules.d/99input.rules" CODE:SELECTALL


# f i l e / e t c / u d e v / r u l e s . d / 9 9 i n p u t . r u l e s K E R N E L = = " m i c e " , N A M E = " i n p u t / % k " , M O D E = " 6 6 4 " , G R O U P = " i n p u t " K E R N E L = = " m o u s e * " , N A M E = " i n p u t / % k " , M O D E = " 6 6 4 " , G R O U P = " i n p u t "

Addanewgroupandaddyouruser(s)toit(myloginisjust'pi') CODE:SELECTALL
g r o u p a d d i n p u t u s e r m o d a G i n p u t p i R e s t a r t t h e s o u n d Update:Ifyouaregettingstatictrybringingdowntheconsole(tildebydefault)andentering

"snd_restart"(noquotes)andpressenter.Itwillreinitthesoundsubsystemandcanclearitupinmybuild.

Soundthroughheadphones
sudoamixercsetnumid=31

129

ShowFPSinGame
#ToshowFPSuse~onthemenuandtype cg_drawFPS"1"

Quake3ConfigFileGuide
http://www.gamesurge.com/pc/hardware/tweaks/q3atweak.shtml

FullversionofQuake3.
Yes,ifyoucopypak0.pk3fromyourcdtothebase3qdirectoryonthePi,youwillunlockthefullgameprovidingyou entertheCDkey.Multiplayerworksatreat!(around480MB).Ensurewhenyoucopythatyourename/overwritethe existingpak0.pak3file,youmightneedtorenametheoldone(forbackup)andmaketheotheronelowercaps!

OpenarenonthePi(NotviaPiStore) cd~ sudoaptgetinstallopenarena sudoaptgetinstalllibcurl3gnutls

Q3Models,Levels,MapsandExtras
http://ioquake3.org/extras/models/Models http://lvlworld.com/Levels http://www.quakeunity.comModPacks/Skins/Texturesetc. http://www.moddb.com/games/quakeiiiarenaQuake3Info.

130

Q3ConsoleManual
Console 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

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

Quake2onthePi.
NeedafreshinstallofWheezynotSqueeze //Getthelatestbuildhttp://deponie.yamagi.org/quake2/debs/source/(thetar.gz) Extractit. GogettheQuake2demo(UnziptheEXE,rescuethefollowingfilesandputontoUSB) ftp://ftp.idsoftware.com/idstuff/quake2/q2314demox86.exe Unzipthisfile(again,it'saselfextractingzipfile). Createanew"quake2/"directorywitha"baseq2/"subdirectoryandputthe"pak0.pak"andthe "players/"subdirectory,youcanfindthemwithintheunzippedfiles(inInstall/Data/baseq2/),inyour "baseq2/"directory.No patchingisneededforthedemo,infactitwouldbreakit. Installthefollowingusingaptgetinstall... libsdl1.2dev libvorbisdev liboggdev zlib1gdev libjpeg8dev MAKEGototheGITHUB,findtheupdatedversion,savetheRAWoverthetop https://github.com/reefab/yquake2 yq2.cfgGotohttps://github.com/reefab/yquake2thenstuff,againsavetheRAWinthebase2qfolder readyforlater.

133

InstallingQuake2onPi
Quake 2 https://github.com/reefab/yquake2/blob/a07e3a605a9f1765b5950da5271df33653245c 6b/README.md MustrunQuake2asRoot. cd/home/pi/quake2 ./quake2 Quake2FIX??? sudolnfs/opt/vc/lib/libEGL.so/usr/lib/libEGL.so sudo ln -fs /opt/vc/lib/libEGL.so /usr/lib/libEGL.so.1 sudo ln -fs /opt/vc/lib/libEGL_static.a /usr/lib/libEGL_static.a sudolnfs/opt/vc/lib/libGLESv2.so/usr/lib/libGLESv2.so sudo ln -fs /opt/vc/lib/libGLESv2.so /usr/lib/libGLESv2.so.2 sudolnfs/opt/vc/lib/libGLESv2_static.a/usr/lib/libGLESv2_static.a sudolnfs/opt/vc/lib/libbcm_host.so/usr/lib/libbcm_host.so sudolnfs/opt/vc/lib/libvchiq_arm.a/usr/lib/libvchiq_arm.a sudolnfs/opt/vc/lib/libvchiq_arm.so/usr/lib/libvchiq_arm.so sudolnfs/opt/vc/lib/libvcos.a/usr/lib/libvcos.a sudolnfs/opt/vc/lib/libvcos.so/usr/lib/libvcos.so OFTENUSEapt-get update && apt-get dist-upgrade apt-get install ntpdate ntpdate uk.pool.ntp.org arm128_start.elf:128MARM,128MGPUsplit arm192_start.elf:192MARM,64MGPUsplit arm224_start.elf:224MARM,32MGPUsplit

134

InstallingDOOM1/2
Firstoff,weneedtoprepareafolderforthesourcecode.IhaveafoldercalledSourcesinmyhome directorywhereIdirectallmysourcecodeandcompilingrelatedneeds.So,let'sstartbycreatingone:
c d ~ m k d i r S o u r c e s c d S o u r c e s

Next,wewilldownloadthe.tar.gzarchivefromSourceForgeeitherwithMidoriorNetSurfordownloadit onyourcomputeranduseSSHtotransferittotheSourcesfolder:
sudowget http://downloads.sourceforge.net/project/chocolatedoom/chocolatedoom/1.7.0/chocolatedoom1.7.0. tar.gz

Thenunpackit,deletethearchiveandnavigateintothenewfolder:
t a r x v f c h o c o l a t e d o o m 1 . 7 . 0 . t a r . g z r m c h o c o l a t e d o o m 1 . 7 . 0 . t a r . g z c d c h o c o l a t e d o o m 1 . 7 . 0

Beforewestartconfiguringandcompiling,weneedtodownloadaprettyhugelistofpackages,theyare mainlySDLrelatedsotheyshouldbeusefultoyouonyournextcompilingadventures.
s u d o a p t g e t u p d a t e s u d o a p t g e t i n s t a l l g c c b u i l d e s s e n t i a l l i b s d l 1 . 2 d e v l i b s d l 1 . 2 d e b i a n l i b s d l i m a g e 1 . 2 l i b s d l i m a g e 1 . 2 d e v l i b s d l m i x e r 1 . 2 l i b s d l m i x e r 1 . 2 d e v l i b s d l n e t 1 . 2 l i b s d l n e t 1 . 2 d e v t i m i d i t y

Wheneverythingisinstalled,wecanfinallyruntheconfigurationscript ./configure (NOTE:Ifthisgivesyouanerror,itismostlikelyduetoapartofyourcompilingmasqueradeismissing. Trygooglingtheerrorandyouwillmostlikelyfindwhatyouneedtoaptgetinordertofixit.) Finally,wecanstartcompiling.ThiswilltakesometimebutnotnearlyaslongasQ3A. make Aftercompilingfinishes,wewillinstallournewbinarieswiththefollowningcommand: sudomakeinstall NOTE:Youneedtorunthisusingsudoorasroot,becausetheinstallingscriptcopiesbinaries,iconsand .desktopfilestothe/usr/sharefolder.Onthebrightside,thismeansthateverythinggetsneatly embeddedinyourLXDEmenu.Duetothewaychocolatedoomislaunchedthisisabitunneeded,but wewilltalkaboutthatlater(atleastwehavetheicon). ToconfigureChocolateDoom,youneedtorunthefollowingcommandfromtheterminal: chocolatesetup ThiswillbringyouupaniceDOSlookingwindowwhereyoucanconfigureournewsoftware.Under displayconfiguration,youcaneitherchoosethefullscreen,butifyouhaveaFullHDLCDlikeme,I reccomendhittingA,disabling"Fixaspectratio"andthenselecting1280x800,sinceittendstobequite laggyonfull1920x1080.Hittheescapekeytoreturntotheoriginalmenu.Sincethereisnojoysticktobe configured,wewillheadrighttothekeyboardconfiguration.Ifyouwantcontrolssimilartomoremodern FPSgames,setMoveForwardtoW,MoveBackwardtoS,StrafeLefttoA,StrafeRighttoDandyou cansetTurnLefttoQandTurnRighttoEorwhateveryoulikeandleaveSpeedOnonShiftandStrafe OnonAlt.PressescapetoreturnandyoucanskiptheMouseconfiguration,sinceeverythingthereisset bydefaulttothe"average"levels.Youcanfiddlearoundthereyourselflater.GotoSoundconfiguration andmakesureSoundEffectsissettoDigitalandthatMusicplaybackissettoNativeMIDI.Onceyou checkedthat,returntothemainmenuandselectSaveparametersandlaunchDOOM.Now,sincethere arenoWADfilesyet,thegamewillnotlauchbutthesettingswillbesaved. 135

Now,weneedtogettheWADfiles.Alittlegooglesearchwilltellyouhowto*cough**cough*extract thesefilesfromyouroriginalDoomCD.Alternatively,youcanuseDoom2,UltimateDoom,TNT:Eviluion orPlutonia.LogintoyourRaspberryPithroughSSHasroot(forexampleusingWinSCP)andmake createafoldercalleddoomin/usr/shareandputyourdoom.wad,doom2.wad,tnt.wadorplutonia.wad.I havetriedStrifeandHexenaswell,butforsomestrangereasontheydon'tworkforme. Thenyoucanfinallystartthegameusingtheterminalwiththefollowingcommand: chocolatedoomiwad/usr/share/(nameofyourfile).wad Congratulations!YouhavenowgotDoomrunningonyourRaspberryPi.

OPTIONAL:CreateaWADspecificlauncher
(soyoudon'thavetousetheterminalallthetime) OpenupLeafPadandtypethefollowingtextin:
[ D e s k t o p E n t r y ] N a m e = D o o m 1 E x e c = c h o c o l a t e d o o m i w a d / u s r / s h a r e / d o o m / d o o m . w a d I c o n = c h o c o l a t e d o o m T y p e = A p p l i c a t i o n C o m m e n t = C o n s e r v a t i v e D o o m s o u r c e p o r t . L o a d e d w i t h a D o o m 1 W A D . C a t e g o r i e s = G a m e A c t i o n G a m e

Andsaveitonyourdesktopasdoom1.desktop.Theexactnamedoesn'treallymatter,sincethename specifiedinsidethefileistheonegettingdisplayed.Bang,yougotyoureasydesktoplauncherforDoom. Canyouevenaskformore?Well...Ofcourseyoucan.Letmeintroduceyoutothe:

OPTIONAL2:CreatealaucherformultiplekindsofDoom
So,let'ssayyouhappentoownbothDoom1,Doom2,andontopofityoualsoownTNTandPlutonia. Andyoudon'twanttohavefourdifferenticons.Thenletuscreatealauncherwithalltheseoptions!Using alittleinspirationfromtheeverpopularPythonGames,wewillmakeourselvesanicelittlemenuusing Zenity.OpenupLeafPad,or,ifyouhaveit,Geanyandpastethefollowingscriptthere:
# ! / b i n / s h R E T = 0 G A M E = $ ( z e n i t y l i s t w i d t h = 3 5 0 h e i g h t = 2 5 0 r a d i o l i s t t i t l e = " C h o o s e y o u r g a m e " c o l u m n " S e l e c t " c o l u m n = " G a m e " T R U E " D o o m 1 / U l t i m a t e D o o m " F A L S E " D o o m 2 " F A L S E " T N T : E v i l u t i o n " F A L S E " T h e P l u t o n i a E x p e r i m e n t " ) R E T = $ ? e c h o $ G A M E i f [ " $ G A M E " = " D o o m 1 / U l t i m a t e D o o m " ] t h e n c h o c o l a t e d o o m i w a d / u s r / s h a r e / d o o m / d o o m . w a d e l i f [ " $ G A M E " = " D o o m 2 " ] t h e n c h o c o l a t e d o o m i w a d / u s r / s h a r e / d o o m / d o o m 2 . w a d e l i f [ " $ G A M E " = " T N T : E v i l u t i o n " ] t h e n c h o c o l a t e d o o m i w a d / u s r / s h a r e / d o o m / t n t . w a d e l i f [ " $ G A M E " = " T h e P l u t o n i a E x p e r i m e n t " ] t h e n c h o c o l a t e d o o m i w a d / u s r / s h a r e / d o o m / p l u t o n i a . w a d e l s e e c h o " C a n c e l l e d . . . " f i

Andsaveitsomewherenice,likeyourhomefolder,underthenamechocolatedoomlauncher(without theextension).Openupterminal,navigatetothefileyoujustsavedandissuethesetwocommands:
c h m o d + x c h o c o l a t e d o o m l a u n c h e r

136

s u d o c p c h o c o l a t e d o o m l a u n c h e r / u s r / b i n

Fromnowon,youhaveanewterminalcommandthatbringsupanicelittlelauncherforallyourDoom relatedbusiness.Nowlet'sturnitintoaprettylittleicon,shallwe?Forthelasttime,openLeafPador Geanyandcreateanewfileandpastethisintoit:


[ D e s k t o p E n t r y ] N a m e = C h o c o l a t e D o o m L a u n c h e r E x e c = c h o c o l a t e d o o m l a u n c h e r I c o n = c h o c o l a t e d o o m T y p e = A p p l i c a t i o n C o m m e n t = O n e l a u n c h e r f o r a l l D o o m r e a l t e d g a m e s . C a t e g o r i e s = G a m e

Andsaveitonyourdesktopaschocolatedoomlauncher.desktop.Ifyouwantthislaunchertoappearin yourmenuaswell,openupterminalforthelasttimeandtypeinthesetwocommands:
c d ~ / D e s k t o p s u d o c p c h o c o l a t e d o o m l a u n c h e r . d e s k t o p / u s r / s h a r e / a p p l i c a t i o n s

Andthat'sit.Younowhaveafullyworking,configuredinstallationofChocolateDoom1.7.0withworking MIDIsoundthruTimidity,withalauncherfordifferentgamesbothonyourdesktopandinyour applicationsmenu.Timetogiveyourselfapatontheback,andgoplaysomeDoom! Enjoy!

InstallingAliensTCandAliensDoom3.0(AVP)inChocolateDoom.
DownloadtheappropriatefilesAliensTC http://www.doomworld.com/idgames/index.php?id=5739 DownloadtheappropriatefilesforAliensDoom3 http://www.doomworld.com/idgames/index.php?id=5254 ExtractintheWADsfolder. RunAlienstTCusing
chocolatedoomiwad<path>/DOOM.WADdeh<path>/atcud19.dehmerge<path>/alitcsf.wadfile<path>/alitcsnd.wad <path>/alitcwad.wad

RunAlensDoom3using
chocolatedoomiwad<path>/DOOM.WADdeh<path>/ad3.dehmerge<path>/ad3spfl.wad<path>/ad3gfx.wad <path>/ad3snd.wad<path>/ad3mus.wad<path>/ad3lev.wad

Dontforgetthesecanbeaddedtothecustomdoomlauncher.(chocolatedoomlauncher)seeabove, setthepermissionsagain,andcopytotheusr/share/applications

InstructionsforLANplay
ToplayChocolateDoomonalocalareanetworkisstraightforward.StartaserverinthesamewayasforInternet play:
chocolatedoomserverdeathmatch

Otherplayerscanthenautomaticallyjointheserverwiththeautojoincommandlineoption:
chocolatedoomautojoin

137

InstallingMinecraftonthePi.
GrabtheTargaBall. w g e t https://s3.amazonaws.com/assets.minecraft.net/pi/minecraftpi0.1.1.tar.gz Todecompressit:tarzxvfminecraftpi0.1.1.tar.gz Torunit:cdmcpi Followedbyminecraftpi

CustomTexturesPacks
Thesedowork.TryDokuCraft,LegopakorSphax (toinstallthesebackupthe ~/mcpi/data/imagesfolder,thenoverwriteitwiththetexturepack.Thiswilloverwrite,butshouldwork. BestdoneinXasyoucanreallyseewhatyouredoing!

PythonScriptsforMinecraft.
EasiestwayistoclonethescriptsGitHub(seeGitHubsworthcloning!)
mkdir/home/pi/mcpi/PythonScripts sudogitclonehttps://github.com/brooksc/mcpipy.git cdmcpipy sudomv*.py/home/pi/mcpi/PythonScripts

Thesecanthenberunfromaseperatecommandprompt!(justrunthenasplainpythonscripts,e.g. sudopython~/mcpi/PythonScripts/maze.py Fortheclocksetcyouhavetokeepthescriptrunningforittoupdate!

Rendering3DModelsintheMinecraftWorld
Fromhttp://www.stuffaboutcode.com/ Downloadandrun Youcandownloadthecodedirectfromgithub,sorunminecraft,open/createaworldandfollowthe instructions:
sudoaptgetinstallgitcore cd~ gitclonehttps://github.com/martinohanlon/minecraftrenderObj.git cdminecraftrenderObj pythonminecraftrenderObj.py

BydefaulttherenderObj(v1)scriptwillrenderthemanhattenskyline. v2willrendertheRaspberryPi,V2worksbetter.Tochangewhatisrenderedyoullhavetogetyour handsdirty! 138

Lotsofmodelsavailablefromhere http://people.sc.fsu.edu/~jburkardt/data/obj/obj.html

MakingtheOBJFiles.
Insketchupgetyourmodelsorted(orimportone!) Ensureyouhavetherightplugininstalledinthepluginsfolder Instructionsfromhere.
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 Model Edit the renderObj.py files your addition should look something like this...

#Cthulhu COORDSSCALE=2 STARTCOORD=minecraft.Vec3(75,25,60) CLEARAREA1=minecraft.Vec3(30,15,30) CLEARAREA2=minecraft.Vec3(100,65,90) BLOCKTYPE=block.WOOD_PLANKS SWAPYZ=False vertices,textures,normals,faces=load_obj("cthulhu.obj")

Viewing3DMeshesonaPi.
TryingoutvariousoptionssuchasPyObjViewerDoesntworkwell.
wgethttp://jestermon.weebly.com/uploads/1/6/2/1/1621282/pyobjviewer.zip

Meshlab?

139

ListofMinecraftBlocks
http://raspberrypython.blogspot.co.uk/2013/02/minecraftpieditionavailable.html
AIR STONE GRASS DIRT COBBLESTONE WOOD_PLANKS SAPLING BEDROCK WATER_FLOWING WATER WATER_STATIONARY LAVA_FLOWING LAVA LAVA_STATIONARY SAND GRAVEL GOLD_ORE IRON_ORE COAL_ORE WOOD LEAVES GLASS LAPIS_LAZULI_ORE LAPIS_LAZULI_BLOCK SANDSTONE BED COBWEB GRASS_TALL WOOL FLOWER_YELLOW FLOWER_CYAN MUSHROOM_BROWN MUSHROOM_RED GOLD_BLOCK IRON_BLOCK STONE_SLAB_DOUBLE =Block(0) =Block(1) =Block(2) =Block(3) =Block(4) =Block(5) =Block(6) =Block(7) =Block(8) =WATER_FLOWING =Block(9) =Block(10) =LAVA_FLOWING =Block(11) =Block(12) =Block(13) =Block(14) =Block(15) =Block(16) =Block(17) =Block(18) =Block(20) =Block(21) =Block(22) =Block(24) =Block(26) =Block(30) =Block(31) =Block(35) =Block(37) =Block(38) =Block(39) =Block(40) =Block(41) =Block(42) =Block(43) STONE_SLAB BRICK_BLOCK TNT BOOKSHELF MOSS_STONE OBSIDIAN TORCH FIRE STAIRS_WOOD CHEST DIAMOND_ORE DIAMOND_BLOCK FARMLAND FURNACE_INACTIVE FURNACE_ACTIVE DOOR_WOOD LADDER STAIRS_COBBLESTONE DOOR_IRON REDSTONE_ORE SNOW ICE SNOW_BLOCK CACTUS CLAY SUGAR_CANE FENCE GLOWSTONE_BLOCK BEDROCK_INVISIBLE STONE_BRICK GLASS_PANE MELON FENCE_GATE GLOWING_OBSIDIAN NETHER_REACTOR_CORE CRAFTING_TABLE =Block(44) =Block(45) =Block(46) =Block(47) =Block(48) =Block(49) =Block(50) =Block(51) =Block(53) =Block(54) =Block(56) =Block(57) =Block(60) =Block(61) =Block(62) =Block(64) =Block(65) =Block(67) =Block(71) =Block(73) =Block(78) =Block(79) =Block(80) =Block(81) =Block(82) =Block(83) =Block(85) =Block(89) =Block(95) =Block(98) =Block(102) =Block(103) =Block(107) =Block(246) =Block(247 =Block(58)

140

MinecraftTwitter(untested)
http://www.stuffaboutcode.com/2013/08/raspberrypiminecrafttwitter.html?m=1

Install Createatwitterapp Youneedtocreateatwitterappusingyourtwitterid,youcandothisbyvisitingdev.twitter.com,signing on,andclickingcreateappifyouarehavingproblemsseeapreviousblogpostofmine,automatically postingupdatestotwitter,whichhassomeindepthinstructions. Installpythonoauth&pycurl Weneedacoupleofpythonmodulestogetthetwitterfeedworking.Ifyouhaveneverinstalledpython modulesbeforeyouaregoingtoneedtoinstallthepythonsetuptoolsmodule,distribute,seeblogpost, pythoninstallingmodules,forinfoonhowtodothis. sudoaptgetinstallgitcore gitclonehttps://github.com/leah/pythonoauth.git cdpythonoauth sudopythonsetup.pyinstall sudoaptgetinstallpythonpycurl Downloadcode cd~ gitclonehttps://github.com/martinohanlon/minecrafttwitter.git cdminecrafttwitter Updatetwitterkeys Youwillneedtogetthetwitterkeysyouweregivenwhenyoucreatedyourtwitterappandputtheminto minecrafttwitter.py.Openminecrafttwitter.pyandscrolldowntillyoufind: #twitteroauthkeys,getyoursfromdev.twitter.com CONSUMER_KEY='#############' CONSUMER_SECRET='###############' ACCESS_TOKEN='############### ACCESS_TOKEN_SECRET='###############' Andreplacethehasheswithyouraccesskeys. Run Startupminecraft pythonminecrafttwitter.py Code Itsabithacky(asyoumightexpectfromahackweekend),butI'veincludeitforreferencebelow.Ifyou wanttogetitrunningthoughIwouldsuggestyoudownloaditfromgithubusingtheinstructionsabove. 141

#www.stuffaboutcode.com #RaspberryPi,MinecraftTwitter #importtheminecraft.pymodulefromtheminecraftdirectory importminecraft.minecraftasminecraft #importminecraftblockmodule importminecraft.blockasblock #importtime,sodelayscanbeused importtime #importoauthfortwittersecurity fromoauth.oauthimportOAuthRequest,OAuthSignatureMethod_HMAC_SHA1 fromhashlibimportmd5 #requiredbytwitterstreamclass importjson,random,math,urllib,urllib2,pycurl #Lettersusedintheprogram,hashesareturnedintoblocks letters={"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

"###"+"\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

"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

"###"+"\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

""+"\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" } #twitteroauthkeys,getyoursfromdev.twitter.com CONSUMER_KEY='#############' CONSUMER_SECRET='###############' ACCESS_TOKEN='############### ACCESS_TOKEN_SECRET='###############' #constantstopositionthetextlinesinminecraft LETTERBLOCKID=block.COBBLESTONE.id LETTERBLOCKDATA=0 #Thesearethelineswherethetweetswillbewritten TEXTLINES={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

} LINEHEIGHT=5 LETTERWIDTH=3 #Classforcreatingtextinminecraft classMinecraftText: def__init__(self,mc): self.mc=mc self.currentLine=0 self.currentTopLeft=LINETOPLEFTS[self.currentLine] #writesalinetominecraftatthenextposition defwriteNextLine(self,line): #Outputmessage self.clearLine(self.currentLine) self.writeLineToMC(line,self.currentLine) self.currentLine+=1 #ifIhavereachedthetopline,resetit ifself.currentLine==4:self.currentLine=0 #writesalineoftextintominecraft defwriteLineToMC(self,line,lineNumber): #getthetextlines textlines=TEXTLINES[lineNumber] #currenttestline currentTextLine=0 #setthecursorposition currentCursor=minecraft.Vec3(textlines[currentTextLine][0].x, textlines[currentTextLine][0].y, textlines[currentTextLine][0].z) #setupxandzdirections xDirection,zDirection=1,0 nextTextLine=False #makelinelowercase line=line.lower() #writethelinetominecraft forcharacterinline: #createthecharacterinminecraft self.writeLetterToMC(character,currentCursor,xDirection,zDirection) #movethe'cursor'on #checkifthecurrentcursorposisoutsidethetextLine, #ifsomovetothenexttextline ifcurrentTextLine==0: currentCursor.x=currentCursor.x+LETTERWIDTH+1 ifcurrentCursor.x>textlines[currentTextLine][1].x:nextTextLine=True ifcurrentTextLine==1: currentCursor.z=currentCursor.z+LETTERWIDTH+14 ifcurrentCursor.z>textlines[currentTextLine][1].z: nextTextLine=True ifcurrentTextLine==2: currentCursor.x=currentCursor.xLETTERWIDTH+14 ifcurrentCursor.x<textlines[currentTextLine][1].x:nextTextLine=True ifcurrentTextLine==3: currentCursor.z=currentCursor.zLETTERWIDTH+14 #ifcurrentCursor.z<textlines[currentTextLine][1].z:nextTextLine=True ifnextTextLine==True: nextTextLine=False #nexttestline currentTextLine+=1 #setthecursorposition currentCursor=minecraft.Vec3(textlines[currentTextLine][0].x, textlines[currentTextLine][0].y, textlines[currentTextLine][0].z)

147

#setupxandzdiections ifcurrentTextLine==1:xDirection,zDirection=0,1 ifcurrentTextLine==2:xDirection,zDirection=1,0 ifcurrentTextLine==3:xDirection,zDirection=0,1 #createaletterinminecraft defwriteLetterToMC(self,character,cursorTopLeft,xDirection,zDirection): #thecurrentpositioniswherewehavereachedincreatingtheletter currentPos=minecraft.Vec3(cursorTopLeft.x,cursorTopLeft.y,cursorTopLeft.z) #isthecharacterinmyletterlist? if(characterinletters.keys()): #getthehashesforthecharacter letterString=letters[character] #loopthroughallthehashes,creatingblock fordigitinletterString: ifdigit=="#": #print"createblockx="+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 ifdigit=="": self.mc.setBlock(currentPos.x,currentPos.y,currentPos.z,block.AIR.id) currentPos.x=currentPos.x+xDirection currentPos.z=currentPos.z+zDirection ifdigit=="\n": currentPos.y=currentPos.y1 currentPos.x=cursorTopLeft.x currentPos.z=cursorTopLeft.z

#clearsalineoftextinminecraft
defclearLine(self,lineNumber): fortextlineinTEXTLINES[lineNumber]: self.mc.setBlocks(textline[0].x, textline[0].y, textline[0].z, textline[1].x, textline[1].yLINEHEIGHT, textline[1].z, block.AIR.id) #classformanagingoauthtokens classToken(object): def__init__(self,key,secret): self.key=key self.secret=secret def_generate_nonce(self): random_number=''.join(str(random.randint(0,9))foriinrange(40)) m=md5(str(time.time())+str(random_number)) returnm.hexdigest() #twitterclient classMinecraftTwitterStreamClient: def__init__(self,streamURL): #Connecttominecraftbycreatingtheminecraftobject #minecraftneedstoberunningandinagame self.mc=minecraft.Minecraft.create() #Postamessagetotheminecraftchatwindow self.mc.postToChat("Minecrafttwitterstreamactive") #createmyminecrafttextscreenobject self.mcText=MinecraftText(self.mc)

148

#setupconnectiontotwitterstream 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() #thismethodiscalledeachtimesomedataarrivesonthestream defon_receive(self,data): #debugtoseewhenthisiscalledsys.stdout.write(".") self.buffer+=data ifdata.endswith("\n")andself.buffer.strip(): content=json.loads(self.buffer) self.buffer="" #debugoutputjsonfrombufferprintcontent #friendsdatastoreforlater if"friends"incontent: self.friends=content["friends"] #text(tweet)arrives if"text"incontent: printu"{0[user][name]}:{0[text]}".format(content).encode('utf8') tweet=u"{0[user][name]}:{0[text]}".format(content).encode('utf8') self.mcText.writeNextLine(tweet)

#gettheurlneededtoopenthetwitteruserstream,includingsignatureafterauthentication defgetTwitterUserStreamURL(): 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':'HMACSHA1', '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__": #Createminecrafttwitter mcTwitter=MinecraftTwitterStreamClient(getTwitterUserStreamURL())

149

InstallingDescentonthePi(untested)
http://blog.sheasilverman.com/2012/08/descenttutorial/

1.

2. 3. 4. 5.

6.

7.

8.

9. 10.

11.

12.

13.

14. 15. 16. 17.

Installtherequireddependancies 1. sudoaptgetinstalllibsdl1.2debianlibsdlmixer1.2libsdlmixer1.2devlibsdlimage1.2 libsdlimage1.2devlibsdlttf2.00libsdlttf2.0devlibsdlnet1.2libsdlnet1.2devgcc4.7 sconslibphysfsdev cd~/ mkdirdescent cddescent Downloadtheneededsourcecode: 1. wget http://sourceforge.net/projects/dxxrebirth/files/dxxrebirth/0.57.3/d1xrebirth_v0.57.3src. tar.gz 2. wget http://sourceforge.net/projects/dxxrebirth/files/dxxrebirth/0.57.3/d2xrebirth_v0.57.3src. tar.gz Downloadtheneededpatches: 1. wgethttp://wwwuser.tuchemnitz.de/~heinm/tmp/d1xrebirthrpi.diff.gz 2. wgethttp://wwwuser.tuchemnitz.de/~heinm/tmp/d2xrebirthrpi.diff.gz Unzipthesourcefilesandthepatches: 1. tarxvfzd2xrebirth_v0.57.3src.tar.gz 2. tarxvfzd1xrebirth_v0.57.3src.tar.gz 3. gunzipd1xrebirthrpi.diff.gz 4. gunzipd2xrebirthrpi.diff.gz Younowhavetopatchthesourcecodewiththedifffiles. 1. cdintothesourcecodedirectories. 1. Descent1 1. cd~/descent/d1xrebirth_v0.57.3src/ 2. patchp1<../d1xrebirthrpi.diff 2. Descent2 1. cd~/descent/d2xrebirth_v0.57.3src/ 2. patchp1<../d2xrebirthrpi.diff Wearenowreadytocompile! Onthecommandlineenterthesetwocommands: 1. exportCC=gcc4.7 2. exportCXX=g++4.7 Descent1 1. cd~/descent/d1xrebirth_v0.57.3src/ 2. sconsraspberrypi=1 1. Waitaround3040minutes. 2. Iftherearenoerrorsyoushouldnowhavead1xrebirthexecutablefilein yourdirectory! Descent2 1. cd~/descent/d2xrebirth_v0.57.3src/ 2. sconsraspberrypi=1 1. Waitaround3040minutes. 2. Iftherearenoerrorsyoushouldnowhavead2xrebirthexecutablefilein yourdirectory! Younowneedthedatafilesthatholdstheactualgamelevels,sounds,artwork,etc.Thesearein .hog,.pig,and.ham(descent2only)files.Youcangetthegamecontentfromdxxrebirth,the creatorsofthisport.Theyalsohavelinkstothesharewarefiles: 1. http://www.dxxrebirth.com/gamecontent/ 2. http://www.dxxrebirth.com/download/dxx/content/descentpcshareware.zip 3. http://www.dxxrebirth.com/download/dxx/content/descent2pcdemo.zip Unzipthosefilesbyrunningunzipfilename copydescent.hoganddescent.pigto~/descent/d1xrebirth_v0.57.3src/ copyD2DEMO.HAM,D2DEMO.HOGandD2DEMO.PIGto~/descent/d2xrebirth_v0.57.3src/ Youarenowreadytoplay! 1. Descent1 1. cd~/descent/d1xrebirth_v0.57.3src/

150

2. 2. Descent2 1. 2. 18. ENJOY!!

./d1xrebirthhogdir.(yes,thatsaperiodattheendthatmustbethere) cd~/descent/d2xrebirth_v0.57.3src/ ./d2xrebirthhogdir.

Irealizethesearealotofinstructions,butIwantedtomakethemasverboseaspossible. Belowaretheprecompiledbinarieswithsharewaredatafilesalreadycopiedover. Descent1Binaries|Descent2Binaries

151

SOFTWAREGamesEmulation 148
ANoteaboutROMS
HeresaquicknoteaboutROMs.ROMsarevirtualdiskimages(Generallyofoldconsole/computer games).NowmanyoldcompaniesmightarguethatROMsarentlegal.Espeicallyifyoudontownthe originalofthegame!Yetforsomeitmakesperfectssense,havingacopyofagametheyboughtyears agotoplayonnewhardware.WhenSonic2wasfirstreleaseditcost45(thatsaround65with inflation)!!!whichisbonkersexpensive.Howevergreedycompanieslovechurningoutgamescollections formodernconsolesandcharginghansomelyforthem,probablymanyoftheemulatorsontheconsoles willbeusingotherpeoplesworkandbenefittingfromit.(N.B.Youllnoticeyoucantgetadecent emulatoronaniPhone/iPad/iPodduetotheclosedarchitectureandnatureoftheappstore,unlessyou jailbreak,sadreally!) SoisitlegaltodownloadGensis(Megadrive),SNESorNESromsfromsiteslikeCoolroms, emuparadiseorRomination?No,butitsasomewhatgreyarea! Idalsoliketotakeanotherviewonthis,bearwithmeifyouwill.Whosarchivingandbackingupour illustriousgamesherritage?Thesegamesdefinedgenerationsandareetchedintoourhistory.But gamesarebeinglost...why?Becausenoonecares?Ornooneisabletoarchiveentirecollections? Copyrightrestrictions?TakealookonanymajortorrenttrackingsiteforConsoleXYZcollectionand youllfindEVERYgameeverreleasedonthatconsole(multipleversionsfrommultiplecountries), immortalisedforposterity!Thesegameshavebeenpainstakinglycollected,categorizedandbundledfor yourconvenience,designedtobeeasilyshared!Why,lestweforget. ShouldIencourageyoutogoandfindthesegames?Dunno.IwillperhapsdemonstrateSonic2running fromanoriginalcartridgeonaMegadrive2,IllthenshowthesamegamerunningonPithrough emulation!Thereareatonoflessonstobelearnthere,Filesizes,Compression,Emulation,Virtualisation etc.Iwillalsomentionsomenoteworthycharactersandsomeofmyotherfaves.WillIencouragekids togoandfindoutmoreaboutthesegames?Ofcourse!Perhapsitwillgetafewmoreparentsinvolved withaconversationoverthedinnertable.Currentcopyrightlawsarearchaicanddesperatelyneed updating!Manyofthesegameswillhaveslippedoutofcopyright,otherswillhavenot.Therewasatime whenSonicandMariowouldnotbeseendeadwitheachother.ImagineSonyandMicrosoftreleasinga gametogether,crazy.Buttimeschange. Handle,withcare,useatyourownrisk.Ifyoulikeit,buyit(thatisifyoucanevensourceanoriginal copy!)RANTOVER.

152

RetroPieEmcompassingMostEmulators.
Thiswilltakeawhiletobuildifyoucompileyourown!(youcouldjustuselatestBinaries,nottested!)
gitclonehttps://github.com/petrockblog/RetroPieSetup cdRetroPieSetup

run
sudoaptgetinstalldialogy sudo./retropie_setup.sh

ChooseSourceBasedInstallation,thiswilltakelonger,butwillgivebetterresults! Tosetupthesystem(whichemulatorsetc)editthefollowingfile.
sudonano~/.emulationstation/es_systems.cfg

Thencheckouttheconfigfilesforcontrols/detailsetc.
sudonano~/RetroPie/config/all/retroarch.cfg setaudio_out_rate=44100

Enusurethatiftryingtorunaplaystationemulatoryouneedtoeditthees_systems.cfgtoreadBINfile (both.binand.BINasimgseemsnottowork!)

RetroArchPhoenixorretroarchjoyconfig???
input_player1_a=x input_player1_b=z input_player1_y=a input_player1_x=s input_player1_start=enter input_player1_select=rshift input_player1_l=q input_player1_r=w input_player1_left=left input_player1_right=right input_player1_up=up input_player1_down=down

http://blog.petrockblock.com/retropiedownloads/
retroarchL/home/root/RetroPie/emulatorcores/GenesisPlusGX/libretro.so /home/root/RetroPie/roms/megadrive/SONIC_CMP.smd

RetroPieXBoxPad
(Guidefromhere) Followingthis,edit/etc/rc.local,adding(beforeanythingelse) 153

xboxdrvtriggerasbuttonid0led2deadzone4000silent&sleep1 Thisensuresthatthedriverlauncheswhenthecomputerboots.Notetheuseofwidintheinstruction, whichisforwirelesscontrollers.Changeittoidforwiredcontrollers. Followingthis,enter


cd~/RetroPie/emulators/RetroArch/tools

Whileinthisdirectory,inputthefollowingcommand:
./retroarchjoyconfigop1.cfgp1j0

Youshouldincreasedigitsbyfactorof1foreachadditionalcontroller.Ifenteredcorrectly,theresulting filesshouldbeaddedtoretroarch.cfg:
sudocatp*.cfg>>~/RetroPie/configs/all/retroarch.cfg

YoucanthensaveandreboottouseyourXbox360controller.

RetroPieExitGamesUsingYourControllers
ThedefaultmethodforexitingagameinEmulationStationisbyrestartingyourRaspberryPisomething thatcancorrupttheSDcardasthisisonlypossibleinthisscenariobyremovingthepowercable. Toovercomethis,aworkaroundexistsmapsanexitoptiontoyourgamecontroller. Youllneedtoedittheretroarch.cfgfiletodothis,addingthefollowingcode: input_enable_hotkey_btn="X" input_exit_emulator_btn="Y" Youwillneedtochecktheretroarch.cfgfiletoidentifythebuttonsyouwanttousehere.Obviouslyyou dontwanttoexitgamesusingtheusualcontrollerbuttonsinstead,youshouldbelookingfortheones thatrelatetothebuttonsinthecentreofthecontroller,perhapslabelledmenuorstart.

RetroPieInstallingROMs
HopefullyyouhavesetupthefolderstoinstalltheROMsusingSAMBASHARESfromthesetupscript.If notyoucanstilluseMobaXTerm(thenontheleftnavigateto/home/pi/RetroPie/roms/ andyouwillfindafolderforeachemulator.Putthecorrectromsinthecorrectfolders!

154

MAME NES
http://www.youtube.com/watchv=7_lbCaBUwhc&feature=bf_next&list=PLN4WWy3UrTHT02MuTtn9Q_W ZxsXhk2ne7

SnesEmulatorSNES9x
https://github.com/ToadKing/RetroArchRpi Snes9x Thereare2choiceV1.39(withosssound)here or1.53(SNESSDLwithlotsofframeskip!)here

Version1.39 Somerequirements.
sudoaptgetinstalllibsdlttf2.0devlibboost1.50alldev cd~ mkdirSNES cdSNES gitclonehttps://github.com/chep/snes9xrpi cdsnes9xrpi make sudomakeinstall ConfJoytoolisreplacedbyconfToolwhichconfigureskeyboardtoo.Startitinits directory,itwillcreateinput.configinsnesdirectory(..).Itsfirstargumentisthenumber ofplayerswhowillusethekeyboard.Use0(zero)ifyouhavenokeyboard.

ScummVM
http://www.raspberrypi.org/phpBB3//viewtopic.php?f=35&t=10692

DGen
(timetoinstallaround1hr)

DGenManual.
http://www.rjanick.com/2012/10/29/dgenontheraspberrypi/ http://dgen.sourceforge.net/

DGenBuildInstructions
InstallthissoyoucanrunROMSfromZips
sudoaptgetinstalllibarchivedev

155

cd~ mkdirDGen cdDGen wgethttp://www.libsdl.org/release/SDL1.2.15.tar.gz tarxvfSDL1.2.15.tar.gz cdSDL1.2.15 ./configure sudomake sudomakeinstall cd.. wgethttp://sourceforge.net/projects/dgen/files/dgen/1.32/dgensdl1.32.tar.gz tarxvfdgen<tab rmdgensdl1.32.tar.gz cddgen<tab> sudo./configure sudomake sudomakeinstall

Ifnotworktryusing
makeinstallclean

FinallrunDGenusingthisforfullscreen.
dgen<filename>f

Orthiswhenrunningonsmallerscreens!
dgen<filename>G320x240

TweakingDGen
Editsettings
sudonano/home/pi/.dgen/dgenrc.auto Thenewestgitversionofdgen(andIthinkthenewestrelease1.32version)includesASMoptimizedemulatorsforthe m68kandz80...makesureyouenablethem=).Youmusteditthedgenrc.5fileandsetthefollowing emu_z80_startup=drz80 emu_m68k_startup=cyclone Thedefaultsarecz80andmusa,andtheyarenotoptimizedforthearmplatform.

SonicLevelSelect
http://info.sonicretro.org/Sonic_hacks

DGenCONTROLS
GAMEPAD: DirectionalControlCursorKeys ButtonAA ButtonBS

156

ButtonCD StartEnter ExitEsc F5TogglesTVModes:blur,scanline,interlace,swab,off F6TogglesScaleModes:hqx,scale2x,default(NONE) ForaFULLdescriptionoftheControlsandOptionsseeHerehttp://dgen.sourceforge.net/

157

Mupen64RPi
TOBUILD/RUN HardwareMupen64plusRpiwillbuildona512or256MEGRaspberryPi,ifyouhavea256MEGvarietymakesure youhavetheRAMsplitattributingaMAXIMUMof64MEGtotheGPU(usetheconfig(sudoraspiconfig)) OperatingSystemRaspbianWheezy OverClockDuetotheprocessingpowerrequireditisadvisedtorunMupen64plusRpiwiththefastestOverClock thatisstableonyourSystem(usetheconfig(sudoraspiconfig)) DependenciesRequiredSDL1.2dev AdditionalFilesRequiredGameROMS RAMSplitAtleast64MEGtotheGPU BuildTimeApproximately45minutesto1Hourdependingonoverclock Installtherequireddependancies sudoaptgetinstalllibsdl1.2dev DownloadthesourcecodefromGithub(ontherightyouwillseeaCloudsymbolwithDownloadZIP,that'sthelinkfor themasterfolder)andextract(uncompress). DownloadLinkhttps://github.com/ricrpi/mupen64plusrpi CDintothefolderandrunthebuildscript ./m64p_build.sh OncecompletedaddsomeROMsandextractthemtoanappropriatefolder(Icalledminen64roms), thenCDintothetestfoldermupen64plusrpimaster/test(wheretheexecutableandpluginsarelocated)andrunthe programalongwiththenameandlocationoftheROM e.g../mupen64plus/home/pi/n64roms/mario.n64(youcanchangethefilenameforeasytyping) CONFIGURATIONFILESETTINGS Thecfgfileislocatedat/home/pi .confg(HiddenFolder) mupen64plus/mupen64plus.cfg Basicchangesareidentifiedbelow,Ifyouarefamiliarwithemulatorcfgfilesfeelfreetoexperimentwithothersettings andreportyourfindings(thiswillassistwithemulatordevelopment). [VideoGeneral] #Widthofoutputwindoworfullscreenwidth ScreenWidth=(Default:640) #Heightofoutputwindoworfullscreenheight ScreenHeight=(Default:480) Changevaluestoalteroutputresolution,320x240istheoriginalhardwareres(inmostcases),andupto1024x768 hasaminimalimpactonperformance(12%whenrunningfromConsole) [VideoRice] #Controlwhenthescreenwillbeupdated(0=ROMdefault,1=VIoriginupdate,2=VIoriginchange,3=CIchange, 4=firstCIchange,5=firstprimitivedraw,6=beforescreenclear,7=afterscreendrawn) ScreenUpdateSetting=(Default:6) Changevaluetoalterscreenupdate,caninfluencecorrectgameperformance(asettingof4willallowStarFox64to rendercorrectlyandPilotWings64todisplayforexample) #Forcetousetexturefilteringornot(0=auto:n64choose,1=forcenofiltering,2=forcefiltering) ForceTextureFilter=(Default:1) Changevaluetoenablefiltering,smoothstextureswithminimalimpactonperformance #Forcetousenormalalphablender NormalAlphaBlender=(Default:False) ChangetoTruefixessomegamessoenvironmentsdisplaycorrectly

158

e.g. TurokDinosaurHunter #Ifthisoptionisenabled,thepluginwillskipeveryotherframe SkipFrame=(Default:True) ChangetoFalsefixessomegamesinconjunctionwithScreenUpdateSetting,however,duetoeveryframebeing displayedslowsemulation e.g. Goldeneye64 TheLegendofZelda:MajorasMask SetScreenUpdateSetting=1,SkipFrame=False Enjoy!

159

SOFTWAREProjects

154

SiriProxyAsUser
FromHere Beforewestart,Idrecommendgettingtmux,butfeelfreetoskip.Youllneedthis(orsomethingsimilar), ifyouplantostarttheSiriProxyserverintheforeground(soyoucanseetheoutput)anddisconnectthe terminalsession(withoutbackgroundingtheserver).Thiswillletyoudisconnect,reconnectwithoutthe serverstopping.ThisinstallprocesscontainsoneverylongstepandIdrecommendrunningthiswith tmuxincaseyougetdisconnected.Italsoletsyourunseveralterminalsessionwithasingletelnet/ssh login.
sudoaptgetinstalltmux

Imalsogoingtocreateausercalledpi
sudoadduserpi

SiriProxyInstall
1.InstalleverythingneededforRuby,RVM,git,etc.
sudoaptgetinstalldnsmasqrubybuildessentialopenssllibreadline6libreadline6devcurlgitcorezlib1gzlib1gdev libssldevlibyamldevlibsqlite30libsqlite3devsqlite3libxml2devlibxsltdevautoconflibc6devncursesdevautomake libtoolbisonsubversion

Selectytocontinue. 2.EditDNS (YoucanskipthisifyourrouterorotherDNScanhandleit.SeeDNSbelow)


sudonano/etc/dnsmasq.conf

Findthelinestartingwith:#address=/doubleclick.net/127.0.0.1(useCtrlWtosearch) AddanewlineredirectingtheApplesSiriservertoyourlocalIP(fromifconfig)
address=/guzzoni.apple.com/192.168.168.63

Saveandexit(CtrlO,Enter,CtrlX) restartdnsmasq
sudo/etc/init.d/dnsmasqrestart

160

TestDNSisresolvingcorrectly
pingguzzoni.apple.com

TypeCtrlCassoonasyouseeanipaddress(almostimmediately) ThisshouldreturnApplesIPaddress(Igot17.174.8.16).AppleblocksICMP,sothepingswilltimeout justmakesureitresolvesintoa17.x.y.zaddress. 3.InstallRVM


bash<<(curlshttps://raw.github.com/wayneeseguin/rvm/master/binscripts/rvminstaller)

Dontworryaboutthewarninginred,thenexttwocommandstakecareofit LoadRVMasafunctionandupdateprofile
[[s"$HOME/.rvm/scripts/rvm"]]&&."$HOME/.rvm/scripts/rvm" echo'[[s"$HOME/.rvm/scripts/rvm"]]&&."$HOME/.rvm/scripts/rvm"#LoadRVMfunction'>>~/.bash_profile

(Idrecommendusingtmuxforthisbit)
rvminstall1.9.3

Youmighthavetorun
rvmautolibsenable

Whichtellstherubyinstalltograbthebitsitneeds! Dontworryaboutthismessage: No binary rubies available for: debian/wheezy_sid/armv6l/ruby-1.9.3-p374. answerYtoallprompts(takesoveranhourtorunontheRaspberry) Ifyougetthefollowingerror,itslikelythatyouranoutofdiskspace(rundfktocheck). 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. SetRuby1.9.3asdefault
rvmuse1.9.3default

4.InstalltheSiriProxy
gitclonegit://github.com/plamoni/SiriProxy.git cdSiriProxy

Select'y'towarningtocontinue.
mkdir~/.siriproxy cp~/SiriProxy/config.example.yml~/.siriproxy/config.yml rakeinstall

Takesawhiletoo.(ifthisdoesnttakeawhile,followtheerroroutputandrun
geminstall/home/pi/SiriProxy/pkg/siriproxy0.5.3.gem

5.GenerateCertificates
siriproxygencerts

6.InstalltheCertificateonyouriPhone Youcanuseanymechanismtogetittotheiphone.AsImusingTerraTerm,IjustusedSSHSCP(File menu>SSHSCP) 161

Anothergreatalternative(ifyoullbedoingalotofeditingonyourlocalmachine)isWinSCP:

Emailthecertificateyourself,clickitandinstallonphone(ignorewarningaboutitbeinguntrusted) 7.Bundle Setafewthingsintheenvironmentfirstandcreateasymboliclinksothatrvmsudoworks.


echo'exportrvmsudo_secure_path=1'>>~/.bash_profile source~/.bash_profile sudolns~/.siriproxy/root/.siriproxy rvmsudosiriproxybundle

8.Starttheserver
rvmsudosiriproxyserver

Amessageshouldappearsayingsomethinglike: Starting SiriProxy on 0.0.0.0:443.. SiriProxy up and running. 9.SetDNSserveronphone ThelaststepistopointyouriPhoneatyourDNSserver.ThiswillbethePIsIPunlessyouareusingan 162

externalDNSserver. 1. GottoSettings>WiFi 2. Clickthebluearrownexttoyourconnection 3. EntertheLinuxVM'sIP

163

10.Test Note:withthecurrentversionsyouwillhighlylikelyreceiveanInvalidByteSequenceerror.Dontpanic.See InvalidByteSequencebelow.Othererrors,andsolutions,canbefoundinPart1 Tryitanyway Pressandholdthehomebutton. SaytheexactphraseTestSiriProxy.ItshouldrespondwithexactlySiriProxyisupandrunningand youshouldseesomethinglikethis:


CreateserverforiPhoneconnection startconn#,@zip_stream=#,@consumed_ace=false,@name="iPhone", @ssled=false> [InfoPluginManager]Pluginslaoded:[#>] [InfoiPhone]ReceivedObject:LoadAssistant [InfoiPhone]ReceivedObject:SetRestrictions [InfoiPhone]ReceivedObject:SetRestrictions [InfoiPhone]ReceivedObject:ClearContext [InfoiPhone]ReceivedObject:SetSessionObjects [InfoGuzzoni]ReceivedObject:AssistantLoaded [InfoiPhone]ReceivedObject:StartSpeechRequest [InfoiPhone]ReceivedObject:SetRequestOrigin [InfoUserLocation]lat:XX.07408038900973,long:YY.70323611215576 [InfoiPhone]ReceivedObject:SpeechPacket [InfoGuzzoni]ReceivedObject:SetConnectionHeader

164

[InfoiPhone]ReceivedObject:SpeechPacket [InfoiPhone]ReceivedObject:SpeechPacket [InfoiPhone]ReceivedObject:SpeechPacket [InfoiPhone]ReceivedObject:SpeechPacket [InfoiPhone]ReceivedObject:SpeechPacket [InfoiPhone]ReceivedObject:SpeechPacket [InfoiPhone]ReceivedObject:SpeechPacket [InfoiPhone]ReceivedObject:SpeechPacket [InfoiPhone]ReceivedObject:SpeechPacket [InfoiPhone]ReceivedObject:SpeechPacket [InfoiPhone]ReceivedObject:FinishSpeech [InfoGuzzoni]ReceivedObject:SpeechRecognized [InfoPluginManager]Processing'TestSiriproxy' [InfoPluginManager]Processingplugin# [InfoPluginManager]Matches(?imx:testsiriproxy) [InfoPluginManager]Applicablestates: [InfoPluginManager]Currentstate: [InfoPluginManager]Matches,executingblock [InfoPluginManager]Say:SiriProxyisupandrunning! [InfoPluginManager]SendingRequestCompleted

SiriProxyPlugins
GenerallyvisittheGitHub, Gotothe~/SiriProxy/PluginsFolder Doagitclone<git> seewhatsintheconfiginfo.yml(copytheinstallbit)ignorethisandjustmakethepathequalsoitcan findtheconfiginfo.yml andpasteinthegeneralfilebelow. sudonano~/.siriproxy/config.yml runrvmsudosirproxybundle runrmvsudobundlesinstall Finallyrvmsudosiriproxyserver(anditshouldALLbeworking!) Magic8Ballhttps://github.com/Ponyboy47/siriproxymagic8ball SiriIMDBhttps://github.com/mattparmett/SiriProxySiriIMDB SirFoulLanguagehttps://github.com/coden00b/SiriProxyFoulLanguage

AddingyourownSiriCommands
Editthisfile.
sudonano~/SiriProxy/plugins/siriproxyexample/lib/siriproxyexample.rb

findthelisten_for,addyourowncommands.TheymustbealignedandthecoloursMUSTmatchup! listen_for/whattimeisit/ido
say"It'sHammerTime."#Saysomethingtotheuser! request_completed#alwayscompleteyourrequest! end

Youcanaddcommandstoberunusingtheputs%x{}command.
listen_for/Quake/ido

165

say"abouttorunQuake3"#Saysomething puts%x{sudo/home/pi/Quake3/ioquake3.arm} request_completed#Alwayscompleteyourrequests! end

Afteryouhavemadechangesyoushoulddo
rvmsudosiriproxyupdate rvmsudobundleinstall rvmsudosiriproxybundle

Thentestwith
rvmsudosiriproxyserver

166

SiriProxyAsRoot
DifferentApproach,notasROOT http://www.hometoys.com/emagazine/2013/02/sirihomeautomationintegrationfromstarttofinishbrpar t1thebasicsusingalinuxvm/2087 Bestguideyet. http://steve0hh.wordpress.com/2013/02/11/raspberrypisiriproxy/ https://gist.github.com/elvisimprsntr/4409751 http://simonthepiman.com/how_to_setup_windows_file_server.phpsettingupSAMBA. ClonetheGitHubandinstructions. https://github.com/plamoni/SiriProxy http://www.idownloadblog.com/2011/12/09/howtoinstallsiriproxytutorialvideo/ 1.UPDATEYOURPI.
TypethisintoPisterminal: aptgetupdate aptgetdistupgrade aptgetautoremove

2.SETTHEROOTPASSWORDFROMTHEUSERACCOUNT
Thismightnotsoundimportant,butthiswillsavealotofhassel!YoullneedrootaccesstostartSiriProxy,butyou dontneedtosudowhileinstallingRVM,whichwillresultinyourusernotbeingabletostartSiriProxyserver.Orroot nothavingRVM,SiriProxyinstalledforthem. Type sudopasswd Setthedesiredpassword. Logoutandlogbackinusingroot. Removetheoriginalaccount(Optional): deluser

3.INSTALLINGTHEBASICS
aptgetinstallsambasambacommonbinsshvimrcsunzipy

4.EDITTHENETWORKSETTINGSTOUSEASTATICIPADDRESS
WedothissoasyourPidoesntchangeitsIPaddress,hencewellhavelesserhasselwhensettinguptheiPhone forSiriProxy. Toedit,type: vim/etc/network/interfaces Thenonceintheconfigurationfile,commentthefollowingoutbyaddinga#tothefront: From ifaceeth0inetdhcp to ifaceeth0inetstatic Thenaddthefollowingsnippetbelowthelineofcodeyouhavejustcommentedout.

167

Note:Replacethewordsincaplockswithyourownaddress. autoeth0 ifaceeth0inetstatic addressYOURDESIREDIPADDRESS netmask255.255.255.0 broadcast192.168.1.255 network192.168.1.0 gateway192.168.1.254 ExampleofmineasmyPisIPaddresswas192.168.1.6: autoeth0 ifaceeth0inetstatic

4.REBOOTYOURPI
Reboottohavethechangestakeeffect. Toreboot,type: reboot

5.BREAKTHECIRCULARAPPLESSIRISERVERDNSREDIRECT
EdityourDNSsettings: nano/etc/resolv.conf CommentoutNAMESERVERentiresfromyourISPorrouterinternalIPaddress,whichisusuallyjustthefirstlinein thefile,thenaddthisintothefile: #GooglepublicDNSservers nameserver8.8.8.8 nameserver8.8.4.4 #Level3publicDNSserverslesshopsandshorterpingtimes nameserver209.244.0.3 nameserver209.244.0.4

6.SETUPYOURDNSSERVER
IamoptingtousePiastheDNSserverasIdonotwanttomesswithmyrouterssetting. ToinstallDNSMASQ,type: sudoaptgetinstalldnsmasq Changetheconfigfile.
s u d o n a n o / e t c / d n s m a s q . c o n f

Ataroundline63,findthefollowing #address=doubleclick.net/127.0.0.1 Underitaddthis #iOSproductionSiriserver address=/guzzoni.apple.com/<yourstaticip> #iOSbetaSiriserver address=/kryten.apple.com/<yourstaticip> Hitsave,thenrestartdnsmasqbytyping: sudo/etc/init.d/dnsmasqrestart

7.INSTALLTHEPREREQUISITETHATNEEDEDTOBEINSTALLED:
168

sudoaptgetinstallrubybuildessentialopenssllibreadline6libreadline6devcurlgitcorezlib1gzlib1gdevlibssldev libyamldevlibsqlite3devsqlite3libxml2devlibxsltdevautoconflibc6devncursesdevautomakelibtoolbison subversionpkgconfigy

8.INSTALLRVM
bash<<(curlshttps://raw.github.com/wayneeseguin/rvm/master/binscripts/rvminstaller)

9.SETRVMPATH
[[s"/etc/profile.d/rvm.sh"]]&&."/etc/profile.d/rvm.sh"

10.SETTHERVMPATHTOBESETUPEVERYTIMEILOGIN
echo'[[s"/etc/profile.d/rvm.sh"]]&&."/etc/profile.d/rvm.sh"#LoadRVMfunction'>>~/.bash_profile

11.INSTALLRUBY1.9.3
(Thiswilltakequitealongtime..Sogograbacoffeeandcomeback.) rvminstall1.9.3

12.CLONETHESIRIPROXYREPO
cd~ sudogitclonegit://github.com/plamoni/SiriProxy.git

13.ENTERTHESIRIPROXYDIRECTORY
cdSiriProxy

14.MAKETHE.SIRIPROXYDIRECTORYINMYHOMEDIRECTORY
mkdir~/.siriproxy

15.COPYTHEEXAMPLECONFIGTO.SIRIPROXYDIRECTORYTOUSE
cp./config.example.yml~/.siriproxy/config.yml

16.INSTALLSIRIPROXY
Cantakeaminuteortwo rakeinstall N.B.Ifnotrunningasrootyouwillprobablyhavetosetpermissionsusing sudochownRwhoami~/.rvm and sudochownRwhoami~/.SiriProxy Itthemfailsonthebuildandtellsyouturrun geminstall/home/pi/SiriProxy/pkg/siriproxy0.5.2.gem DONOTRUNTHISASSUDO,itwillfail,tryitnormally!

17.GENERATETHECERTIFICATESFORYOURIPHONETOUSE
siriproxygencerts

18.EMAIL&INSTALLITTOYOURIPHONE!
AsSSHport22isopenedbydefaultontheRaspbianwheezyimage,wecoulduseWinSCP(onourmaincomputer) togetthecertificate(ca.pem)fromourPi.Todothat,wevetotype(onourmaincomputer): Naviagateto/home/pi/.siriproxyandcopytheca.pem. AttachthisfiletoanemailaccountyouhaveaccesstoonyouriPhone. OntheiPhonesimply,openyouremail,tapthefileandfollowthepromptstoinstallthecertificate.

169

19.CONFIGUREYOURIPHONE
AswellneedtoconfiguretheDNSsettingsontheiPhone!. HeadtoSettingsapponyouriPhone,selectWifi.

Thenselectthebluearrowofthehotspotyouareconnectedtoformoresettings.

ChangetheDNSIPaddresstoyourPisIPaddress,inmycase,Ivesetitto192.168.1.6,whichismyIPaddress.

170

20.BUNDLESIRIPROXY
Thisinstallsthepluginsandwhatnot siriproxybundle bundleinstall

21.STARTTHESERVER!!
TostartSiriProxy,type: siriproxyserver Intheterminalitshouldshowsomethinglike:

22.TESTIFITSWORKING!
OnyouriPhonelaunchSiriandsay:testsiriproxy IfitreplyswithSiriProxyisupandrunning!,thenyouknowyougotit.Andontheterminal,youwillseesomething liketheimagebelow.

171

UltrasonicDistanceMonitor
http://www.raspberrypispy.co.uk/2013/01/ultrasonicdistancemeasurementusingpythonpart2/

172

TakingScreenshotsontheRaspberryPi
PostedbyzagonFeb27201304:26PM

Itlookslikethedefaultdebianimageisn'tsetuptotakescreenshotsatthemoment. Mostpeoplewillneedtomakeascreenshotatsomepoint,sohereisaquickguidetosettingitup.

Step1
Loadupstart>>accessories>>LXTerminal
sudoaptgetinstallscrot

Whentheinstallisfinished,type'scrot'attheterminaltostartit.

Step2
Press"PrtScr"onthekeyboard Nowgotofilebrowserandyouwillseethescreenshotinyouruserarea. Somethinglikethis: [attachment=222:screenshot.jpg]

173

SimpleSambaShare
http://elinux.org/RPi_NAS (Triedthissokidscouldgrabstufffrommydemopi?)
cd~

#Installthe2sambapackages(30ishMB)
sudoaptgetupdate sudoaptgetinstallsamba

Editthesambaconfigforyourshare!
sudonano/etc/samba/smb.conf

#Addthefollowingattheend
[MROShare] comment=MROShare path=/home/pi/ readonly=Yes writeable=Yes createmask=0777 directorymask=0777 guestonly=Yes guestok=Yes

#Savethefile(ctrl+o,Enter,ctrl+x) #RestarttheSambaservice.Test.
sudoservicesambarestart

usesmbgetorsimilartotest(tryoutonwindowsPC!)

SMBGET(testedandworking!)
youneedtohavesambainstalledtousethistograbafile.
sudosmbgetsmb://<ipaddress>/<folder>/<file>

ortograbanentirefolder(useRrecursive)
sudosmbgetRsmb://<ipaddress>/<foldere.g.MROShare>/<file>

SAMBAServeronthePi.
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 applied
pi@raspberrypi~$sudoaptgetupdate

NOTE:- The disk drives that I will be attaching will be formatted in windows format - either FAT32 or NTFS

174

3. Attach the disk drive or drives to the Raspberry Pi then type


pi@raspberrypi~$sudofdiskl

This will show all the details of the attached disks even if you are not yet using or are able to access them. A powered 1Tb disk drive and a 400Mb usb card

Disk/dev/mmcblk0:3965MB,3965190144bytes DeviceBootStartEndBlocksIdSystem /dev/mmcblk0p117121676800cW95FAT32(LBA) /dev/mmcblk0p2123326672162816083Linux /dev/mmcblk0p3266892974419558482Linuxswap/Solaris Disk/dev/sda:1000.2GB,1000204886016bytes DeviceBootStartEndBlocksIdSystem /dev/sda111216019767600017HPFS/NTFS Disk/dev/sdb:4005MB,4005560320bytes DeviceBootStartEndBlocksIdSystem /dev/sdb114863903763+bW95FAT32 From the above listing you can see a disk /dev/mmcblk0 (the SD Card) which contains 3 partitions - so this is the operating system disk. I also have /dev/sda which is a Terabyte drive which has one partition and has been formatted 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 been formatted 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 device address such as /dev/sda with a partiton 1 so /dev/sda1 is the disk in the first Pi usb port and is partition 1. 4. Now we need to make the disks available to the operating system so we need to create a 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 the example below we will use /mnt/disk1 for the 1st Disk and /mnt/disk2 for the second.
pi@raspberrypi~$sudomkdir/mnt/disk1 pi@raspberrypi~$sudomkdir/mnt/disk2

The above commands have made 2 new directories for us to use. To test they exist type
pi@raspberrypi~$ls/mnt

it should show the following if all is ok disk1 disk2 5. Now we need to attach the disks to these folders so we have to edit the /etc/fstab file that is used my the operating system on bootup to connect the physical disks to the 175

filesystem.
pi@raspberrypi~$sudonano/etc/fstab

This will show the following proc/procprocdefaults00 /dev/mmcblk0p1/bootvfatdefaults00 #/dev/mmcblk0p3noneswapsw00 We need to add the bottom 2 lines for the 2 disk drives, please note that the entry vfat or ntfs-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/procprocdefaults00 /dev/mmcblk0p1/bootvfatdefaults00 #/dev/mmcblk0p3noneswapsw00 /dev/sda1/mnt/disk1ntfs3gdefaults00 /dev/sdb1/mnt/disk2vfatdefaults00 To make the files visible to the filesystem type
pi@raspberrypi~$sudomounta

This will try to mount the new devices into /mnt/disk1 and /mnt/disk2 - so to test if it has worked type
pi@raspberrypi~$ls/mnt/disk1

This should now list any files on the disk that you have put there. If this is not the case then 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 to share windows files.
pi@raspberrypi~$sudoaptgetinstallsamba

Wait while stuff flies up the screen and type y at any yes/no prompts Depending on the Distro you are using you may need to install this, so do it anyway.
pi@raspberrypi~$sudoaptgetinstallsambacommonbin

7. When all is complete then the samba package has been installed so will need configuring for your setup, so you will need to edit the /etc/samba/smb.conf file.
pi@raspberrypi~$sudonano/etc/samba/smb.conf

The things that possibly need changing are the workgroup entry set to WORKGROUP for XP and previous operating systems and HOME for Windows 7 and above (not sure what is the default for Vista). workgroup=WORKGROUP Then i would comment out the following lines by adding a ; to the front of the item as this makes initial setup and testing easier.
[homes] comment=HomeDirectories browseable=no [printers] comment=AllPrinters browseable=no path=/var/spool/samba printable=yes guestok=no

176

readonly=yes createmask=0700 [print$] comment=PrinterDrivers path=/var/lib/samba/printers browseable=yes readonly=yes guestok=no [cdrom] comment=Sambaserver'sCDROM readonly=yes locking=no path=/cdrom guestok=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 of usband will share out the content of /mnt/disk1 - to share the other disk, add another entry as below with the share name within the [ ] and the path to the other disk drive.
[usb] comment=USBShare path=/mnt/disk1 writeable=Yes onlyguest=Yes createmask=0777 directorymask=0777 browseable=Yes public=yes

8. At last we can restart samba and test the configuration so to restart samba.
pi@raspberrypi~$sudoservicesambarestart

and to check the shares and configuration run


pi@raspberrypi~$sudotestparms

this should show something similar to that below


Loadsmbconfigfilesfrom/etc/samba/smb.conf rlimit_max:rlimit_max(1024)belowminimumWindowslimit(16384) Processingsection"[usb]" LoadedservicesfileOK. Serverrole:ROLE_STANDALONE [global] serverstring=%hserver obeypamrestrictions=Yes pampasswordchange=Yes passwdprogram=/usr/bin/passwd%u passwdchat=*Enter\snew\s*\spassword:*%n\n*Retype\snew\s*\spassword:*%n\n *password\supdated\ssuccessfully*. unixpasswordsync=Yes syslog=0 logfile=/var/log/samba/log.%m maxlogsize=1000 dnsproxy=No winssupport=Yes panicaction=/usr/share/samba/panicaction%d

177

[usb] comment=USBShare path=/mnt/disk1 readonly=No createmask=0777 directorymask=0777 guestonly=Yes guestok=Yes

If you get the above info then you need to add the pi user to the samba user database which is not the same as the pi username/password but can be so
pi@raspberrypi~$sudosmbpasswdapi

This 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 you will 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\piin the user name field and raspberry in the password field. NOTE: windows will always by default try your username and password from your PC to make the connection (in my case my PC is called VNET and my username is simon so you see 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 to also specify the machine that the user is on before the user name therefore the username is raspberrypi\pi.

178

Then click [OK] which will close the pop-up and [Finish], this should now map your drive to the Raspberry Pi NAS server. 9. Right the samba share is working, however if you reboot the Pi then the drive will not be auto mounted, and therefore the share will be empty - so we will need to install a command called autofs which is designed to automatically mount usb disk drives.
pi@raspberrypi~$sudoaptgetinstallautofs

This 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~$sudovi/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.extusbtimeout=10,defaults,user,exec,uid=1000

Now you can reboot and the server will keep on working and sharing your windows files on boot

179

SOFTWAREXBMC

174

XBMCisthebestmediasoftwareIhaveeverused.Ivebeenafanandbeenausersincethedaysof theoldXBMC4Xbox!ItwasthemajorfactorastoWHYIjailbrokemyiPad! Howeverasthisguideisfortheraspberrypiletsdealwiththat!

Ivetriedboth

Xbianand

RaspBMC.

XBianseemsstablebutisonlyupdatedhalfasoften.Bothseemtoworkwell.RaspBMChasthe advantageofbeingoneofthestandardinstallsforNOOBS.N.B.IhadtroublewiththeRaspBMCusing NOOBS,ifyoureusingtheAutoUpdatefeatureitcanbaulkyourinstall(thisisallegedlyfixedwiththe newestupdate!).Bettertodoacustombuildifitisoneyouareusingallthetime!(Ihave2floating aroundthehouse,thismaybecome3,withonehookeduptotheStereo!) Youllneedtoinstallthefollowingbitsofsoftwareifyouretryingtodoanythingclever. sudoaptgetinstallgitcloneunzip

BootingtoBlackScreen
TheraspberrypiseemstohavesomeissueswithsomeTVs,whereitwillseeminglyboottoblack screen.IthinkthisissomethingtodowiththeHDMIstoppingsupplyingpowerorsomethingandthePi defaultingtotheCompositeVideoOut.TostopthisedittheConfig.txtontherootofthecardensuringit hasthefollowing(thelast3linesarethemostimportant!)
arm_freq=840 core_freq=350 gpu_freq=253 force_turbo=1 disable_overscan=1 gpu_mem=128 start_file=start_x.elf fixup_file=fixup_x.dat hdmi_force_hotplug=1 hdmi_group=1 hdmi_mode=16

180

Windows7andAddingSources
IhavehadissueswithaWindows7PC*(orseveralofthemonthesamenetworknotshowingupin XBMC,tofixthisensuretheyhaveSTATICIPaddresses.Whenaddingsourcesdontbothersearching justuse
smb://<fixedip>/<share>,somyTVfolderwouldbesmb://192.168.1.1/Tv AlsoensurewhenaddingsharestoWindowsthatyouuseADVANCEDSHARING,EVERYONEshouldhave permissions. RightClickonFolder Properties Sharing AdvancedSharing Permissions CheckthatEveryoneisetcwithatleastreadallowticked.

181

HowtoaddSources/Repos/Addons
Thebestwaytogetadditionalplugins,addonsandRepos(repositoriesthatwillautoupdateyour softwarewhennewversionsbecomeavailable!)etcistoaddthesourcesetc. InXBMCgotoPrograms>FileManager,thenAddsource. 2Excellentsourcestoaddare
XBMC: http://xbmc.flirc.tv Install the repository so when updates are available it will update automatically. Then install the Addon.

Fusion:http://fusion.xbmchub.com (installAddonsViaZipFile,choosethehubwizardbeta) FromtheRepo Byaddingthemassourcesitwillmakeiteasiertoinstalltheadditionaladdons.(insteadofbrowsingfor localZipFiles,youcanthenbrowseforZipfilesfromtheonlinesources. GotoVideos>AddonschoosetheXBMCHubWizard,waitforthelaunchertorunthenchoosethe Androidinstall.Thiswillinstallatonofaddons,butitwillalsomessupsomeofyourdefaultssobe preparedtosetthingsupagain!(Itwillalsochangethebootlogoandyourwallpaper,sohavethose readytoo!) GettheFLIRCPluginfromtheGitHubhttps://github.com/flirc/flircxbmcplugin

182

CustomXMLforbetterremoteusage(atleastonourbigtelly!!!)
sudonano/$HOME/.xbmc/userdata/keymaps/remote.xml
< k e y m a p > < F u l l s c r e e n V i d e o > < r e m o t e > < s e l e c t > O S D < / s e l e c t > < s u b t i t l e > S h o w S u b t i t l e s < / s u b t i t l e > < r e d > S h o w S u b t i t l e s < / r e d > < / r e m o t e > < / F u l l s c r e e n V i d e o > < V i s u a l i s a t i o n > < r e m o t e > < s e l e c t > O S D < / s e l e c t > < r i g h t > S k i p N e x t < / r i g h t > < l e f t > S k i p P r e v i o u s < / l e f t > < b a c k > B a c k < / b a c k > < / r e m o t e > < / V i s u a l i s a t i o n > < g l o b a l > < r e m o t e > < m e n u > C o n t e x t M e n u < / m e n u > < / r e m o t e > < / g l o b a l > < / k e y m a p >

FixingTVScraperError
SometimeifyoureusingsourcesandscanningXBMCwillcomeupwithunabletobeconnecttosource, continuescanningerrorthiscangetboring.IthinkitssomethingtodowiththeTVDBandthescraper. Thisseemedtofixitforme. Youmayhavetocreate/editthefollowingfile. /$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 exactly as is (save as tvdb.xml and replace in folder)

but use this

<?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;url cache=&quot;\1-$INFO[language].xml&quot;&gt;http://thetvdb.com/api/1D62F2F90030C444/series/\1/all/$INFO[langu age].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

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;langu age=$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;url cache=&quot;\1-$INFO[language].xml&quot;&gt;http://thetvdb.com/api/1D62F2F90030C444/series/\1/all/$INFO[langu age].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;url cache=&quot;cache-\1$$4.xml&quot;&gt;http://thetvdb.com/api/GetSeries.php?seriesname=\1$$4&amp;amp;langua ge=$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;url cache=&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"> <expression repeat="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></det ails> --> <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

<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;.*?&l t;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;thumb aspect=&quot;banner&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"> <expression repeat="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&g t;</expression> </RegExp> <RegExp input="$$5" output="&lt;thumb aspect=&quot;banner&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"> <expression repeat="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;thumb aspect=&quot;banner&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"> <expression repeat="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;</e xpression> </RegExp> <RegExp input="$$5" output="&lt;thumb aspect=&quot;banner&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"> <expression repeat="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;/Langu age&gt;</expression> </RegExp> <RegExp input="$$5" output="&lt;thumb aspect=&quot;banner&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"> <expression repeat="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+"> <expression repeat="yes">&lt;BannerPath&gt;([^&lt;]*)&lt;/BannerPath&gt;[^&lt;]*&lt;BannerType&gt;season&lt;/BannerType&gt

185

;[^&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+"> <expression repeat="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;/L anguage&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+"> <expression repeat="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;/Languag e&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+"> <expression repeat="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])*&l t;/Language&gt;[^&lt;]*[^S]*Season&gt;([0-9]+)&lt;/Season&gt;</expression> </RegExp> <RegExp input="$$5" output="&lt;thumb aspect=&quot;poster&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+"> <expression repeat="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+"> <expression repeat="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;fanart url=&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+"> <expression repeat="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+"> <expression repeat="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;url cache=&quot;$$2-$INFO[language].xml&quot;&gt;http://thetvdb.com/api/1D62F2F90030C444/series/\1/all/$INFO[lan guage].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>*</thu mb><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

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+"> <expression repeat="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&l t;/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+"> <expression repeat="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;url cache=&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"> <expression repeat="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;url cache=&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"> <expression repeat="yes">&lt;Episode&gt;.*?&lt;id&gt;([0-9]+).*?&lt;Combined_episodenumber&gt;([^&lt;]*).*?&lt;Combined_se ason&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>*</p lot> --> <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

</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&g t;</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

SettingupaSharedLibrary
BasicExplinationhere http://lifehacker.com/5634515/howtosynchronizeyourxbmcmediacenteracrosseveryroomintheho use Fullguide http://wiki.xbmc.org/index.php?title=HOWTO:Share_libraries_using_MySQL (N.B.Onlyuseversion5.5ofSQLthelatestversion5.6doesntwork!)

FirstsetuptheSQLDB.
1. 2. 3. 4. 5. 6. DownloadacopyofMySQLserverfromhttp://dev.mysql.com/downloads/mysql/ SelectStandardconfiguration Createapasswordwhenasked Selectthatyouwantthedatabasetohavenetworkaccesswhenpromptedduringinstallation. Openthe"MySQLCommandLineClient"fromtheMySQLstartmenu Enterthefollowingcommands: 1. Typein:CREATE USER 'xbmc' IDENTIFIED BY 'xbmc';andpressreturn 2. Typein:GRANT ALL ON *.* TO 'xbmc';andpressreturn 7. Closeoutthecommandlinetool 8. InWindows7,youmayneedtomakeanexceptioninthe"WindowsFirewall" 1. Gotocontrolpanelandopenwindowsfirewall 2. Clickonadvancedsettings 3. ClickonInboundRules,thennewrule 4. Chosetheportoption,clicknext 5. Thentypeintheportnumberyousetmysqltouse(Defaultis3306) 6. MakesureAllowtheconnectionischeckedthenclicknext 7. NameitMYSQLInbound(orwhateveryouwant)thenclickfinish 8. UsethesesamestepstosetuptheOutboundexceptionthennameitMYSQLOutbound(orwhateveryou want)thenyou'refinished. 9. Youmayormaynothavetosetupbothinandoutbound,someonewithmoreknowledgepleaseeditthisifyou know. 10. InWindowsXP,youmayneedtomakeanexceptioninthe"WindowsFirewall" 1. OpenControlPanelandSetto'ClassicView' 2. DoubleClickonWindowsFirewall 3. ClickonException>AddPort 4. NameItMySQLXBMCorwhateveryouwant 5. Thentypeintheportnumberyousetmysqltouse(Defaultis3306)

Edittheadvancedsettings.xml
(intheuserdatafolder!) GNUnano2.2.6File:/$HOME/.xbmc/userdata/advancedsettings.xmlModified
<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

<user>xbmc</user> <pass>xbmc</pass> <name>xbmc_music</name> </musicdatabase> <videolibrary> <importwatchedstate>true</importwatchedstate> <backgroundupdate>true</backgroundupdate><!settohidethe$ </videolibrary> <videoscanner> <ignoreerrors>true</ignoreerrors> <videoscanner> </advancedsettings>

190

RemoteControls.
TherearemanywaystocontrolXBMConthePi. Youcanuseamouse,whichhaslimitedfunctionality. Youcanuseakeyboard,alittledifficulttonavigatesometimes. Youcanuseremote(30fromCPC)orfromachinesewholesalerifyourenotinarush http://www.tomtop.com/computersnetworking/hausbell24gminiwirelessqwertykeyboardmousetouc hpadforpcnotebookandroidtvboxhtpcc1705.html

Thisworksremarkablywell,comeswitha rechargeablephonebatteryandreciever.

Youneeddirectlineofsite,buthalftheprice.

Thefinaloptionistouseyourphone/ipad/tablet etc.MostofthemhaveXBMCremoteapps.The officialiOSxbmcRemoteappworkswell,although IwouldrecommendusingstaticIP.(itcanthen controlmultipleinstances(justnotatthesame time!) TodothisyouwillneedtoturnonZeroconfinthe XBMC>Settings>Services>Zeroconf. IdalsorecommedyouchangethenetworkIDof eachofthePisifyoureusingmultipleones.(see elsewhereinthisguide!)

191

AccessingRegionLockedContent.:)
GettingtheiPlayertoworkintheStates,or1channelorFreeCablepluginstoworkoutsidetheUSofAis apaininthebutt.HoweverIhaverecentlyhadsomesuccessusingtheexcellentTunlrservice, admittedlyyouhavetofiddleabitwithXBMCsettings,butttings,butnottoodtastically.Basicallyitjut requiresyoutosethtePrimaryDNSservertotheirs.InRaspBMCgototheRaspBMCsettings> Networkandjustenterthedteails,sometimesyoullahvetocheckthenumbers,othertimesyoumight ahvetochoosethihjeirbackupserverseirbackupserver.ThroughthisIvewatchedepisdoesofthe ColbertReportonComedyCentral,anepisodeofANTMontheCW,andanInterventiononA&E.Iwill keepthisupdated. PluginsIknowareworking. Video iPlayer FreeCable 1Channel NaviX IceFilms YouTube Vimeo Radbox Pluginsthatarecurrentlybroken. Video Demand5 4OD (botharebrokentillsomeonecanreverse engineertheiencryption)

Audio 8Tracks PBS DigitallyIMported

GetiPlayer
AlthoughtechnicallynotXBMCasthisisdesignedtoruninRaspbianthissoundedusefulandprettycool. ThissoftwareshouldallowyoutocaptureandrecordBBCprogramsfromiPlayer(ofcoursethiswont workifyoureoutsideGBunlessyouresmartwithaProxy.(seewww.tunlr.com) Fullinstructionshere. http://raspi.tv/2012/get_iplayerfullinstructionsforraspberrypiinstallfromscratch

192

USEFULBITSOFPYTHON

187

RunningAConsoleCommandViaPython
First
importos

Thecallanycommandyouwouldusuallytypeintheconsoleusing
os.system(<command>)

Noticethesinglequotes,youcanusemultiplecommands,stringthemtogetherusing&&orusesingle& toputtheminthebackground.

PassingArgumentstoPythonprograms
Youcanpassargumentstopythonprogams,e.g.TwitterPhoto.pylistedlater
pythonTwitterPhoto.pyarg1arg2

inthepythoncodeyoucanthenrecalltheseusing
x=sys.argv[1] y=sys.argv[2]

ChangingTerminalTextColours/EffectsViaPython
ThisIwouldhavethoughtwouldhavebeensimpleenough,sadlyitwasnot.TheonlywayIfoundtodo thiswastodownloadandaddressapythonmodulecalledcolorama,ensureyoucallthecommands Fore,Back,Styleetcfromthecoloramascript.thenuseprint(<colourbit>+message)
fromcoloramaimportFore,Back,Style print(Fore.RED+'someredtext') print(Back.GREEN+andwithagreenbackground') print(Style.DIM+'andindimtext') print(+Fore.RESET+Back.RESET+Style.RESET_ALL) print('backtonormalnow')

QuickPythonPygameJoystickAxisDetection(TestedandRechecked.)
Fromhere
#!/usr/bin/envpython importpygame importtime importmath

193

#initcontroller pygame.init() controller=pygame.joystick.Joystick(0) controller.init() print'XboxControllerConnected' print'/*********************************/' print'JoystickDriveProgram' print"UpdatedbyMROforXBoxPad" print'/*********************************/' key=0 y=0 x=0 whilekey!='q': foreventinpygame.event.get(): ifevent.type==pygame.JOYAXISMOTION: #PrintouttheAxispressedandtheValueturnedout(usuallybetween1and1) print"Axis:",event.axis,"Value:",event.value ifevent.axis==1: y=event.value #tomaketheselesssensetiveturnthemto0.5s(forbiggerdeadzone?) ifmath.fabs(y)<0.2: y=0 ifevent.axis==0:#Ihadtocheckthisvalueusingtheaboveevent.axis!!! x=event.value ifmath.fabs(x)<0.2: x=0 #Displaythecorrectoutputhopefully! command='' ify<0: command='up' elify>0: command='down' elifx<0: command='left' elifx>0: command='right' ifcommand!='': printcommand

UsingPygametodetectJoystickPresses
<fromhere>N.B.IhadtochangethedefprintfunctiontodefprintoutasthisconflictedwithPythonsexisitingprint
command.Nobiggy.Justchangetextprint.printtotextpring.printout importpygame #Definesomecolors BLACK=(0,0,0) WHITE=(255,255,255) #Thisisasimpleclassthatwillhelpusprinttothescreen #Ithasnothingtodowiththejoysticks,justoutputingthe #information. classTextPrint: def__init__(self): self.reset() self.font=pygame.font.Font(None,20) defprint(self,screen,textString): textBitmap=self.font.render(textString,True,BLACK) screen.blit(textBitmap,[self.x,self.y]) self.y+=self.line_height

194

defreset(self): self.x=10 self.y=10 self.line_height=15 defindent(self): self.x+=10 defunindent(self): self.x=10

pygame.init() #Setthewidthandheightofthescreen[width,height] size=[500,700] screen=pygame.display.set_mode(size) pygame.display.set_caption("MyGame") #Loopuntiltheuserclickstheclosebutton. done=False #Usedtomanagehowfastthescreenupdates clock=pygame.time.Clock() #Initializethejoysticks pygame.joystick.init() #Getreadytoprint textPrint=TextPrint() #MainProgramLoop whiledone==False: #EVENTPROCESSINGSTEP foreventinpygame.event.get():#Userdidsomething ifevent.type==pygame.QUIT:#Ifuserclickedclose done=True#Flagthatwearedonesoweexitthisloop #Possiblejoystickactions:JOYAXISMOTIONJOYBALLMOTIONJOYBUTTONDOWNJOYBUTTONUP JOYHATMOTION ifevent.type==pygame.JOYBUTTONDOWN: print("Joystickbuttonpressed.") ifevent.type==pygame.JOYBUTTONUP: print("Joystickbuttonreleased.")

#DRAWINGSTEP #First,clearthescreentowhite.Don'tputotherdrawingcommands #abovethis,ortheywillbeerasedwiththiscommand. screen.fill(WHITE) textPrint.reset() #Getcountofjoysticks joystick_count=pygame.joystick.get_count()

195

textPrint.print(screen,"Numberofjoysticks:{}".format(joystick_count)) textPrint.indent() #Foreachjoystick: foriinrange(joystick_count): joystick=pygame.joystick.Joystick(i) joystick.init() textPrint.print(screen,"Joystick{}".format(i)) textPrint.indent() #GetthenamefromtheOSforthecontroller/joystick name=joystick.get_name() textPrint.print(screen,"Joystickname:{}".format(name)) #Usuallyaxisruninpairs,up/downforone,andleft/rightfor #theother. axes=joystick.get_numaxes() textPrint.print(screen,"Numberofaxes:{}".format(axes)) textPrint.indent() foriinrange(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,"Numberofbuttons:{}".format(buttons)) textPrint.indent() foriinrange(buttons): button=joystick.get_button(i) textPrint.print(screen,"Button{:>2}value:{}".format(i,button)) textPrint.unindent() #Hatswitch.Allornothingfordirection,notlikejoysticks. #Valuecomesbackinanarray. hats=joystick.get_numhats() textPrint.print(screen,"Numberofhats:{}".format(hats)) textPrint.indent() foriinrange(hats): hat=joystick.get_hat(i) textPrint.print(screen,"Hat{}value:{}".format(i,str(hat))) textPrint.unindent() textPrint.unindent()

#ALLCODETODRAWSHOULDGOABOVETHISCOMMENT #Goaheadandupdatethescreenwithwhatwe'vedrawn. pygame.display.flip() #Limitto20framespersecond

196

clock.tick(20) #Closethewindowandquit. #Ifyouforgetthisline,theprogramwill'hang' #onexitifrunningfromIDLE. pygame.quit()

197

PiClub 192
HeresaroughlistofwhathappenedatPiClub,attendance,issues,problemsetc.

Session1BasicSetup(Network)andMinecraft(anEasyWin)
Whatworked
Explaintokidstheyneedafewcommandstogetthemworkingonthenetwork! Givingkidsmemorycardstolookafter/keepingholdofthosekidsdidnotwanttotakeaway. Givingkidssmallidentifyingsticker(frommy1.99Legostickerbook)Putthemonthecardssothey knowwhosiswhos.Getcardsstoredinlittlewallettocarryaround! Getkidstouseeveryothercomputerinmyroomsetup,thentheycanopenthisdocumentontheother asareference. SortoutmemorystickofAwesome(withstuffneededtobepassedaround) NicetoseesomekidsbringingtheirOWNPis!!!!

Session2USBRocketLaunchers
Gotout4newUSBRocketLaunchersexplainedaboutcommandsetc.Gotthemtoacquirefilesetc.

Issues
Gettingallthedartsback!(althoughmostkidsafterexplinationandcostwerevery,verygood!) NotenoughUSBHubs(mustbuy2more!) Notenoughexposed/accessiblepowersocketsforhubs. 2oftherocketlauncheronlyseemtofirefromcertainhubs,theydmove,butnotfire!

Session3Quake3andEmulation(DGEN?)
Quake3Basicinstall! Compilingyourowncode! DGen(testifthisworkviaasmbget!) Games. DiscusslegalityofROMsandfullversionofQuake3.

Suggestions:
Currentlysomeofthestuffinthisdocrequiresaccesstositeslikedropboxetcthatareblockedbythe schoolproxy.ItriedworkingaroundthiswithGDrive,butitsarealfaff.IstumbleduponasolutionthatI thoughtwasreasonable.Setupyour/home/pi/folderasaSAMBAshare,(seeguide),thengetthekidsto installSAMBA,youcanthenusesmbgetratherthanwgettograbfilesdirectlyfromtheMasterPi! (insteadofjusttheAWESOMEPendrive).

WhatWorked.:
smbgetdidwork,evenwhenthePiwasrunningasaserver!Problemsarosewhenthekidshadnt expandedtherootfstofillthecardandacoupleofthecardsgotfull.4GBisntTHATbig!Get8GBsif 198

youcan.Oneortwocardshadabitofcorruption,thisseemstohappenifyoupowerthePisviaUSB andconnectthemuptoahighdraindevice,liketherocketlauncher???Q3Areanawasgoodfun,we discussedcustomservers,evenrantheoneatthefrontasadedicatedserver,evenbetterwhenone brightsparkrealisedhecouldKICKpeopleoffusingvariouscommands(Iwouldnthavethoughtofdoing that!)

Whatdidntwork:
DGen/Snes9xDespitethesetupoftheMegadrive2withSonic2andthePirunningDGen(thatseems wellfussywithSDLDispMax(stillcantrunonmyowncard!).Ididntexplainthisverywell.Suggestkids goawayandfindmodels.Onekidsuggestedhesliketocreatehisown(offthebackoftheminecraft skinning,assumingitwasjustJPGfilestoedit!)Iexplainedhedneedtolearnalittle3dmodelling.I mightseeifIcanfindaguidonthis!(PerhapsSketchuptoQ3Arean!)Ididofferrewardsforkidsthat emailedmelinkstolevels/Mods,gotonetotheSimpsonsneighbourhood,howeverthiswouldnotrun onthePiduetothememorylimitations,nothingelse!ButIdidfindsomecollectivemappacks, lvl_10th_Anniversarypack,seemedtobequitegood.Willhaveaplaywithsomemodifiersperhapstry runningTheDarkConjunctionmod.(nowIhaverealisedwhattheBATfilesdo!,justcallthestandard quakeexe(orinthiscase.arm)withsomearguments!)OneissueIfoundwithQ3onthewhiteboard wastheteenytinyconsolefont(inQ3console,nottheBASH!).

Session4BreakoutBoard(s),Wiringbits?
Suggestions:
ScreamingJellyBaby? IntrotoPython?

WhatWorked:
BythistimeIvehadacoupleofstudentaskingaboutsettingupwirelessadapters(asmostroutersare oftenawayfromtheirrooms!).ThefirstonewasasimpleenableinXanddisabletheschoolbitsin /etc/apt/apt.conf(#outtheschoolproxy).Thesecondwasissuesinstallingdrivers???Stillunsovled,but workingonit.Asmallergroupthistime(dueto2weekabsenseandschooltriptoHolland!).Talkedthe brieflythroughtheproject.IntroducedtheCobblerKit,orbits,showedthePins,explainedtheyrean interacetotheoutsideworld.Printedoff5copiesoftheSingingJellybabyOCRWorksheetasabasis. ThemoreablestudentswereEAGERtogetgoingonthis,onegotthroughveryquicklyandmovedon. Anotherfollowedthisuplaterandthentriedexpandingupontheidea,butwantedtochangethetext colourintheTerminalofhisoutput(foundapythonplugincalledcolorama),Withabitoftweakinggot thisdone!BythispointthosenotinterestedintheGPIOetcwereabletogetupandrunning/networked onQuake3orMinecraftwithoutmuchassistance.KeepbackinguptheSDCardImage!

WhatDidntWork
Formanythiswastheirfirstintroductiontowritingpythonscritps,somestruggledwithsyntax.Ididnt explainaboutTabbingyourcode(acrossthepageforloopsetc).Thiscausedoneortwoissues.Should havecheckedearliertheMP3wasavailable.IfdoneagaingrabtheMP3,orcreatetheirown(HaveMIC setupforthis!).

199

Session4.5Fail.
Thiswasabitofadampsquid.Gettingbackfrom2weeksoff,unpreparedandwithoutanyresources.It wasamullingaroundsessionandkidsweredistracted.Notagreatturnout.Kidsstillnottaking ownershipofmemorycards.Needmoreincentives/rewards???

Session5RobotArm.
WhatWorked
OnepupilwaskeentotryouttheXBMCdistrohedfound.Wasabletosetupandusehisphoneas hotspot.ManagedtostreamlotsofvideosfromYouTube. LetkidslooseontheRobotArmsthatIdgotviaSTEMbudget,theyrefuntobuild,butthekidsneed *SOME*support.Howeveroneortwostudentsreallyenjoyedcreatingthem.Hopedtogetthemhooked uptoPisbutranoutoftime.ManagedtogetthecodeforittoworkwithPS3Pad(WiredIassume!)But thenforgotthePS3pad.FoundaYear11tofetchoneatlunch.Buttheynevercameback.:((Dontrely onYear11sforkit!)Years79morereliable.Howevetheyrenotallowedoffsite.

Whatdidntwork.
Forgettingequipment.Havemultiplesofeverythingforusage?Thisisoneoption.Needtowriteupmore tutorials,getlaptopsthatwerepromisedsocandoSSH,agreatwayofgettinglargechunksofcode quicklyonthePis!Schoolwontletitbeinstalledonthedesktops!Boo.SecurityRiskApparently!

Session6PiCamera.
WhatWorked
Demonstratedthecamera,hadabriefdiscussionabouttheCamera,whynotUSB,thefactusesfast bus.Lookedatthephysicalcamera,commentedonsize,comparedittophonecamera.Demodit doingbasicphotocapture,thenabitofvideocapture.Themagicwaskeptaliveasthiswasdone throughthemagicofWinSCPwhichallowedquickaccess/viewingofphotos.Nicethathadayear9 tryingtodownloadQuake3Mods,heeventually(throughtheschoolproxy)foundafew.Thenhad discussiononhowtogetthisontoQuakeonthePi,discussedhowAWESOMEwgetcommandwas, thenviaSSHenabledbrowseraccessonthePi(thisisdifferenttojustusingtheproxyatthebash!)and hebrowsedonthePi,foundthefile,downloadedthelink,unzipped,putonthepiandtested!He managedtofindagoodlevelthatwasaDJDeck,ifyoustoodonthedeskyouspun!!!Hadonekidsstill buildingrobotarm,thishastakenhimnearly4sessions,butisalmostcomplete!Theotherbrightspark wantedPiClubstickers,sowekilledatreegoingthroughpublisherliningupmarginsetc,onlytofinally printonthelaserandwasbadlyaligned,butthechildlearntquitealotaboutPublisher,borders,paper etc.

Whatdidntwork.
Wantedtotrystopmotioncaptureandpossiblywebstreaming.Thiswouldhavebeenbrillianttoget studentsnextdoor(oronanyothercomputerontheschoolnetworkviewingthecameraoutput.Ididnot howeverhavetimetogetthisworkingintheclub.(furtherreadingandfiddlyconfigurationshoudlhave beendonebeforetheclub.KidsweremarvelledatlegocasethatIhavemyPiin,perhapsprovidetutorial PDFofinstructions. 200

Session6.5AShortPiClubduetomeetingsandothercommitments.
TalkedaboutTorrents(Legaldownloadingoflargefiles)astriedtodemonstratehowIcouldnotdownload CrunchBangatschoolviathesystemasitwasatorrentandportsareblockedatschool,sowouldhave todothisathome.WanttobeabletorunPinexttocomputersetup.Worksbetterthatway!Less guessing!DidshowthatyoucouldtakeoveranotherstudentsPibySSHingtoit.

WhatWorked
GettingkidstologontoPCsandsetupPisrelativelyquickly. GettingkidstowritetheirIPAddressesonthewhiteboard! Itsworthdownloadigusefulvideos,theGigafide(Tinkernut)YouTubeonhowtohackminecraftisuseful andfunnytoo.wellworthgrabbingforlateruse.http://www.youtube.com/watch?v=YsXumCkcxLw

Whatdidntwork
TheGithubseemedblockedatschool!(sighanotherissue!) Hadlotsoftroublesettingupmyend(laptop,andprojectscreenhardlyvisibleinthebrightlight!

Session7MinecraftHackingonthePiusingPythonScripts?
POAGetMinecraftrunningonthePiscreateacoupleofcustomsimplescriptstoallowpeopletohack minecraft,demonstratehowtogetthePyScriptsfromthesite(havethemdownloadedalready,justin case!)thenrunviaSSHforextraawesomeness??? WhatWorked WhatDidntwork.

Session8PiFM(PirateRadio!)
POAGetstudentstoseehowsimpleitistogetFMsignalfromaPi. Getstudentstorecordapieceofaudio(converttocorrectformat!) Getthemtoplayitbackout,possiblywriteascripttomakethesignallooproundandround(perhapsa Zombietestmessage?LikeIdid.) SetupLiveMicExample(testedandworking). Getthemtorunaroundtheschooltestingjusthowfarthesignalwillgo.Alsofreakoutrandomstudents ifyouhaveagoodclearviewoftheatrium!

Session9Twittering
ThisrequiresthestudentstohaveAccesstoTWITTER!(otherwisethetwitterAPIwillnotwork!) ShowthemhowyoucalltheAPIeachtimewithusefulbitsofinfo!

201

COSTOFSTUFF/PRICEGUIDE 196
Product
RaspberryPi. SuitableAdapterPlug HDMICable HDMI>DVICable USBHub(Powered) Keyboard PS3ControlPad Mouse BluetoothAdapter WirelessAdapter PrototypeBoardKit CobblerInterfaceCable PiCase MemoryCards8GB USBRemoteControl TextstarLCDModule RemoteATVTheBear(kit,with3xMotors) AssortedElectronicComponents(Chipsand LCDsetc) JumperWires(MotherboardtypeforLCD) GERTBoard RandomLCDDisplaysHitachiHD44780LCD controllerCompatible MotorDriverChipsandBreadboardBreakout Bits RobotArm(USB) PiCar

Vendor
Farnell Farnell/RS (ASDAVALUE) EBay EBay/Amazon. Generic(GoWilkinsons/Similar) Amazon(MustbeGenuine!) Generic Poundland Amazon(Edimax) Ebay Adafruit SKPang www.MemoryBits.co.ukorwww.7dayshop.com Play.com/Ebay CoolComponents www.IWoot.com Maplins Maplins www.farenell.com Ebay

Approx Cost
30.00 5.00 3.00 3.00 7.00 5.00 30 5.00 1.00 8.00 10.00 8.50 12.50 7 5.00 28.00 20.00 10.00 3.99 40.00 20.00

LEDStripLights(12volt) ArmtelBoard(forlighting)NooGrooveUSB BoardATMEGA32U2(AT90USB162)AVR Stick Ebay 11 New5V8ChannelRelayModuleBoardfor ArduinoPICAVRM Ebay 6.00 SolarCharger Online(Paypal)[email protected] 20.00 PS3Eyetoy LEDBorg 3.5"TFTLCDCarRearViewMonitorColor ScreenDVDVCRForCarBackupCamera DreamCheekyUSBRocketLauncher TVTuner(USB)AugustDVBT205USB FreeviewTunerStick Game(2ndHand) http://www.piborg.com/ledborg Ebay 2 5 12.03

http://www.hobbytronics.co.uk 18.00 Maplins 30.00 PiCar.com 30.00 Ebay(user http://myworld.ebay.co.uk/gomepls?_trksid=p2047675.l25 59) 4.00

Amazon. Amazhttp://www.amazon.co.uk/gp/product/B002EHVP 9C/ref=oh_details_o00_s00_i00?ie=UTF8&psc=1on

29 15

DCPowerSupply(312V) PebblePowerSupply ForwardPowerTubePhoneBattery

Wilkos Scan.co.uk Scan.co.uk

5 14 9

202

PiBowCase CamerMount PiHeatsink PiNoodleCable PiVesaMount(Slice) CheapPocketRadiototestPiFM PiHub

www.pimoroni.com thepihut.com thepihut.com thepihut.com thepihut.com Poundland http://shop.pimoroni.com/products/pihub

13 3 1 3 5 1 25(inc shipping) 3

BurgerSpeakers(USBChargeandfitted audiojack.)

ebay

203

LinuxMiniGuide(forLaptop/PC)

198

HereisjustwhereIwilljotdownsomeexperiencesthatIvehadsinceIvebeenboldenoughtodabble withLinuxonDesktops/Laptops. IdrecommendyoustartwithLiveUSBs/DVDs. IvetrieddifferentDebianbaseddistros. Ubuntuseemsprettyfriendly,butdidntworkverywellonoldtech. LinuxMintseemsstableandworkswithmanythingsoutofthebox!

CreateaLiveUSBwithPersistance.
Thismeansyoudontloosethesettingsyouvedone/createdeverytime. ThissoftwareLILILinuxLiveUSBCreatorallowsyoutoaddpersistancetoalivelinuxdistro(Currently TestingwithMint!)

HowtoEnableSSHonLinuxMint15/14/13/12
IhavenoticedthatalotofpeopledonotknowhowtoenableSSHonLinuxMintsystems,soIhave decidedtomakethisarticle. ToenableSSH(secureshell)onLinuxMint15Olivia,LinuxMint14Nadia,LinuxMint13MayaandLinux Mint12,allyouhavetodoisinstalltheSSHpackage,whichisopensshserver.
sudoaptgetupdate sudoaptgetinstallopensshserver

sudopasswdmint <enteranewpassword!>

VNConLinuxtoPi
InstalltheVNCViewersoftware
sudoaptgetinstallvncviewer vncviewer<ipaddressofpi>:1

204

You might also like