12.07.2015 Views

Steady Hand Fun With The Raspberry Pi - Adrirobot

Steady Hand Fun With The Raspberry Pi - Adrirobot

Steady Hand Fun With The Raspberry Pi - Adrirobot

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

IISSUE 05 ­ SEP 2012A Magazine for <strong>Raspberry</strong> <strong>Pi</strong> UsersAlso in this issue<strong>Steady</strong> <strong>Hand</strong> <strong>Fun</strong><strong>With</strong> <strong>The</strong> <strong>Raspberry</strong> <strong>Pi</strong>Tutorial by Mike CookSqueezy or Wheezy?DebianDistro'sExamined<strong>Raspberry</strong> <strong>Pi</strong> Media CentreA Guide To OpenELEC and Raspbmchttp://www.themagpi.com<strong>Raspberry</strong> <strong>Pi</strong> is a trademark of <strong>The</strong> <strong>Raspberry</strong> <strong>Pi</strong> Foundation.This magazine was created using a <strong>Raspberry</strong> <strong>Pi</strong> computer.


Contents04 STEADY HANDSAre your hands stready enough to beat the <strong>Pi</strong>? by Mike Cook07 ENVIRONMENTAL MONITORINGTrack temperature fluctuations. by Duncan Rowland.1 0 WHAT'S ON GUIDE & COMPETITIONFind out where <strong>Raspberry</strong> Jams' are happening and win a starter kit1 2 XBMC: Raspbmc and OpenELECGet to grips with your media centre setup. by Colin Deady1 6 SQUEEZE VS WHEEZYImprovements and changes. by Jaseman1 8 COMMAND LINE CLINICLearn how to backup important data. by Bobby (bredman) Redmond20 C CAVE<strong>Fun</strong>ctions, pointer and text file encryption. by W. H. Bell & D. Shepley24 THE SCRATCH PATCHProgram your own Simon says game. by Antiloquax26 48HR RASPITHONBen, Luke, Ryan and Edward recount their python challenge.27 THE PYTHON PITGradient fills, and using maths to plot points of a circle, by Jaseman32 FEEDBACK & DISCLAIMER3


STEADY HANDSYou don't have to get complicated to get a great deal of funfrom an interfacing project. Electrically this is just about assimple as you can get, however it has a very good fun totechnology ratio.DIFFICULTY: INTERMEDIATE<strong>Steady</strong> hands is a very old game, however,with a <strong>Raspberry</strong> <strong>Pi</strong> we can give it a new twist.<strong>The</strong> idea is that you have to guide a wire loopalong a bendy wire without making the twotouch. You can make this as complex or aseasy as you like by having more bends in thewire or having the loop smaller.Materials-Bare single core Wire (2mm Dia)e.g. Metal coat hanger. If using wire itneeds to be thick enough to hold its shape.-Stranded wire (insulated)-Block of wood (size depends on yourdesign of 'bent coathnager')-Electrical TapeTools-Drill-Drill Bit (just smaller than the diameterof the wire)-Solder-Soldering IronA - Physical pin 7 GPIO pin 4B - Physical pin 3 GPIO pin 0C - Physical pin 5 GPIO pin 1D - Physical pin 6 Ground<strong>The</strong> Construction1 . Drill holes in the wooden block for the 'bentcoathanger/wire' just smaller than thediameter of the coathanger/wire so that thewire will hold itself up. Make sure to space thetwo holes far enough apart to accomodateyour design.2. Make the wire loop and solder a length ofwire to it. You might want to add a covering ofinsulation tape, or better self amalgamatingtape, over the end you hold.3. Put the 'bent coathanger/wire' through thewire loop and then into the wooden block.4. Solder a length of stranded wire (insulated)to one end of the 'bent coathanger/wire'.5. Drill two holes on either side the bentcoathanger/wire as shown in the image belowfor the rests.6. Put two short lengths of coathanger/wire toact as rests in these holes. <strong>The</strong>se will detectwhen the game starts and when the wireloopreaches the end. Bend them so the loop willrest against them without shorting out to thebent wire.4


7. Solder a length of normal wire (insulated) toeach end stop.8. On each end of the 'bent coathanger/wire'and both rests, from where they hit the blockof wood, tape them with insulated electricaltape 4 cm high.<strong>The</strong> following table, and image, show howeach part of the 'STEADY HAND' attaches towhich pin of the PI GPIO via the 2.54mmheader:STEADY HANDPI GPIOWIRE LOOP GROUND - PIN 6BENT WIRE GPIO 1 - PIN 5START REST GPIO 4 - PIN 7END REST GPIO 0 - PIN 3First of all the three lines must be set up asinputs. <strong>The</strong>y boot up as inputs anyway but it isalways good practice to initialise the lines youwant to use.I used the GPIO numbers and not the physicalpin numbers in the code as I strongly believethat using physical pin numbers is actually nota sensible thing to do, and not a good way toteach children. It's like the ITA (InitialTeaching Alphabet) mistake all over again.<strong>The</strong> game is in three phases:1 ) Wait until the loop is placed on the startrest.2) Wait until the loop is removed from the startrest.3) Time the interval from lifting it off the startrest until it reaches the end rest. While it is inthis phase monitoring the bendy wire fortouches.This is then repeated forever, so a control C isneeded to stop the program.This is just the bare bones of what is possible.I always think a good way to learn anything isto extend and modify from a base. This is yourbase.One extension would be to add a soundwhenever the bendy wire is touched. <strong>The</strong>August issue of the Mag<strong>Pi</strong> showed you how toincorporate sound effects into a Pythonprogram, so take those bits and graft theminto this program.<strong>Raspberry</strong> <strong>Pi</strong> Physical <strong>Pi</strong>nsHow does the GPIO work?Basically we have three signal wires and aground. Using GPIO 0 & 1 means that a pullup resistor is already connected on the <strong>Pi</strong>, justleaving GPIO 4 to have either an external pullup attached or activating the internal pull upresistor. I opted for the latter option.<strong>The</strong> Program<strong>The</strong> software was my first venture into writingin the Python language. It is quite straightforward.You could also keep track of the high scorer,or even have a table of high scores along withthe names. You can make that permanent bywriting it out to a file and reading the file whenthe program first starts up.You can add penalty points into the time, say3 seconds per point to give a single figure. Ona more practical level, see if you can abort atimed run when the loop is placed back on thestart loop.<strong>The</strong>re is plenty of scope for adding your ownrefinements. Have fun.Continues on the next page5


# python3# <strong>Steady</strong> hands gameimport R<strong>Pi</strong>.GPIO as GPIOimport time# use BCM GPIO numbering ­ use anything else and you are an idiot!GPIO.setmode(GPIO.BCM)# set up GPIO input pins# (pull_up_down be PUD_OFF, PUD_UP or PUD_DOWN, default PUD_OFF)GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP)# GPIO 0 & 1 have hardware pull ups fitted in the <strong>Pi</strong> so don't enable themGPIO.setup(0, GPIO.IN, pull_up_down=GPIO.PUD_OFF)GPIO.setup(1, GPIO.IN, pull_up_down=GPIO.PUD_OFF)print("Hi from Python :­ <strong>Steady</strong> <strong>Hand</strong>s game")delay = range(0,5000)dum = 0start_rest = 4end_rest = 0wire = 1while True:#wait until the wand is at the startprint("Move the loop to the start rest")while GPIO.input(start_rest) != 0:time.sleep(0.8)#now we are at the start of the bendy wireprint("Start when you are ready")#wait until the loop is lifted off the wirewhile GPIO.input(start_rest) == 0:time.sleep(0.1)print("Your off")#time the run to the other restpenalty = 0run_time = time.clock()while GPIO.input(end_rest) != 0:if GPIO.input(wire) == 0:penalty = penalty + 1print("Penalties total", penalty, " points")time.sleep(0.07)score = time.clock() ­ run_time + (penalty * 0.07)print("<strong>The</strong> run time was", score, "seconds with", penalty, "Penaltypoints")#finished a run so start againPYTHON VERSION: 2.6.6 / 3.2.2PYGAME VERSION: 1.9.2a0O.S.: Debian 6 / Win7Hope you give it a go. Have <strong>Fun</strong>.Article by Mike Cook6


DIFFICULTY: INTERMEDIATEDr Duncan Rowland – University of LincolnThis article builds on topics fromprevious issues of <strong>The</strong> Mag<strong>Pi</strong> and showshow to add a temperature sensor to your<strong>Pi</strong> together with a simple method torecord and display the data on the web.<strong>The</strong> temperature sensor used is the ‘tmp1 02’(http://www.ti.com/product/tmp1 02) andconnects via the i2c bus (i.e. the same wayRob McDougall connected his accelerometerin last month issue). <strong>The</strong> temperature sensoris readily available already mounted on abreakoutboard(http://www.sparkfun.com/products/941 8) sowith the addition of some header pins it can bepushed straight onto a breadboard forprototyping (see photos). <strong>The</strong> recentlyreleased Raspbian build (201 2-07-1 5-wheezy-raspbian) now already has the i2cmodules included and the firmware is ready togo too.Starting with a fresh install, the instructionsthat follow do not require the graphical userinterface, so you can boot your <strong>Pi</strong> and use aterminal window and keyboard or remotelylogin via ssh as you prefer.First we need to install the tools for talking tothe i2c bus:sudo apt-get updatesudo apt-get install i2c-tools<strong>The</strong>re are a couple of modules we need to add(i2c-bcm2708 and i2c-dev). You can eitherinclude then manually by issuing the following‘modprobe’ commands (in which case you willneed to do this each time you reboot); or youcan add them to the file ‘/etc/modules’ (inwhich case they will be loaded automaticallywhen you reboot):sudo modprobe i2c-bcm2708sudo modprobe i2c-devFinally, so that you can read from the i2c bus,you need to add the pi user to the i2c usergroup (after which you will need to logout andlog back in for the change to take effect).sudo usermod –a –G i2c pilogoutIf you have correctly connected your tmp1 02sensor (as shown in the photos) it should nowbe accessible to you on the i2c bus when youlog back in.7


Wiring Connections:Tmp102PI GPIOGND PIN 06 (Ground)SCL PIN 05 (I2C0_SCL)SDA PIN 03 (I2C0_SDA)V+ PIN 01 (3V3 Power)ALT leave disconnectedADD0 GNDawk ' {printf( " %. 2f\n" , ( a=( \" 0x" substr( $1, 5, 2) substr( $1, 3, 1) ) *0. 0625 \)>1 28?a-256:a)}'Now you should be able to communicate withthe device.i2cget -y 0 0x48 0x00 wThis will read the value in address (0x48) oni2c bus (0) which is the current value of thesensor. <strong>The</strong> datasheet referenced aboveshows how to convert this hexadecimal valueinto degrees centigrade, and the following awkscript performs this task.awk ' {print( \( " 0x" substr( $1, 5, 2) substr( $1, 3, 1) ) *0. 0625) \}'Essentially what this does is to reorder the bits(using sub-strings) and appropriately scale theresulting value for degrees. It can becombined with the first command using a pipe‘|’ which takes the result of i2cget and sends itto awk. i.e.i2cget -y 0 0x48 0x00 w | \awk ' {print( \( " 0x" substr( $1, 5, 2) substr( $1, 3, 1) ) *0. 0625) \}'<strong>The</strong> following wraps this in a bash script so itcan be run from the command line (with aslight adjustment to the output to force twodecimal places and a newline). Make a newfile called tmp1 02.sh and add the following:#! /bin/bashi2cget -y 0 0x48 0x00 w | \awk ' {printf( " %. 2f\n" , \( " 0x" substr( $1, 5, 2) substr( $1, 3, 1) ) *0. 0625) \}'To correctly calculate negative temperaturevalues the follow change to the awk scriptmust be made:To make the script executable you need totypechmod +x tmp102. shand you can run it by typing:. /tmp102. shOne fun thing to do with this data is to send itto the “Internet of Things” web service COSM.This will store your data and plot graphs thatcan be embedded in a web page. We canautomatically run the process every minute orso and send the value to COSM. First you willneed to login and create an account onhttp://cosm.com. Once you’re verified (viaemail) you can make a new “Device” (aka“Feed”). Click on the word “Adding” and then“Something Else” to create a feed for your <strong>Pi</strong>.Select “No, I will push data to COSM” and fillout the rest of the configuration as you’d like(a good title would be something like “My<strong>Raspberry</strong> <strong>Pi</strong>”. You will receive a “feed ID”which you will need to send updates. In the“update.sh” script below you should put thisvalue where I have left XXXXX.Next we need to define a “Datastream” for thisfeed. In the console click on “+ Datastream”and enter the required data (e.g. ID =Temperature; Symbol = ° C). <strong>The</strong> ID youspecify will need to be provided when yousend updates. In the blank.json data templatebelow, you should put this where I have theentry YYYYY.Finally, we need a key that gives uspermission to post updates to the COSMserver. Go to the Keys section (situated in the8


top-right corner in a drop-down menu next toyour name) and click “+ Key”. Choose a labeland leave the Feed Restrictions as the default“Use any public feed” and Access Privilegescan be set to all. <strong>The</strong> key that is generated is along string of characters and this is required toauthenticate updates. In the “update.sh” scriptbelow you should put this value where I haveleft ZZZZZ.<strong>The</strong> COSM server expects data in a specificformat. Save the following in a file called“blank.json” (remembering to replace thevalue YYYYY with your datastreams ID).{}" version" : " 1. 0. 0" ," datastreams" : [{" id" : " YYYYY" , " current_value" : " T1" }]#! /bin/bashwhile true;dotemp=$( . /tmp102. sh)cat blank. j son | sed ' s/T1/' $temp' /g' > \send. j soncurl --request PUT \--data-binary @send. j son \--header " X-ApiKey: ZZZZZ" \http: //api. cosm. com/v2/feeds/XXXXXsleep 60doneYou can stop the update.sh script by pressingCtrl+C. If you would like to leave the scriptrunning in the background after you havelogged out, then you can run the script like thisinsteadnohup . /update. sh > /dev/null &and when you log back in, stop it by typingkillall update. shYou can now create a new update.sh scriptfile as below incorporating the values for yourdevice ID (XXXXX) and your authenticationkey (ZZZZZ). <strong>The</strong> script is essentially thesame as our previous efforts, with a couple ofadditions. First, the template data file“blank.json” is sent to the “sed” commandwhich replaces the “T1 ” with the temperaturevalue from the sensor. Second, “curl” is usedto send the newly created data-file (send.json)to the COSM server. You will need to makethe script executable as before (chmod +xupdate.sh) and run it (./update.sh). All thingsbeing well your <strong>Pi</strong> should be sending regularupdates to your COSM data feed, you can askCOSM to plot this on as an embeddable graphby clicking the cog and selecting “GraphBuilder”.9


Want to keep up to date with all things <strong>Raspberry</strong> <strong>Pi</strong> in your area?<strong>The</strong>n this new section of the Mag<strong>Pi</strong> is for you! We aim to list <strong>Raspberry</strong> Jam events in yourarea, providing you with a R<strong>Pi</strong> calendar for the month ahead.Are you in charge of running a <strong>Raspberry</strong> <strong>Pi</strong> event? Want to publicise it?Email us at: editor@themagpi.comE-DAY @ GATESHEADWhen: 29th SeptemberWhere: Gateshead LibraryMakerspace Newcastle will deliver a <strong>Raspberry</strong> <strong>Pi</strong> intro/workshop.Our aim is to encourage adults and children over 1 0 to, find out more aboutand, engage with technology.To this aim we also have other groups/people taking part such as:- Vector 76 Avatar workshop- Gateshead CLC ipad and lego robotics- Makerspace 3D printers- A local group who will be working with retro gamingMelbourne AustraliaWhen:Where:<strong>Raspberry</strong> Jam1 st Saturday of the month &Thursday of the third week of the monthDetails at http://www.meetup.com/Melbourne-<strong>Raspberry</strong>-Jam/Still cranking up the regular meetings, but we have held a couple of ad hoc meetingsalready.SheffieldWhen:Where:<strong>Raspberry</strong> JamLast wednesday of the month. 6:30-8:30PM1 st Floor, <strong>The</strong> Workstation,Grinders Hill / Brown Street,Sheffield, S1 2BX, UKHosted by GISThub10


AUGUST COMPETITIONThis month <strong>The</strong> Mag<strong>Pi</strong> and PC Supplies limited are proud to announce yet anotherchance to win some fantastic R­<strong>Pi</strong> goodies!First prize will recieve the following:Limited Edition Mag<strong>Pi</strong> CaseHDMI CablePower SupplyAudio CableVideo CableGPIO CableNetwork Cable32GB SDHC Card with Raspbian<strong>With</strong> two runners up winning a Mag<strong>Pi</strong> engraved case!For a chance to take part in this months competition visithttp://www.pcslshop.com/info/magpiClosing date is 20/9/2012.Winner will be notified in next month's magazine and by email. Good luck!Last Month's Winner !Congratulations to last month's winner DAVID HARPER from DOVER.We will be emailing you soon with details of how to claim all of those fantastic goodies!11


XBMC Media Center:OpenELEC and RaspbmcA low power <strong>Raspberry</strong> <strong>Pi</strong> media centre equipped withHDMI and capable of high definition 1080p outputAs more people are looking to access theirmedia catalogue via their computer or TVwithout the use of physical media, the freelyavailable XBMC is an ideal solution. XBMC isknown as a 1 0-foot GUI: you can comfortablysit on your sofa across the room and clearlyview the user interface on your television.We will look at the two main XBMCdistributions available for the <strong>Raspberry</strong> <strong>Pi</strong>covering installation, configuration, videoplayback, accessing YouTube, using CEC oran Android mobile phone as a remotecontroller and AirPlay. XBMC has a largefeature set only a subset will be covered in thisarticle. To find out more point your browser at:http://xbmc.org .OpenELEC and RaspbmcOpenELEC (www.OpenELEC.tv)provides source and pre-builtimages and is built from scratch asa dedicated media centreappliance. <strong>The</strong> filesystem is readonlywhich increases robustness but meansadditional software must be installed fromwithin XBMC, which is inline with OpenELEC'sobjective to be the most user friendlydistribution available. OpenELEC is small, fastand optimised purely for running XBMC.Raspbmc (www.raspbmc.com) isbased on Raspian and developedby Sam Nazarko. What isespecially impressive is thatalthough Sam is only 1 8 he hasalready released XBMC for the AppleTVunder the name Crystalbuntu. He is nowworking his magic on XBMC for the <strong>Raspberry</strong><strong>Pi</strong>. Raspbmc's filesystem can be modifiedmeaning that you can install additionalsoftware beyond XBMC. While this hasdefinite advantages in some respects it doesmean that potential exists to install too manyservices that slow down the operating systemand XBMC, hence care needs to beexercised. Raspbmc is likewise available asboth a pre-built distribution and souce, andalso runs XBMC quickly.<strong>The</strong> OpenELEC port of XBMC began on a<strong>Raspberry</strong> <strong>Pi</strong> alpha board and likewiseRaspbmc has been under continuousdevelopment and improvement for severalmonths. A seamless XBMC experience isprovided to you for free by the considerableefforts of those involved and for this I take myhat off to the respective Developers and BetaTesters.What you will needTo get XBMC up and running you will need toconnect your <strong>Raspberry</strong> <strong>Pi</strong> to your TV overHDMI, optionally via an A/V receiver for 5.1surround sound. A USB hard drive will act asyour media source, although if you just want towatch online content such as YouTube this isnot necessary.IMPORTANT: the USB drive should have itsown power supply or be connected via apowered USB hub. <strong>The</strong> <strong>Raspberry</strong> <strong>Pi</strong>'s USBports are not suitable to power a portable USBhard drive.An additional computer is needed to installeither OpenELEC or Raspbmc onto an SDcard. Any reasonably specified computerrunning Linux can be used. Installation ofRaspbmc via Windows or Mac OS X is alsopossible.Obtaining and installing XBMCOpenELEC provides compilable source and adownloadable pre-built image (see UsefulLinks at the end of this article). You will needto prepare and write the data to your SD cardfollowing the online instructions.As OpenELEC uncompresses and boots froma read-only filesystem each time it is notpossible to change the root password afterbuilding the software (however disablingpassword logins and ussing ssh keys insteadis reportedly possible). This also applies to the12


pre-compiled image.Building OpenELEC from source may wellseem complex but it is worth attempting if youhave not compiled and installed an operatingsystem before as it is a great worked examplethat yields a genuinely useful result.Raspbmc installs from a downloadable pythonprogram (see Useful Links) on Mac OS X andLinux. On Windows executing the installer.exeis the equivalent. A base image will quicklyinstall to the SD card, sufficient to allow the fullinstallation to complete upon first bootprovided the <strong>Raspberry</strong> <strong>Pi</strong> is connected to theinternet.<strong>The</strong> first boot of each distribution takes a fewminutes (Raspbmc will be considerably longerwhile the operating system proper isdownloaded and installed), but subsequentboots take under 30 seconds..Ready to run out of the box<strong>The</strong> great thing about XBMC is that it worksstraight away: it is a good example of what isknown as a black box(http://en.wikipedia.org/wiki/Black_box). Ablack box is a great concept for a mediacentre appliance: just like your DVD or Blu-Ray player you should not need to care aboutthe internal workings to be able to use theinputs and outputs provided.After booting, XBMC will present a horizontalcontrol strip of options that enable access toyour media collection and other goodies(including live weather updates). Navigationby keyboard, mouse, various remote controls(including XBOX and XBOX360 controllers) oran Android phone (more on that later) issupported.For users of earlier builds of either OpenELECor Raspbmc it is worth upgrading to ensurethat you are taking advantage of recentperformance improvements. Sam Nazarko ofRaspbmc mentioned that using Raspbian withhard floating point operation support frombuild RC4 should make the Raspbmc XBMCexperience more responsive and this iscertainly the case. Gimli of XBMC andStephan of OpenELEC fame confirm that theyhave been using their own highly optimisedhard floating point build of Linux for about fivemonths which incorporates variousoptimisations as a result of user feedback andtesting leading to a steady increase inperformance. This news prompted animmediate upgrade of both of my XBMCinstallations and I can confirm that XBMC on<strong>Raspberry</strong> <strong>Pi</strong> is quick.After booting you may notice that the edges ofthe screen fall off the edge of your TV. If thishappens you need to adjust the overscansettings, which in lamens terms meansadjusting the corners of the displayed imageto ensure that all of the picture is visible.Overscan is changed under System settings /System / Video output / Video calibration byusing the keyboard's cursor keys, Enter tomove to the next option and Escape to savechanges.On Raspbmc, once overscan is set you shouldchange the default password (raspberry) forthe pi user by selecting the power icon (bottomleft) and then Exit. Quickly press Esc and youwill be directed to the shell (note that the firsttime you log in via the shell you will beprompted to configure some localisationsettings). At the command prompt enter:sudo passwd piOn Raspbmc the root user is disabled bydefault. If you need to execute a commandwith root privileges prefix it with the commandsudo. To return to XBMC type exit to return tothe login prompt and then quickly press enterfour times.Raspbmc and OpenELEC provide additionaldistribution-specific configuration optionsunder the Programs menu to configurenetworking and automatic updates. This maybe especially useful if your <strong>Raspberry</strong> <strong>Pi</strong> failsto obtain an IP address via DHCP.Setting the default time<strong>The</strong> <strong>Raspberry</strong> <strong>Pi</strong> automatically sets the dateand time from the internet. However thetimezone may be incorrect and the time maynot take account of Daylight Savings Time (orBritish Summer Time). This can easily be fixedby selecting System settings / Appearance /International and changing the Timezonecountry from the default "Aaland Islands" toyour local timezone.Add-ons for allVideo Add-ons exist for a large variety ofservices including CNET Podcasts, Engadget,ESPN Video, Redbull.tv, TED Talks, YouTubeand many others. <strong>The</strong> full list is available viathe Videos menu / Add-ons / Get More option.Installing YouTube took only 1 5 seconds forexample. Likewise Music and <strong>Pi</strong>ctures alsoprovide Add-ons that are well worth exploring.Each creates an additional option under therelevant Add-ons section. Online video qualitycan vary, but having the enormous selection13


that XBMC provides access to greatlyincreases the media centre's capabilites.Installing extra software onRaspbmcInstalling additional software on Raspbmcoutside XBMC is possible. As noted earliercare should be taken not to install too manyresource hungry services that may impact onthe performance of XBMC. Backup the SDcard before installing extra software by usingthe dd command (instructions for this are easyto find with a Google search).To install extra software on Raspbmc exit tothe command line and type:sudo apt­get install Whatever the WeatherXBMC provides weather information from themain menu. It attempts to determine yourlocality, but as this is derived from yourinternet address it is likely to be fairlyinaccurate. Change location information byselecting Weather, pressing the left cursor keyto slide out the options menu, selectingSettings / General / Settings. Up to threeweather locations can be specified. You cantoggle between these via the up and downicons at the top of the slide out options menu.Weather is a good example of lateral thinkingfor the XBMC development team: while itsprimary purpose is clearly that of a mediacentre, it is capable of undertaking other tasksas well.Video formatsOn August 24th the <strong>Raspberry</strong> <strong>Pi</strong> Foundationmade both MPEG2 and VC-1 licensesavailable for purchase from the <strong>Raspberry</strong> <strong>Pi</strong>store. This functionality had previously beenomitted from the hardware to keep productioncosts to a minimum. <strong>With</strong>out these licensesthe <strong>Raspberry</strong> <strong>Pi</strong> will playback MPEG4 andH.264 video but not MPEG2 or VC-1 . <strong>With</strong> thelicenses pre-existing media libraries that wereencoded as MPEG2 or VC-1 will now play.This is a superb announcement from theFoundation(http://www.raspberrypi.org/archives/1 839).Naming your media filesWhen the USB hard disk is connected XBMCwill scan the contents looking for matchesbased on file name and year to present underMovies as noted below. For this reason it isimportant to name files in a particular way. Forexample:\Movies\Transformers (2007).mkvFull details on naming conventions for Moviescan be found on the XBMC Wiki at:http://wiki.xbmc.org/index.php?title=Adding_videos_to_the_library/Naming_files/Moviesand for TV shows:http://wiki.xbmc.org/index.php?title=Adding_videos_to_the_library/Naming_files/TV_showsimdb.com likely contains the year informationthat you need.Organising your mediaXBMC can better organise films than thedefault Videos option provides: by genre, year,actor etc, and can download fan art, displayfilm information and provide links to previews,all under a Movies option. To enable scan yourvideos as a new source:Select Videos / Files / Add Videos / Browse /Root filesystem and then the path /media/usb0on Raspbmc or /media/ onOpenELEC. Press the left cursor key andselect OK. Change "This directory contains" toMovies and finally OK to add the source.Select Refresh information for all content andyour Movie library will gradually be scannedwhich can take a while. Fortunately you cancarry on using XBMC while this process takesplace. Once completed you will see a newoption next to Videos, Movies which providesall of the added goodness.CEC and Android remote controlsBoth OpenELEC and Raspbmc now supportCEC. This means that all of your HDMIequipment that also supports CEC can becontrolled via a single remote. In XBMC youcan navigate menus, browse your media,control playback and link power settingsbetween devices with your TV remotecontroller. A good demonstration on thisfunctionality is available on YouTube:http://www.youtube.com/watch?v=XPyOyJsnB1 oIn addition to CEC support software such asXBMC Remote is available from the AndroidPlay Store (other Android, WebOS andiPhone apps are available). This also providesnavigation, browsing and playback options.Your Android smartphone needs to beconnected to the network via WiFi where-as14


your <strong>Raspberry</strong> <strong>Pi</strong> can be connected via eitherwired or wireless ethernet meaning line ofsight is not required unlike infrared. Configureas follows:- On the <strong>Raspberry</strong> <strong>Pi</strong> select Settings /Services / Remote control and enable the two"Allow programs" options. Under Settings /Services / Webserver select "Allow control ofXBMC via HTTP" and set both a usernameand password. This will permit thesmartphone to make the connection.- On the smartphone tap Menu / Settings /Manage XBMC Hosts / menu / Add Host.Enter the details you configured on the<strong>Raspberry</strong> <strong>Pi</strong>. If using a DHCP IP addressensure the router is set to reserve it for the<strong>Raspberry</strong> <strong>Pi</strong> on each boot. Also ensure theport numbers match. You can determine theDHCP assigned address on the <strong>Raspberry</strong> <strong>Pi</strong>by selecting System info beneath the mainSystem menu option.<strong>The</strong> advanced options under XBMC RemoteSettings include Show incoming SMS andShow incoming calls that enable a small popupnotification to appear on the TV when youreceive a text message or phone call. Thisdoes of course require you to keep yoursmartphone constantly connected via WiFi toXBMC which can drain your smartphonesbattery somewhat, hence keep your phone oncharge.AirPlay remote streamingXBMC supports streaming media content fromiTunes and some third party applications viaAirPlay. Enable it via System / Settings /Services / AirPlay. Although DRM protectedcontent is not supported it is for examplepossible to stream non-DRM music directly toXBMC. <strong>With</strong> AirPlay enabled iTunes shouldautomatically detect XBMC as a destination,selectable via an icon in the bottom right ofiTunes. Select XBMC, and then click play toredirect mustic to your <strong>Raspberry</strong> <strong>Pi</strong>. Yourfirewall may block AirPlay on port UDP 5353.Other featuresXBMC also provides other features that areworth investigating:- Skins (changing the default theme of XBMC)- Python widget scripting (the ability to addnew functionality to XBMC yourself- Controlling XBMC through a web browser ona different computer or tablet- Communicating with MythTV, a digital videorecorder.As always, exploration, trial and error areoften the best ways to learn new technology.In conclusionAfter using XBMC on the <strong>Raspberry</strong> <strong>Pi</strong> is isclear that each distribution is a success - thereis something inherently "cool" as well aspractical in being able to play media via the<strong>Raspberry</strong> <strong>Pi</strong> on your TV. <strong>The</strong> work that hasgone into OpenELEC and Raspbmc is trulyimpressive. Each works exceptionally well andwith continued active development it is clearthat both have a bright future ahead of them.Each provides a straightforward installationprocess with automatic updates as well ascompilable source if you need an extra level ofinitial configuration (or just want to learn howto).Both have a friendly, helpful community ofpeople supporting the core efforts. Try themboth. See which you prefer and go with it. Youwill not be disappointed in either case.Useful linksPre-built OpenELEC image:http://sources.openelec.tv/tmp/image/openelec­rpi/and associated instructions:http://wiki.openelec.tv/index.php?title=Installing_OpenELEC_on_<strong>Raspberry</strong>_<strong>Pi</strong>Build OpenELEC from source:http://wiki.openelec.tv/index.php?title=Building_and_Installing_OpenELEC_for_<strong>Raspberry</strong>_<strong>Pi</strong>Raspbmc image download:http://www.raspbmc.com/download/Raspbmc Windows installer:http://www.raspbmc.com/wiki/user/windows­installation/Build Raspbmc from source:http://www.raspbmc.com/wiki/technical<strong>Hand</strong>brake:http://www.handbrake.frAcknowledgementsMany thanks to Sam Nazarko and StephanRaue for their help in providing technicalinformation on Raspbmc and OpenELECrespectively. Also to Edgar (gimli) Hucek fortechnical information on XBMC.Article by Colin Deady15


SQUEEZY OR WHEEZY?Debian Distro's ExaminedIn this article I look at the differences between the Debian 6(Squeeze) and Debian 7 (Wheezy) distributions.SPEEDSQUEEZE (Debian 6)Things are very slow - particularly if you areattempting to run larger apps such as Scribus.STABILITYSqueeze would randomly freeze or completelylock up requiring a rebootIMAGING AND PARTITIONINGIf you have imaged Squeeze onto a larger SDCard, you will most likely want to expand thesize of the primary partition, to make use ofthe available space. This is not a very easy orfun task. <strong>The</strong> Mag<strong>Pi</strong> covered this procedurein Issue 2, but it required use of a Linux basedPC or a Linux LiveCD, and a tricky set ofinstructions for the resize using the 'GParted'application. It's an annoyance that slowsdown the installation process.MULTIMEDIAThis is probably the one area where Squeezecurrently has the edge. You can play mp3 andwma music as well as most video formats,providing you choose the right apps.OMXPlayer is good all-rounder, but cansometimes be problematic with WMA files.'avifile-player' however seems to handle WMAmusic better, but not good for video.Unfortunately development of 'avifile-player'seems to have been discontinued and it is notavailable for Wheezy.GEANY & PYTHON<strong>The</strong> programming text editor is great, butunfortunately you do have to make a smallconfiguration change to get programs toexecute from within the IDE (IntegratedDevelopment Environment). Python programsrun reasonably well.RANGE OF PACKAGESDuring the making of Issue 3, <strong>The</strong> Mag<strong>Pi</strong>tested and provided a long list of apps andgames that work on the <strong>Pi</strong> under Squeeze.INTERNETSqueeze comes with a version of Midori whichis rather limited. It struggles with manywebsites. I would recommend installing thechromium-browser which seems to work withmore websites, however the downside isslowness - the browser is rather cumbersomecompared with Midori. You can get by withGoogle's Gmail, IRC chat and Dropbox as wellas many other websites.16


SPEEDWHEEZY (Debian 7)Everything runs MUCH quicker underWheezy.STABILITY<strong>With</strong> Raspbian Wheezy the random freezingseemed to have been fixed.IMAGING AND PARTITIONINGAfter imaging Wheezy onto the SD Card, theprimary partition can be resized easily usingan in-built tool that autoloads the first time yourun the Operating System. You areconfronted with a menu which allows you toeasily configure a number of settings. <strong>The</strong>reare many options, which might look dauntingand confusing to beginners who might notnecessarily know what settings they need.<strong>The</strong> menu has other useful features allowingyou to have LXDE loaded on boot, avoidingthe login password, etc. Personally I prefer todo this manually myself as described onpages 3 & 4 of Mag<strong>Pi</strong> Issue 3 - Although thoseinstructions were written for Squeeze, theywork just as well on Wheezy.RANGE OF PACKAGES<strong>The</strong> Mag<strong>Pi</strong> have not yet tested all of theavailable Wheezy packages, but the list iscertainly a lot shorter than the number ofpackages for Squeeze. It may be possible toextend availability by adding new packagerepositories to the sources.list file. Wheezyhas it's own repository, and hopefully therange of apps will improve over time.work around this by hitting the back buttonafter each file download - A minor annoyance,unless you are going to be downloading largenumbers of files this way.MULTIMEDIAWheezy scores badly on this one. <strong>The</strong> mainproblem seems to relate to audio bufferunderrun. When playing music or videothrough the omxplayer, it will generally fallover after a minute or two. <strong>The</strong>re are otherapps which can handle wma and mp3 withoutissue, but I have yet to find a decent videoplayer that runs on Wheezy. <strong>The</strong> problemdidn't exist on Squeeze, and I suspect it hascrept in during the recompiling of Wheezypackages. <strong>The</strong> omxplayer is the backbone ofXMBC, so hopefully this will be addressed infuture releases without requiring recompiling.GEANY & PYTHONGeany is a very useful programming texteditor. Geany is no longer included by default,but can be installed using:sudo apt­get install geanyYou get a newer version than the one thatcomes bundled with Squeeze. Wheezy seemsto favour using IDLE for editing Python code.As with Squeeze, Python programs run well.Article by JasemanINTERNET<strong>The</strong> version of Midori that is bundled with theWheezy distro seems to be a hugeimprovement over the Squeeze version.Greater website compatibility means that youno longer need chromium-browser (It's goodbecause chromium-browser isn't available onWheezy anyway). I haven't spent too muchtime testing the browser, but it seems to workwell and quick. <strong>The</strong>re is a glitch whendownloading from dropbox.com, you arepresented with an error message, but you can17


18Linux commands can bejoined together to createscripts. <strong>The</strong>se scripts allowyou to create programs whichcan be just as powerful as anyother programs on the<strong>Raspberry</strong> <strong>Pi</strong>.Scripts can be very useful to hold commandsthat you need to type regularly. It can be veryinconvenient to have to type the samecommand again and again, especially if thecommand is long and complex.Let's take an example of a useful commandthat you may need to enter regularly. We willuse the example of a command to save acopy of all of your files in a safe place.Before we start writing the script, we need asafe place to put all of your files. Your files arenormally in /home/pi (assuming that you areusing the username "pi"), therefore the safeplace must be somewhere else. We willcreate a special directory called "/backup" byusing the commandssudo mkdir /backupsudo chown pi /backupWhat do these commands do?<strong>The</strong> mkdir command makes a new directory.By default, the user pi can only write to files in/home/pi, this is to prevent accidentaldamage to other users or to the system files.By adding sudo to the mkdir command, theuser pi gains the authority to create adirectory outside the normal working area.Creating the directory is not enough, to beable to completely control this directory, thechown command is used to changeownership of the directory. Now the user pi isin full control of this directory.Now we are ready to create the script. Byusing the nano editor, we can create a filenamed "backup"nano backupand we can add this (as one line) to the filecp ­­recursive ­­verbose /home/pi /backupTo save the file, press the Ctrl and o keystogether, followed by Enter. To exit the editor,press the Ctrl and x keys. This script nowcontains the command to copy files from/home/pi to /backup. <strong>The</strong> "--recursive" optionmeans keep drilling down into directories tofind files. <strong>The</strong> "--verbose" option means wewant to be told what is happening.Now we can try to run the script by enteringbash backupYou should see a list containing each file inyour directory with an arrow to the respectivebackup file.A script can contain more than one command,so we will add text messages at the beginningand end to inform us what is happening. Editthe file again and change the file to containecho "Starting backup"cp ­­recursive ­­verbose /home/pi /backupecho "Backup is finished"Try running the script again by entering thecommandbash backup


Remember, if the list of files is long, you canpipe the result through the "less" commandbash backup | lessThis turns on (+) the executable (x)permission for this file. To be correct (but notneeded in this simple example) the first line ofthe script should containYou can move through the list with up/downarrow keys or PageUp/PageDown keys,press the q key to quit.<strong>The</strong> last step is to make this script anexecutable file. This will allow you to run thescript without putting "bash" before the name.To make the file executable, enter thecommand#!/bin/bashThis tells the operating system which programshould be used to launch this script. You canlaunch the script by typing the command./backupchmod +x backupA more complete exampleHere is a more complete version of the script. You may note that it is a lot morecomplex because some extras have been added.<strong>The</strong> names of the directories are now in variables so that they can be easily changed if you wish.<strong>The</strong> script uses an "if" statement to check if the backup directory already exists.<strong>The</strong> cp command uses the --update option to avoid copying files that have not changed recently.#!/bin/bash# Simple program to make a backup of files on the <strong>Raspberry</strong> <strong>Pi</strong># Set the location of my files and the backup locationmydirectory="/home/pi"safeplace="/backup"echo "Starting backup of files from $mydirectory to $safeplace"# Check if the backup directory existsif [ ! ­d $safeplace ]thenfi# Does not exist, need to make a new directoryecho "Making new directory $safeplace"sudo mkdir $safeplace# Change owner of this directory to the user pisudo chown pi $safeplace# Copy all the files in my directory# recursive means keep drilling down into directories to find files# update means only copy files that have been changed since the last backup# verbose means I want to be told what is happeningcp ­­recursive ­­update ­­verbose $mydirectory $safeplaceecho "Backup is finished"19


Tutorial 3 - <strong>Fun</strong>ctions, pointers and files.A place of basic low-level programmingHow did you get on with the challenge problem? Let us take a quick look at the solution before continuing.Challenge solution#i ncl u de i nt mai n(){i nt nterms , term = 0, i ;pri ntf( " How many terms ? " ) ; /* As k the u s er for i npu t * /s canf( " %d" , &nterms ) ; /* Read the whol e number * /for( i =1; i 0) /* L oop whi l e x i s greater than zero * /{res u l t * = x; /* mu l ti pl y x by res u l t and as s i gn to res u l t * /x- - ; /* Decrement x by one * /}retu rn res u l t; /* Retu rn x! when x i s not zero. * /}<strong>The</strong> variable x and the return type are defined as an unsigned int, since the function cannot compute the negativefactorial of an input value. <strong>The</strong> function also uses another of the loop types, the while loop. <strong>The</strong> while loop executes20


the compound statement within {} as long as the condition between the parentheses ( ) is true.<strong>The</strong> new function can now be used in a program,#i ncl u de u nsi gned i nt factori al ( u nsi gned i nt x) ;i nt mai n(){u nsi gned i nt i = 3; /* Decl are an i nt and as s i gn i t the val u e three. * /pri ntf( " %d! = %d\n" , i , factori al ( i ) ) ; /* Pri nt factori al of i * /retu rn 0; /* Retu rn s u cces s to the operati ng s ys tem. * /}When a simple variable is passed into a function the value of the variable is copied into a new memory location. Thisnew memory location is not connected with the first memory location. <strong>The</strong>refore, if the value of x is modified inside thefunction factori al , the value of i will remain three after the function call. To change this behaviour pointers can beused.PointersUnlike simple variables, a pointer stores the address of a memory location. <strong>The</strong> memory location can be a simplevariable, or function, or structure of some sort. <strong>The</strong> type of the pointer normally has to be the same as the type of thevariable, to which the pointer points. When implemented correctly within a program, using pointers can produce moreefficient code. A pointer is declared by prepending a variable name with an asterix. For example, a pointer of type i ntcan be declared via,i nt * p = 0; /* Decl are a poi nter p and as s i gn i t a nul l addres s . * /<strong>The</strong> pointer can then be given the address of another variable,i nt i ; /* Decl are an i nt i . * /p = &i ; /* As s i gn the addres s of i to p. * /<strong>The</strong> assignment can also take place through a function call,#i ncl u de voi d fu n(i nt, i nt * ) ; /* A fu ncti on wi th no retu rn val u e. * /i nt mai n(){i nt np = 1, p = 1; /* I ni ti al i s e two i nt vari abl es * /pri ntf( " &np=%p, p=%p\n" , &np, &p) ; /* Pri nt the addres s es . * /pri ntf( " Before fu n() : np=%d, p=%d\n" , np, p) ; /* Pri nt the val u es . * /fu n(np, &p) ; /* Pas s the val u e of np and the addres s of p. * /retu rn 0; /* Retu rn s u cces s to the operati ng s ys tem. * /}voi d fu n(i nt np, i nt * p){np = 2; /* As s i gn 2 to the l ocal vari abl e np. * /* p = 2; /* As s i gn 2 to the memory of p defi ned i n mai n. * /pri ntf( " &np=%p, p=%p\n" , &np, p) ; /* Pri nt the addres s es . * /}In this example, the address of the variable p defined in the main function is passed to the pointer p in the functionfu n. <strong>The</strong> value in this memory address is then changed by dereferencing the pointer, by using an asterix in front of thepointer name. Notice, that when a pointer is declared an asterix must be used. However, when a pointer is declaredthe pointer can be assigned an address rather than a value.21


Pointers can also be used together with arrays,#i ncl u de i nt mai n() {i nt i , * p, arr[4] = {6, 2, 4, 7} ;p = &arr[0] ; /* As s i gn the addres s of the fi rst el ement to p * /for( i =0; i


fpri ntf( fi l ePtr, " Wri ti ng ou t s ome i mportant data. . . %d, %d, %d\n" , 2, 3, 4) ;When the file access has been completed it has to be closed, flushing any data in memory to the disk.fcl os e( fi l ePtr) ; /* Cl os e textFi l e. txt, fl u s hi ng data to di s k * /<strong>The</strong> final example program uses many of the concepts discussed so far, to provide a simple encryption algorithm,#i ncl u de i nt mai n(i nt argc, char * argv[] ) {i nt mas k = 163; /* Decl are an i nt and as s i gn i t wi th a val u e l es s than 256. * /char c; /* Decl are a character ( whi ch i s one byte, maxi mu m val u e 255. ) * /FI L E * i npu tFi l e = 0, * ou tpu tFi l e = 0; /* decl are two fi l e poi nters * /i f( argc! =3) { /* Check the number of argu ments * /pri ntf( " Us age: %s \n" , argv[0] ) ;retu rn 1; /* Report an error * /}i npu tFi l e = fopen(argv[1] , " r" ) ; /* Open the i npu t fi l e. * /i f( ! i npu tFi l e) retu rn 2; /* I f fi l e poi nter i s nul l retu rn an error. * /ou tpu tFi l e = fopen(argv[2] , " w" ) ; /* Open the ou tpu t fi l e. * /i f( ! ou tpu tFi l e) retu rn 3; /* I f the fi l e poi nter i s nul l retu rn an error * /c = fgetc( i npu tFi l e) ; /* Get the fi rst character. * /whi l e( c ! = E OF) { /* L oop u nti l end- of- fi l e i s reached. * /c ^= mas k; /* E xcl u s i ve- OR wi th the mas k. * /fpu tc( c, ou tpu tFi l e) ; /* Wri te to the ou tpu t fi l e. * /c = fgetc( i npu tFi l e) ; /* Get another character. * /}fcl os e( i npu tFi l e) ; /* Cl os e the i npu t fi l e. * /fcl os e( ou tpu tFi l e) ; /* Cl os e the ou tpu t fi l e. * /}retu rn 0; /* Retu rn s u cces s to the operati ng s ys tem * /<strong>The</strong> program uses an exclusive-OR to encrypt and decrypt files. An exclusive-OR is true if either bit is set and false ifboth or no bits are set. For example, 2 ^ 3 = 1 in decimal or in binary 10 ^ 11 = 01. Type in a text file withnano and then try to encode the file. <strong>The</strong>n run the program again to decode the file.Challenge problemImprove the encryption algorithm by using a simple random number generator, e.g:#i ncl u de i nt newMas k( ) {i nt mas k = ( dou bl e) rand( ) /RAND_MAX* 254+1; /* Nu mber between 1 and 255 * /retu rn mas k;}i nt mai n() {s rand( 1234567) ; /* Set the s eed once * /i nt mas k = newMas k( ) ; /* Get a new mas k each ti me i t i s u s ed. * /retu rn 0;}<strong>The</strong> solution to the problem will be given next time.Article by W. H. Bell & D. Shepley23


Make a "Simon" Memory Game!This month we are going to use Scratch to makea memory game based on the classic toy:"Simon". If you've never heard of it, ask yourparents (or grandparents! ).It's simple game. Simon plays four notes and youhave to repeat them in order. If you get it right,you get another sequence with more notes toremember - and it goes faster each time!<strong>The</strong> original "Simon".First, make four quarter-circle sprites. Idid it by making a circle first and thenselecting the bit I needed, discarding therest. You'll need each one to have two"costumes": one a dark colour and onelighter (to look like a light is on! )That's the hard bit done! Now we canwrite some scripts.It's easy to make a second costume. Afteryou have made your sprite, you'll see atab called "costumes" in the centerpanel. Click on it and make a newcostume.As usual, if you get stuck you candownload the project from:http://scratch.mit.edu/forums/My user name is "racypy".24


<strong>The</strong> Scripts<strong>The</strong>se scripts control a spritethat is just a button with"New Game?" written on it.This is the main script thatcontrols the game! I gave itto the yellow segment sprite,but it doesn't really matterwhich sprite owns it.Each segment sprite will need thesescripts. You'll need to vary the numbersfor the notes.I used: 60, 62, 65 and 67.25


This month we show you a method ofcreating a gradient fill, to add depth toflat looking rectangles, and usingtransparency effects to change the shapeof gradient filled surfaces, how to plotpoints of a circle as well as some coolexamples of why you would want to doso.# GRADIENT FILL# By Jaseman ­ 8th August 2012import os, pygame; from pygame.locals import *pygame.init(); clock = pygame.time.Clock()os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'pygame.display.set_caption("Gradient Fill")screen=pygame.display.set_mode([600,382],0,32)# We know that color values are between 0­255 so...# Lets give the sky surface 255 pixels heightsky = pygame.Surface((600,255))# Now we will draw rectangles down from the top of the sky surface# Each rectangle gets slightly higher color values so that the blue# gets lighter and lighter towards the horizon# We will define some variables and then create a loop to draw# rectanglesr=0; g=64; b=128 # Start Red Green and Blue Valuesfor l in range (0,255):pygame.draw.rect(sky,(r,g,b),(0,l­1,600,l))r=r+1;g=g+1;b=b+1 # Increase the Red Green and Blue Valuesif r>=255: r=255 # Max amount of red allowedif g>=255: g=255 # Max amount of green allowedif b>=255: b=255 # Max amount of blue allowed# Let's do a similar thing with the ground# For the ground let's have half as many pixels height# as available color values (256/2=128)ground = pygame.Surface((600,128))r=192; g=255; b=192 # Start Red Green and Blue Valuesfor l in range (0,128):pygame.draw.rect(ground,(r,g,b),(0,l­2,600,l))r=r­2;g=g­2;b=b­2 # Decrease the Red Green and Blue Valuesif r


# MOUNTAINS# By Jaseman ­ 18th August 2012import os, pygame; from pygame.locals import *pygame.init(); clock = pygame.time.Clock()os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'pygame.display.set_caption("Mountains")screen=pygame.display.set_mode([600,382],0,32)sky = pygame.Surface((600,255))r=0; g=64; b=128for l in range (0,255):pygame.draw.rect(sky,(r,g,b),(0,l­1,600,l))r=r+1;g=g+1;b=b+1if r>=255: r=255if g>=255: g=255if b>=255: b=255ground = pygame.Surface((600,128))r=192; g=255; b=192for l in range (0,128):pygame.draw.rect(ground,(r,g,b),(0,l­2,600,l))r=r­2;g=g­2;b=b­2if r=255: b=255# Draw some black (Transparent) polygons to create mountain peaks# <strong>The</strong> screen is 600 wide so I've drawn 10 polygons at 60 pixels wide eachpygame.draw.polygon(mountain,[0,0,0],[(0,0),(60,0),(60,10),(0,40)])pygame.draw.polygon(mountain,[0,0,0],[(60,0),(120,0),(120,30),(60,10)])pygame.draw.polygon(mountain,[0,0,0],[(120,0),(180,0),(180,20),(120,30)])pygame.draw.polygon(mountain,[0,0,0],[(180,0),(240,0),(240,50),(180,20)])pygame.draw.polygon(mountain,[0,0,0],[(240,0),(300,0),(300,40),(240,50)])pygame.draw.polygon(mountain,[0,0,0],[(300,0),(360,0),(360,10),(300,40)])pygame.draw.polygon(mountain,[0,0,0],[(360,0),(420,0),(420,35),(360,10)])pygame.draw.polygon(mountain,[0,0,0],[(420,0),(480,0),(480,45),(420,35)])pygame.draw.polygon(mountain,[0,0,0],[(480,0),(540,0),(540,42),(480,45)])pygame.draw.polygon(mountain,[0,0,0],[(540,0),(600,0),(600,15),(540,42)])screen.blit(sky,(0,0))screen.blit(ground,(0,255))screen.blit(mountain,(0,128))pygame.display.update()pygame.time.wait(30000)Here we use transparent polygons to cut azig-zag mountain range out of the top of arectangular surface.PYTHON VERSION: 2.7.3rc2PYGAME VERSION: 1 .9.2a0O.S.: Debian 728


# POINTS OF A CIRCLE# By Jaseman ­ 21st August 2012import os, pygame; from pygame.locals import *from math import sin, cos, pipygame.init(); clock = pygame.time.Clock()os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'pygame.display.set_caption("Points Of A Circle")screen=pygame.display.set_mode((600,600),0,32)background=pygame.Surface((600,600))background.fill((0,0,192))dot=pygame.Surface((8,8))pygame.draw.circle(dot,(255,255,255),(4,4),4,0)dot.set_colorkey([0,0,0])screen.blit(background,(0,0))screen.blit(dot,(300­4,300­4)) # Paste a dot in the centre of the screen# 300=half screen width 4=half dot widthradius = 200points = 90angleStep = pi *2 / pointsfor a in range(0,points):x = sin(a*angleStep)*radiusy = cos(a*angleStep)*radiusscreen.blit(dot,(x+300­4,y+300­4)) # Paste dots in a circlepygame.display.update()pygame.time.wait(30000)In this program, we make use of the maths functions 'sin', 'cos' and 'pi' to calculate the x and ycoordinates for plotting points of a circle. Try changing the values of radius and points to see whathappens.<strong>The</strong>re are many reasons why we might wish to plot points of a circle. For example we might wantto animate a graphic in a circular motion, or have the hands of a clock or needle of a dial rotate bydrawing a line from the centre of the circle to one of the points of the circle.We can also generate basic geometric shapes by this method. For example, if you set the numberof points to 3 and joined the dots, you would get a triangle. 4 points for square, 5 for pentagon, 6for a hexagon, and so on. You could use those coordinates as the points of a filled polygon.You might even choose to plot several circles which have the same number of points, and thendraw lines connecting the points of both circles. It is possible to create some 3d effects in this way.If the circles have different radius, you could create a tunnel or perspective effect. You could alsoadd a line into the 'for loop' to increase or decrease the radius during the loop, to produce adecaying circle or spiral.29


# CIRCLE DEMO# By Jaseman ­ 22nd August 2012import os, random, pygame; from pygame.locals import *from math import sin, cos, pipygame.init(); clock = pygame.time.Clock()os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'pygame.display.set_caption("Circle Demo")screen=pygame.display.set_mode((800,600),0,32)bk=pygame.Surface((800,600)); bk.fill((0,64,0))dot=pygame.Surface((4,4)); dot.set_colorkey([0,0,0])pygame.draw.circle(dot,(255,255,255),(2,2),2,0)smlradius = 60; bigradius = 120; points = 90# Variable Arrays To Store X&Y points for a small and big circlesmcx = []; smcy = []; bgcx = []; bgcy = []# Calculate the X&Y points and put values into the arrayangleStep = pi *2 / pointsfor a in range(0,points):smcx.append(sin(a * angleStep)*smlradius)smcy.append(cos(a * angleStep)*smlradius)bgcx.append(sin(a * angleStep)*bigradius)bgcy.append(cos(a * angleStep)*bigradius)a=0; b=0 # Points a & b will be moving points of the circlesc=0; d=0 # Points for sine and cosine wavescx=800/2; cy=600/2 # Centre of the screenr=random.randint; pdl=pygame.draw.line # Abbreviations for commandsrun = 1while run == 1:screen.blit(bk,(0,0)) # Draw the background surfacescreen.blit(dot,(cx­2,cy­2)) # Centrepoint# Draw the circlescreen.blit(dot, (bgcx[a]+cx­2,bgcy[a]+cy­2))screen.blit(dot, (smcx[a]+cx­2,smcy[a]+cy­2))screen.blit(dot, (bgcx[b]+cx­2,bgcy[b]+cy­2))screen.blit(dot, (smcx[b]+cx­2,smcy[b]+cy­2))rcol=r(0,255); gcol=r(0,255); bcol=r(0,255)pdl(bk,[rcol,gcol,bcol],(bgcx[a]+cx­2,bgcy[a]+cy­2),(smcx[a]+cx­2,smcy[a]+cy­2))pdl(bk,[rcol,gcol,bcol],(bgcx[b]+cx­2,bgcy[b]+cy­2),(smcx[b]+cx­2,smcy[b]+cy­2))pdl(bk,[rcol,gcol,bcol],(smcx[a]+cx­2,smcy[a]+cy­2),(smcx[b]+cx­2,smcy[b]+cy­2))# Constrained points (Fixed X or Y)screen.blit(dot, (bgcx[a]+cx­2,cy­bigradius­14))screen.blit(dot, (bgcx[b]+cx­2,cy+bigradius+10))screen.blit(dot, (smcx[a]+cx­2,cy­bigradius­34))screen.blit(dot, (smcx[b]+cx­2,cy+bigradius+30))screen.blit(dot, (cx­bigradius­14,bgcy[a]+cy­2))screen.blit(dot, (cx­bigradius­34,smcy[a]+cy­2))screen.blit(dot, (cx+bigradius+14,bgcy[b]+cy­2))screen.blit(dot, (cx+bigradius+34,smcy[b]+cy­2))pdl(bk,[rcol,gcol,bcol],(bgcx[a]+cx­2,cy­bigradius­14),(smcx[a]+cx­2,cy­bigradius­34))30


pdl(bk,[rcol,gcol,bcol],(bgcx[b]+cx­2,cy+bigradius+10),(smcx[b]+cx­2,cy+bigradius+30))pdl(bk,[rcol,gcol,bcol],(cx­bigradius­14,bgcy[a]+cy­2),(cxbigradius­34,smcy[a]+cy­2))pdl(bk,[rcol,gcol,bcol],(cx+bigradius+14,bgcy[b]+cy­2),(cx+bigradius+34,smcy[b]+cy­2))# Ellipse (Big and Small Radius points mixed)screen.blit(dot, (bgcx[a]+cx­2+bigradius+160,smcy[a]+cy­2))screen.blit(dot, (smcx[a]+cx­2­bigradius­160,bgcy[a]+cy­2))screen.blit(dot, (cx­2+bigradius+160,cy­2))screen.blit(dot, (cx­2­bigradius­160,cy­2))pdl(bk,[rcol,gcol,bcol],(cx­2+bigradius+160,cy­2),(bgcx[a]+cx­2+bigradius+160,smcy[a]+cy­2))pdl(bk,[rcol,gcol,bcol],(cx­2­bigradius­160,cy­2),(smcx[a]+cx­2­bigradius­160,bgcy[a]+cy­2))# Sine and Cosine Wavesscreen.blit(dot, (c,smcy[a]+cy­2­bigradius­100))c=c+1if c>=800: c=0screen.blit(dot, (smcx[a]+cx­2­bigradius­100,d))d=d+1if d>=600: d=0clock.tick(200); pygame.display.update(); a=a­1; b=b+1if b>=points: b=0if a==­1: a=points­1In this demo, the x and y coordinates of two sets of circle points are stored in variable arrays:smcx - small circle x coords, smcy - small circle y coordsbgcx - big circle x coords, bgcy - big circle y coordsIn the center you can see dots travelling around both circles in clockwise and anticlockwisedirections. Randomly coloured lines are drawn between the big and small circle, and horizontallines are drawn across the small circle, between point a and b (A and B are points that move eitherin clockwise or anticlockwise directions around the circles).Surrounding the circle are more dots that bob up and down and side to side. <strong>The</strong> side to side onesuse the same x coord as the dots that move around the circle. <strong>The</strong> bobbing up and down dots usethe same y coord as the dots which move around the circle.A set of ellipses are drawn by putting together the x coords of the small circle with the y coords ofthe large circle (And visa versa).You might notice two other dots - one weaving down the screen from top to bottom and anotherone moving left to right. Each has one constant direction (Either x or y) and the other uses thecircle points, making Sine and Cosine wave patterns.PYTHON VERSION: 2.7.3rc2PYGAME VERSION: 1 .9.2a0O.S.: Debian 731


FeedbackJust wanted to say greatmag. I read it page to page. Iam age 45 and think youmag is good for anyone. Iwent out and purchased arobot to follow the skutterseries. i was a bitdisapointed not to see it inissue 4 i hope it will be in thenext one. Please keep upthe good work i look forwardto the next issue.AndyWhat a great magazine. Thisshould be required readingfor <strong>Pi</strong> owners.AdamI'd just like to say that I loveit! Keep up the good workchaps.ScepI think it's great. I have hadmy <strong>Pi</strong> running for 4 days nowand have used all of thepython tutorials, orderedsome parts from Tandy sothat I can try the GPIO, andread all of the articles. It'sperfect for a noob like mehas taught me loads.JI think your magazine is verywell done; and it certainlyreflects the enthusiasm thatmany of us have for the <strong>Pi</strong>.Your early articles seemedto have a definite tilt towardWindows computers (ascontrasted with the OS onMacs). While you may havehad very good reasons forthis, I hope that, wheneveryou may take us back to adesktop, you will maintain agood balance betweenthose two systems.GeneGreat effort guys! <strong>The</strong>hardware and programmingcontent takes me right backto my youth when HomeComputers were justbecoming 'common-place'and I was keen onelectronics.SuperObsessiveManeditor@themagpi.com<strong>Raspberry</strong> <strong>Pi</strong> is a trademark of the <strong>Raspberry</strong> <strong>Pi</strong> foundation. <strong>The</strong> Mag<strong>Pi</strong> magazine is collaborativelyproduced by an independent group of <strong>Raspberry</strong> <strong>Pi</strong> owners, and is not affiliated in any way with the<strong>Raspberry</strong> <strong>Pi</strong> Foundation. <strong>The</strong> Mag<strong>Pi</strong> does not accept ownership or responsibility for the content oropinions expressed in any of the articles included in this issue. All articles are checked and tested beforethe release deadline is met but some faults may remain. <strong>The</strong> reader is responsible for all consequences,both to software and hardware, following the implementation of any of the advice or code printed. <strong>The</strong>Mag<strong>Pi</strong> does not claim to own any copyright licenses and all content of the articles are submitted with theresponsibility lying with that of the article writer.This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. To view acopy of this license, visit:http://creativecommons.org/licenses/by-sa/3.0/32or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041 , USA.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!