(Please wait while this loads! - Don`t try opening on a

Transcription

(Please wait while this loads! - Don`t try opening on a
(Please wait while this loads! - Don’t try opening on a Pi at all, it won’t ever finish!)
Dedicated to John Routledge
03/02/47 - 10/05/2013
- He never hid the screw drivers!
and
Penelope Alice ‘Squishy’
Routledge
21st July 2013
Last Updated: 21st Jan 2014 - Total Pages 273
1
Random Links to Sort.
2
http://www.spillmonkey.com/?page_id=5 - Spillpass for the Pi (3DS hotspot thing!)
http://letsmakerobots.com/node/38610
FLASK - http://flask.pocoo.org/
http://jack.minardi.org/raspberry_pi/make-an-internet-controlled-lamp-with-a-raspberry-pi-and-flask/
http://www.instructables.com/id/Raspberry-Pi-Multi-Room-Audio-MobileTabletPC-Contr/
http://www.drdobbs.com/tools/wolfram-mathematica-language-free-on-ras/240164308
http://elinux.org/images/f/f9/Trinity_RPi_Specification.pdf
http://makezine.com/2013/11/27/makerbot-raspberrypi-google-chrome-happymaker/
http://raspi.tv/2013/sonic-pi-flight-of-bumblebee-video-with-hdmipi
blog.thestateofme.com/2013/12/30/pi-lite-with-node-red/ - Node Red & Pi-Lite
http://www.raspberrypi-spy.co.uk/2013/11/quick-guide-to-nano-text-editor-on-the-raspberry-pi/
http://www.retrocollect.com/News/commodore-amiga-disk-drive-replaced-with-raspberry-pi-a-adf-diskloading-software.html
http://www.thefanclub.co.za/how-to/how-setup-usb-3g-modem-raspberry-pi-using-usbmodeswitch-andwvdial
http://www.adafruit.com/blog/2013/11/29/raspberry_pi-piday-raspberrypi-52/
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/voice-controlled-lights/
Fixing the memory card socket.
http://smstextblog.blogspot.co.uk/2014/01/fixing-broken-sd-slot-on-raspberry-pi.html
Stop Motion Animation on the Pi (inc user interface!)
http://trevorappleton.blogspot.co.uk/2014/01/creating-animation-studio-with.html
Hosting your site on a Pi
- http://www.instructables.com/id/Host-your-website-on-Raspberry-pi/?ALLSTEPS
Pi as a Webserver
- http://www.instructables.com/id/Raspberry-Pi-as-webserver/
- http://www.instructables.com/id/Install-a-webserver-on-Raspberry-Pi/
Robot Control From Web GUI
www.linuxuser.co.uk/tutorials/control-your-raspberry-pi-robot-from-a-web-connected-device
Music Box
http://www.woutervanwijk.nl/pimusicbox/ (Spotify and Google Music)
Currently Working on:
- Photo Frame with motion detection.
http://www.ofbrooklyn.com/2014/01/2/building-photo-frame-raspberry-pi-motion-detector/
https://github.com/alexis-mignon/python-flickr-api/wiki/Tutorial
http://www.flickr.com/services/api/flickr.photosets.getPhotos.html
http://idgettr.com/
2
https://github.com/alexis-mignon/python-flickr-api/wiki/Tutorial
http://www.instructables.com/id/How-to-Make-a-Raspberry-Pi-Media-Panel-fka-Digita/?ALLSTEPS
- Setting up Newsreader on a Pi
http://www.howtogeek.com/162060/how-to-install-nzbget-for-lightweight-usenet-downloading-onyour-raspberry-pi/flite
- Mini CNC Laser Engraver - http://funofdiy.blogspot.co.uk/2013/10/a-raspberry-pi-controlledmini-laser.html
- DukePad - https://wiki.openjdk.java.net/display/OpenJFX/DukePad
- Cloud Lamp - http://falldeaf.com/2013/07/the-pi-control-script/
- Sonic Pi http://www.cl.cam.ac.uk/projects/raspberrypi/sonicpi/teaching.html
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=63&t=58313&p=438279
Bluetooth Speaker with the Pi http://www.instructables.com/id/Bluetooth-Speakers-using-Raspberry-Pi/?ALLSTEPS
- NFC with the PI.
http://learn.adafruit.com/adafruit-nfc-rfid-on-raspberry-pi/overview
https://docs.google.com/viewer?url=http://learn.adafruit.com/downloads/pdf/adafruit-nfc-rfid-onraspberry-pi.pdf&chrome=true
http://www.instructables.com/id/USB-RFID-Python-Pub-Sub-MQTT/
- Raspberry Pi Web GUI
http://www.instructables.com/id/Simple-and-intuitive-web-interface-for-your-Raspbe/?ALLSTEPS
- Raspberry Pi Camera module Web Streaming using Motion.
http://www.raspberrypi.org/phpBB3/viewtopic.php?p=356814
- IKEA Lights Hack
http://blog.nadnerb.co.uk/?p=575 - Hyperion (Boblight?)
https://github.com/tvdzwan/hyperion/wiki
http://pibob.nadnerb.co.uk/software.html
http://hackaday.com/2011/08/19/adding-usb-control-for-ikea-rgb-led-strips/
http://www.microchipdirect.com/productsearch.aspx?Keywords=DV164121
http://christian.amsuess.com/tutorials/threebutton_dioder/
http://hackaday.com/2013/03/28/ikea-dioder-ambilight-hack/#more-96953
http://www.slickstreamer.info/2013/10/another-ikea-dioder-hack-arduino-ikea.html
Probably need an Arduino
https://gist.github.com/evilmachina/7073753 - Link to ino file.
- Setting up the Pi as an Wireless Access Point http://learn.adafruit.com/setting-up-a-raspberrypi-as-a-wifi-access-point?view=all
- Pirate Pi???
- Minecraft rendering 3D OBJ Models (Cthulhu didn’t work very well, nyan cat to follow!)
- SiriProxy Test at school?
3
- 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!!! (removed the IR sensor from a PS3 Eyetoy, now will pick up Infrared,
or more importantly if you bathe stuff in an IR Light (stronger than Wii Bar) you can see what’s
happening in the dark!!!
- EmulationStation - selected PSX games not working.
- CUPS (Printing from Linux!) - Tested and need tweaking, try at school.
- Telnet http://www.youtube.com/watch?v=NS6t8HnrrXw
- PiUi - http://blog.davidsingleton.org/introducing-piui/
- Turn Pi into Bluetooth Speaker
http://www.instructables.com/id/Turn-your-Raspberry-Pi-into-a-Portable-Bluetooth-A/?ALLSTEPS
- Connecting your Pi to GMail - http://mitchtech.net/connect-raspberry-pi-to-gmail-facebooktwitter-more/
- Remote Pi Access
http://pihw.wordpress.com/guides/direct-network-connection/
- Pi as a NAS
http://www.makeuseof.com/tag/turn-your-raspberry-pi-into-a-nas-box/
- XBOX 360 Ring / RF Transmitter Hack.
http://www.astrorats.org/blog/2013/07/29/xbox-360-rf-module-and-the-raspberry-pi/
RFID Ideas
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=37&t=55321&p=419718
PiPresents - https://github.com/KenT2/pipresents-next
http://pipresents.wordpress.com
4
On the back burner - Stuff to try when parts arrive! :) 4
- LED INDICATOR (Some good stuff here)
http://www.howtogeek.com/140063/build-an-led-indicator-with-a-raspberry-pi-for-email-weather-oranything/
Cheap PIR Sensors.
-http://www.raspberrypi-spy.co.uk/2013/01/cheap-pir-sensors-and-the-raspberry-pi-part-1/
How to use Pi as a low power network storage device.
http://www.howtogeek.com/139433/how-to-turn-a-raspberry-pi-into-a-low-power-network-storage-device/
Steepen Motor Controller?
I ordered two from “4tronix_uk” on eBay and they arrived the next day. There are additional
details in the Stepper Motor 28BJY-48 Datasheet
http://www.raspberrypi-spy.co.uk/2012/07/stepper-motor-control-in-python/
Ultrasonic Distance Meter
http://www.raspberrypi-spy.co.uk/2012/12/ultrasonic-distance-measurement-using-python-part-1/
USB Driver for Unknown Device.
http://matthias.vallentin.net/blog/2007/04/writing-a-linux-kernel-driver-for-an-unknown-usb-device/
http://hackaday.com/2009/08/20/reverse-engineering-usb-drivers/
http://www.wingmanteam.com/usbsnoopy
http://www.reactivated.net/weblog-content/20050806-reverse-0.2.txt
5
Stuff I’d like to buy if I had the cash. 4
Rapiro Robot Kit
- http://www.kickstarter.com/projects/shota/rapiro-the-humanoid-robot-kit-for-your-raspberry-p
Frindo
- http://robotbits.co.uk/robot-kits/frindo-robot-kit/prod_162.html
Thermal Printer
- https://www.sparkfun.com/products/10438
BADGEr4
http://www.seeedstudio.com/depot/badgerv4-p-1587.html
PiPan
http://www.openelectrons.com/index.php?
module=pagemaster&PAGE_user_op=view_page&PAGE_id=15
Basic Electronics Kit
http://www.monkmakes.com/#!/~/product/category=0&id=32645469
General Links.
5
Official Pi Stuff
http://www.raspberrypi.org/ - The official Site.
http://www.themagpi.com/ - The Magazine
http://www.raspians.com/ - Raspberry Community Projects
OCR Guides / Recepie Sheets - Guides and Tutorials
http://pibeginners.com/ - Pi Beginners Youtube Clips.
http://www.pi-fun.com/ - A nice site with some useful content.
http://www.recantha.co.uk - RaspberryPiPod (Good for news)
http://downloads.raspberrypi.org/Raspberry_Pi_Education_Manual.pdf - Pi Education Manual.
http://www.raspberry-projects.com/pi/pi-operating-systems - Some interesting Tutorials
6
Python and Programming
http://www.codecademy.com/ - A great prgramming place to start.
http://pythondictionary.code-it.co.uk/ - Python Dicitonary / Resource.
http://www.pythoncode.co.uk - Good examples / tutorials / questions. (Based on Python 3)
http://www.ictvideohelp.co.uk/python.html - Python Videos.
http://usingpython.com/ - Using Python
http://www.pythontutor.com/visualize.html#code=#Enter your python program
here.%0A#Press 'Visualize Execution' to see it running line by line!
http://www.tutorialspoint.com/python/index.htm - Seems like a simple resource with examples.
http://www.staff.city.ac.uk/afl/tinybasic/index.html - TinyBasic
http://inventwithpython.com - Some good guides of Python / Pygame.
http://pythonbooks.revolunet.com/ - A good selection of python books.
Linux General
http://elinux.org/RPi_Hub - Great source for Pi info / hardware.
http://linuxmanpages.com - Linux Commands, no fuss.
http://unix.stackexchange.com/ - Linux Q&A Forums.
Youtube Links / Channels
GigaFide / Tinkernut
RaspberryPi Tutorials - http://www.youtube.com/user/RaspberryPiTutorials
Raspberry Pi IV Beginners
http://www.youtube.com/user/raspberrypitutorials
OCR Pi Tutorials
7
Foreword
6
My father died suddenly at 66. This document would not exist without him. He did not effect it directly,
(or probably have even known of it’s existence) When I was a boy I wanted to ‘work with computers, like
daddy!’. I also seemed to have a knack at taking things appart. Luckily for me Dad never hid his tools or
the screwdrivers, they were always a versatile couple always present in the ‘Draw of Doom’, (EVERY house
has one, usually a small draw full of bits, fuses, a torch, batteries and other assorted guff.) I made good
use of them to fulfil my curiosity of what was inside things! Indirect support often goes unnoticed, but
Thanks Dad I owe you!
This document has been a labour of love. I’ve spent far too long messing with Pi’s and not writing stuff
down. I hope this guide is useful. It will be for me, but hopefully it will get passed into the hands of
students. Those with more time to experience and mess with the system, to continue to innovate, design,
create and best of all dream! I don’t mean to tread on anyone’s toes and a lot of this is copied and / or
pasted from t’web.
This document is a scaffold, it will take you to numerous websites, is totally full of errors / mistakes and
half completed instructions, but like I say it has come together over a year and I plan to keep adding to
it. If you find a mistake or wish to add to it then Email me, I’ll fix it. (Similarly if you want anything that is
explicity yours and you don’t want sharing then again email me!)
This document is very much NOT my own work, just TONS of stuff that I’ve copied from other peoples sites
and hard work. As such please ‘share and share’ alike, that’s what the original authors would want! (Note
the creative commons link at the top!)
I’d like to say THANKS to everyone the guys (and gals) at the RaspberryPi organisation that dared to
create, see a project through and hopefully reap the rewards. The people who have created individual
projects / tutorials etc that I’ve lovingly followed and all those who offer tons of help and support on the
forums.
On a personal note, thanks, it’s been just the boot (up the bottom) I needed to learn some NEW stuff,
Linux, Python and for the first time since Uni, pick back up my dusty Multimeter and soldering iron! Let
the projects begin! Although I’m not very innovative myself I love taking other peoples ideas, giving them
a go, and maybe combining them!
Thanks to all those who have spent the time listening to me rabbit on about how good these little boards
are. To Lloyd for keeping me busy with technical questions, Arron for helping me find answers and
tolerating my Linux stupidity and Lewis for the blind belief that I could get Linux running on his Netbook
(which we did!). I hope you all do well in the future.
Finally an apology to my wife as I’m sat here in the small hours of the morning when I should be in bed,
knowing that I’m going to be knackered tomorrow, but I’m keeping my noggin busy and that’s important
too! As this document approaches 300 pages I wonder just how many hours I’ve spent dabbling! Bugger.
In all this time I’ve only (sort of) broken one Raspbery Pi (I broke a bit off the memory card holder, and had
to glue it back on!)
Keep on hacking / modifiying / innovating
8
Mr R.
9
Contents
7
*Random Links to Sort. *
2
On the back burner - Stuff to try when parts arrive! :) 4
- LED INDICATOR (Some good stuff here)
Cheap PIR Sensors.
How to use Pi as a low power network storage device.
Steepen Motor Controller?
Ultrasonic Distance Meter
USB Driver for Unknown Device.
Stuff I’d like to buy if I had the cash.
4
Rapiro Robot Kit
Frindo
Thermal Printer
BADGEr4
PiPan
Basic Electronics Kit
-*General Links. * 5
Official Pi Stuff *
-Python and Programming *
-Linux General *
-Youtube Links / Channels *
Foreword *6
Contents 7
*FAQs*
15
Back Your card up often! (every couple of weeks!)
What happens if (when) you corrupt your memory card!
Constant keyyyyyyyyyyyyyyyyyyyyyyyyyboard presses
Corrupt Memorycard
Constant Reboots.
Reboots when you plug something USB in!
-Falling off the Network Randomly
Apt-get update Fails.
No diversion 'diversion
IF YOU FILL YOUR MEMORY CARD!!!
SSH on the school system???
Using both Wireless and Wired connections (Untested Sofar!)
The Hardware
18
How to check what RPi.GPIO version you have
How to check your Raspberry Pi Revision number?
* DISTROs. *
20
Backing up the Memorycard using the PI (working)
Setup Raspbian Memory Split and config.
Update and Install updated packages!
10
-Recommended Packages to Install (You’ll probably need them later!)
Optional Fancies.
RPi-update - Firmware
sudo rpi-update
Randomized Learning
* GitHubs Worth Cloning *
Backing up files to GDrive (Tested)
* PC Software to get familiar with *
24
SSH - KitttySSH or Putty
WIN32Imager
7Zip
Advanced IP Scanner
UltraVNC (Portable)
Geany / Ninja IDE. (versions available for both Windoze and PI!)
WinSCP
Xming / Xming Portable (not got this working for me! :( )
MobaXTerm - Works as well as VNC
LILI USB - Live USB Stick Creator with Persistence.
Phone / Mobile Device Software
Useful Linux Commands* 26
-A note about the command prompt
-Installing Software / Drivers
Using NANO Guide
Using GREP Properly.Basic syntax
Additional Arguments
SYSTEM 30
Using ‘screen’
Setting a Static IP (network address)
How to Change Your Raspberry Pi (or Other Linux Device’s) Hostname
Why Do I Want to Do This?
Changing the Host on your Pi
Setting up Wi-Fi *
Setting up ad-hoc wifi
Testing Internet Connection Speed with Wget
*School Site Proxy Info (to remember)
Edit this file to set Permanently Across All Profiles.
Allow programs other than Bash access to a (school) network under Proxy.
Temporarily from the LXTerminal (not ideal and only works for ROOT!)
Changing the Font Size of the Terminal Text
sudo dpkg-reconfigure console-setup
Choosing which programs run when the Pi boots
Creating Icons to your programs on the desktop in X
Executing A Command In LX Terminal via a Desktop Icon
Running Applications in Kiosk (Fullscreen Mode)
11
A bit of Optimising / Tweaking (in Testing)
Setting up VNC *
VNC - http://myraspberrypiexperience.blogspot.co.uk/p/setting-up-vnc.html
Running VNCServer at Startup
Web Interfacing with your Pi.
webiopi
Installation
Running WebIOPi
Running WebIOPi (Daemon)
Auto start at boot
Usage
Buddy Pi Setup - (part Tested)
web-pins
Install the requirements.
Install GPIO Python library
Usage
-Sound on the Pi. *
Check Alsa & remove Pulse!
Test the sound using
-Force HDMI sound using
-Making the Pi Speak *
SOX - The Swiss Knife of WAV / Raw audio on Linux
MPG321
Turning your Raspberry Pi into an FM Transmitter*
Writing a Script to Monitor Mic Input
A Better Live Mic Solution
Playstation Microphones
Stream and Play Internet Radio Stations (Tested)
A selection of Radiostations to tune into.
# Add BBC channels to MPC
-Using MPD - Music Player Daemon
-Autostart MPC without Daemon (MPD)
Control using mpod App like mpod or Android MPDroid?
Download music from GrooveShark (CLI) (TESTED but won’t work on school network)
Karaoke on the PI (Tested)
Installation
Blanking the Console Screen
Voice Recognition on the Pi using Google Voice API
Asking Wolfram Alpha Questions
Getting the APP_ID
Text To Speech
Combining Speech to Text and Text to Speech.
Alternative Google Voice Settings / Script
Microsoft Translation and Google Text to Speech
Putting it all Together
*Mounting a USB the Easy Way! *
...Or the hard way
12
Printing on a Pi. *
Video on the Pi
Youtube-dl
Minimal Kiosk Browser (installed but untested!)
Presenting on the Pi - Screenly. - (TESTED)
Install Screenly OSE yourself
Configure the Raspberry Pi
Install Screenly OSE
Adding YouTube Video links! :)
Problems with Screenly.
Disabling Screenly
Making a Program LOOP FOREVER*
Making a program repeat every so often (CRON Jobs!) *
HARDWARE
45
Cases
Raspberry-Pi-GPIO-Layout-Revision-2
Ultimate Pin-Out Diagram
*-GPIO Stuff
-Connecting a Pi to the outside world
PIN Basics
-Making an LED Flash
ScratchGPIO – Introduction for Beginners (untested)
by cymplecy Scratch Controlling the GPIO Pins on a Raspberry Pi Part 1 of 4 (Version 4)
Controlling GPIO remotely using Arduino Remote on iPhone / iPad
Powering Mains
Singing / Screaming Jelly Baby (Probably works with Fruit Pastels too!)
Make sound playback through the headphone socket
-Pi Camera Module
-How to use the Raspberry Pi camera software
Example commands
-To shoot video with the Raspberry Pi Camera
Berrycam Photos (Tested)
Time Lapse Photos
-Time Lapse Video from Stills.
Converting the Video output
-Extra Tricks by Bill Tidey
Watermarking with another Graphic!
Using the Pi Camera module with Motion
Creepy Face Tracking (Partly Tested)
Fixing RaspVid / RaspImage for Headless streaming
QRCodes on the Pi.*
13
First install the Python QR Tools.
Generating QR Codes
Using ZBar from the Shell
Python Quick Example (calling ZBarCam)
Video for Linux Driver for Raspberry Pi Camera (so camera shows as /dev/video0!)
Cheap PIR Sensors and the Raspberry Pi – Part 1 (untested)
-Robot Arm Stuff.
Robot Arm Basics
Robot Arm with PS3 Pad
Robot Arm With Wii-Mote
Robot Arm GUI (in Python) - WIP
-7 Segment Display Project (One of my first test projects!)
**
Chips for driving motors
-LCD Setup
Cheap 3.5 LCD Display.
Setting up an iBeacon
Install The Required Software
Next install BlueZ’s source files and compile it.
Check for your USB Module
Enable the USB Device
Enter the iBeacon Advertising Data
Testing it on iOS
HARDWARE - Controllers
84
Graphics Testing / Visual Joystick Test
Wiimote Basics *
-Getting the drivers / setup
Running WiiMote as a Mouse.
-Wii-Mote Button Mappings
WIIMote Info
Creating Custom WiiMote Configs
-Using Wii-Motes in Python Projects
-XBox 360 Pad*
-Install the XBox Pad Drivers.
Create a mapping file
Alternative Setup For XBMC.
-Call the mapping using
-Using a PS3 controller*
Dualshock 3 and Raspberry PI
-PS3 Move???
PS3 Joystick Buttons and Axes
QJoyPad - Turning Joystick Commands into Keypresses.
HARDWARE - USB Devices*
98
14
WIFI ADAPTER???
TP Link wn725n (V2)
Edimax Dongle
Quick Webcam Monitor Guide via Motion
PS3 Camera Test under XDE.
PS3 Eyetoy Camera Streaming - Using Motion
Face Recognition on the Pi.
GUVCVIEW
CMAKE
OPENCV
Install the face recognition API
Install the Reco Program
FINALLY...
-Removing the IR Filter on The Eyetoy
-Using Multiple Cameras with Motion
-Retaliation (USB Rocket MOD!)
Retaliation Modification to Script. (TO REDO to use KEYBOARD!)
TVHead Test for XBMC
-Hardware Add-on Boards
151
Berry Clip *
Input / Output Pins on the BerryClip
*LedBORG - http://www.piborg.org/ledborg
Rev 2, 2013-09-10 or 3.6.11+ build #538
Usage
Controlling LedBorg
To set the colour from a Python script:
To set the colour from a terminal type:
To set the colour from a terminal with the basic driver type:
To disable LedBorg from a terminal type:
To enable LedBorg from a terminal type:
Managing boot options
-PILite LED Matrix Access to the serial port
Disable Serial Port Login
Disable Bootup Info
Reboot
Programming from the Raspberry Pi
SOFTWARE
109
-GitHubs - Why They Rock!
How to clone your repo to your local machine ?
Compiling Your Own Version of Software (Roll your own!)
-Grab
-Configure
-Make
Make Install
SOFTWARE - Interfacing
111
-Pi-Wall (WORKING!)
15
Setting up the units.
Network configuration
Testing the software
-Looping an Video on the screens.
Multicasting Input from the Pi Camera (untested!)
Fritzing
PI-Car
Using Twitter
Creating An Array of Followers (Partly Tested)
Creating a Python Script that can Tweet (Tested)
Creating a Python Script that can Tweet Images (Tested)
Create a Python Script that can Tweet Images Via Raspicam, watermark them and Tweet
Them
Creating a Python Script to Output System Info
-Tweeting on a Set Interval
-Read Out Tweets (Untested)
Tweeting Webcam Pics (Part Tested)
-- Reading Tweets from a #Tag
-Creating a TweetBot
Clever Graphics Programming / Shaders (a chance to fix Dremples)
Download openFrameworks
Compile openFrameworks:
Having fun with hte OpenFrameworks.
SOFTWARE - GAMES 123
A good list of Games that run on the Pi
SDL DispManx
-Q3 Arena on RASP PI (Build)
-Quake 3 Quick Install - School Build
School Build Error solutions
OR fix the permissions so non-root uses can access /dev/input/mice and /dev/input/mouse0
as follows.
Create new file in "/etc/udev/rules.d/99-input.rules"
Add a new group and add your user(s) to it (my login is just 'pi')
Sound through headphones
Show FPS in Game
Quake 3 Config File Guide
Full version of Quake 3.
Q3 - Models, Levels, Maps and Extras
Q3 Console Manual
Quake 2 on the Pi.
Installing Quake 2 on Pi
Installing DOOM 1 / 2
-OPTIONAL: Create a WAD-specific launcher
OPTIONAL 2: Create a laucher for multiple kinds of Doom
Installing Aliens TC and Aliens Doom 3.0 (AVP) in Chocolate Doom.
-Instructions for LAN play
16
-Installing Minecraft on the Pi.
-Custom Textures Packs
Python Scripts for Minecraft.
Rendering 3D Models in the Minecraft World
Making the OBJ Files.
Viewing 3D Meshes on a Pi.
wget http://jestermon.weebly.com/uploads/1/6/2/1/1621282/pyobjviewer.zip
List of Minecraft Blocks
Minecraft Twitter (untested)
Installing Descent on the Pi (untested)
SOFTWARE - Games Emulation 148
-A Note about ROMS
-RetroPie - Emcompassing Most Emulators.
-RetroPie - XBox Pad
-RetroPie - Exit Games Using Your Controllers
RetroPie - Installing ROMs
MAME
NES
Snes Emulator - SNES9x
ScummVM
DGen (Hit and Miss) - *
DGen Manual.
DGen Build Instructions
Tweaking DGen
Sonic Level Select
DGen CONTROLS
Using ta conrol pad (if it appears as /dev/js0)
Mupen64 - RPi
SOFTWARE Projects
154
*SiriProxy - As User
SiriProxy Install
Siri Proxy Plugins
Adding your own Siri Commands
SiriProxy - As Root
Ultrasonic Distance Monitor
Taking Screenshots on the Raspberry Pi
Simple Samba Share *
SMBGET (tested and working!)
SAMBA Server on the Pi.
Creating a Web GUI on the Pi using Apache Sever *
*SOFTWARE - XBMC * 174
-Booting to Black Screen
Windows 7 and Adding Sources
-How to add Sources/Repos/Addons
-Custom XML for better remote usage (at least on our big telly!!!)
17
-Fixing TV Scraper Error
-Setting up a Shared Library
First setup the SQL DB.
Edit the advancedsettings.xml
-Remote Controls.
-Accessing Region Locked Content. :)
-Get iPlayer
-USEFUL BITS OF PYTHON
187
Running A Console Command Via Python
Passing Arguments to Python programs
Changing Terminal Text Colours / Effects Via Python
Quick Python Pygame Joystick Axis Detection (Tested and Rechecked.)
Using Pygame to detect Joystick Presses
-Pi Club 192
Session 1 - Basic Setup (Network) and Minecraft (an Easy Win)
What worked
Session 2 - USB Rocket Launchers
Issues
Session 3 - Quake 3 and Emulation (DGEN?)
Suggestions:
What Worked.:
What didn’t work:
Session 4 - Breakout Board(s), Wiring bits?
Suggestions:
What Worked:
What Didn’t Work
Session 4.5 - Fail.
Session 5 - Robot Arm.
What Worked
What didn’t work.
Session 6 - Pi Camera.
What Worked
What didn’t work.
Session 6.5 - A Short Pi Club due to meetings and other commitments.
What Worked
What didn’t work
Session 7 - Minecraft Hacking on the Pi using Python Scripts?
Session 8 - PiFM (Pirate Radio!)
Session 9 - Twittering
Session 10 - Recap on SSH & Pi-Karaoke
Session 11 - Makey Makey and DGen
-COST OF STUFF / PRICE GUIDE
196
Linux Mini Guide (for Laptop / PC)
198
-Create a Live USB with Persistance.
-How to Enable SSH on Linux Mint 16/15 /14 / 13 / 12
VNC on Linux to Pi
18
FAQs
15
Back Your card up often! (every couple of weeks!)
I’ve had cards die a few time, probably something I’m doing, could be dodgy hardware. But eventually
the card will die. It’s all good though as you did back up right? If you lose lots of stuff it’s your own
fault. Luckily for me I’ve got a handy guide like this that keeps me up-to-date and helps so I don’t forget
anything!!! WICKED. If I’m a good soldier I’ll back up after every Pi-Club session (and keep what’s on
the card incase the kids mess theirs up too!) One word of warning, please try to keep to the same brand
of memory card as an 8GB Sandisk card will NOT be same size as a 8GB Transcend card, it might only
be a few MB, but it’s enough to NOT allow you to install the backup image you made!
What happens if (when) you corrupt your memory card!
GRRRR: CAUTION if using crappy / cheap PSU / Cables you will probably end up with a corrupt
memory card (due to reboots etc!) This can cause much heartache, back up often. I speak from
experience. But I’ve always got this document to fall back on!!! Note if it all goes horribly wrong and you
mess up your card, you can rescue it by using a Live Linux Distro e.g. Ubuntu (or Mint) this will let you
(hopefully) grab and rescue all the stuff from the memory card (just use a card reader!) but as it also has
GParted on it, you can format your memory card back to something Windoze will recognise!
Constant keyyyyyyyyyyyyyyyyyyyyyyyyyboard presses
If you start getting weird keyboard presses it’s due to the combination of hardware, namely the keyboard
and probably the Hub. I’ve had this several times, I generally plug the keyboard straight into the Pi,
everything else into the hub!
Corrupt Memorycard
If you’ve got a a memorycard that keeps becoming corrupt it might be due to dodgy sectors,
recommendations is that you get a new card. I have a Sandisk SDHC 8GB class 4. Would be fine for a
few installs, but then would seem to corrput. You’ll know when it becomes corrupt as it’ll start scrolling
errors up the page and lots of red warnings, you may also get errors on boot sectors and will ask you to
run fsk!
Going to give a Trascend 8GB Class 10 a go instead!
Constant Reboots.
I had this today with a student’s PI.... it just kept rebooting. It failed at some point while booting, seemed
to have to a check of the filesystem on the memory card,, find an error and reboot (ad infinitum). Turned
out this was a dodgy power cable (between the Pi and the USB from the Computer powering it!) 19
Thanks for this one Lloyd.
Reboots when you plug something USB in!
Many devices, often WIFI dongles etc can cause the Pi to reboot when inserted. Some devices are fine
(it tends to be the lower power ones!) Most USB Pendrives don’t cause the system to reboot (often you
might have to do the keyboard/mouse/memory stick shuffle if you don’t have a hub handy! However I
discovered today that Verbatim Blue USB did cause the Pi to reboot!
Falling off the Network Randomly
I had this wth a a Pi running powered by a PC, turns out it was the cable that was supplying power.
Some cables just do NOT work. Took me a while, I suspected the Pi, or memory card, however it was
just the cable. The Pi would appear on the network for a while, maybe run a few commands, then would
just drop off. You’d get an occasional error on boot.
Apt-get update Fails.
if apt-get update fails, it could be for a few reasons. First check /etc/apt/apt.conf and check your proxy
is not still set, second check /etc/bash.bashrc and check the proxy lines (usually added at the end).
However if it can connect, but fails when building, or comes up with Reading package lists... Error!
It might be something has become a little corrupt. Well worth trying the following. Fixed it for me.
Run
sudo apt-get clean
It will often tell you where the error occured, e.g.
E: Error occurred while processing libwww-mechanize-perl (NewVersion2)
or E: Error occurred while processing gnoemoe (NewVersion2)
So after a bit of googling I ran this…
sudo rm /var/lib/apt/lists/mirrordirector.raspbian.org_raspbian_dists_wheezy_main_binary-armhf_Packages
however you might have to run.
sudo rm /var/lib/apt/lists/* -vf
sudo apt-get update
No diversion 'diversion
You will sometimes get this error when running apt-get update / upgrades. It is due to dependencies not
met when updating. You WILL NEED to REBOOT. However I suspect this ruined the memory card and
the Pi no longer booted. Perhaps running the Rpi-Update FIRST would have helped?
20
IF YOU FILL YOUR MEMORY CARD!!!
At some points you might befoolishlly fill your memory card, this could be if you have done too many aptget installs, or perhaps copied a large folder, porracross, like Minecraft or Quake3.
use
sudo apt-get purge <program>
to remove anything big you've put in recently, e.g. VLC, or TightVNCServer (see the optional list at the
top of the document). you may need to do 'su root' to get access to this.
After that run 'ls' in the /home/pi folder and see what's installed there.
You can then use
sudo rm -rf <folder>,
things like Quake3 and Minecraft can get quite large, especially if you've installed custom maps /
models!
Once you've finished messing can I recommend running
sudo apt-get autoremove && sudo apt-get autoclean
For me it freed up over 200MB!!!!
21
SSH on the school system???
Most managed networks at school will not allow students to have access to SSH, it will be considered
a security risk. However I know that it does work (as I can run extra software on my Laptop!) However
if you want kids to have the benefits of SSH (and they’ll be doing lots of copy and pasting of code!)
why not get them using a LiveUSB of Linux (Full blown linux, either Ubuntu or Mint!) I’ve recently been
doing some testing of Linux distros, mainly due to an overzealous student wiping his netbook in a fit of
rage! The netbook an Acer Aspire One (225) or similar would happily boot a LiveUSB of linux, but would
not install the bootloader so when you tried an install you just got left with a blank screen maybe with
a flashing cursor! However we tested lots of version of the LiveUSB (Ubuntu) in the hope one of them
would work. Verion 9 went on okay, but didn’t isntall the network card drivers… useful NOT. However
in all fairness, Mint went on flawlessly, and worked out of the box. The student seemed much happier
using than windoze. So much so that I’ve been dabbling with it all evening and I’m typing this on my
school laptop (running a LiveUSB (2GB tiny stick burnt with Win32Imager)) and am quite liking it. It’s
responsive and stable (well Firefox is, Chromium (which I tried installing) not so much, but at least unlike
Windows wouldn’t crash out completely, but would discreetly kill the page in question! However I tried
an ‘apt-get update and upgrade’, this no longer fit on the 2GB stick (be warned!)
I have managed to pilfer a couple of old laptops that I intend to hook up to the school network running
LiveUSB versions of MINT, and see how they go. In theory they /etc/apt/apt.conf and /etc/bash.bashrc
edits should be enough to get them up and running! :)
22
Using both Wireless and Wired connections (Untested Sofar!)
http://onlineextremist.com/blog/2013/07/06/configuring-wireless-interfaces-on-the-raspberry-pi/
This is me trying to be sneaky so that I can quickly connect to my phone as a WIFI point or use the
school setup if the wireless is not available.
First install ifmetric
sudo apt-get install ifmetric
now edit the /etc/network/interfaces file
sudo nano /etc/network/interfaces
## Loopback interface - this is pretty much standard for everyone
auto lo
iface lo inet loopback
## Wired ethernet interface
#Set both of these to hotplug.
allow-hotplug eth0
iface eth0 inet dhcp
#The LOWER the metric the higher priority, so 0 takes preference over 1!
metric 1
## Wireless interface
#auto wlan0
allow-hotplug wlan0
iface wlan0 inet manual
#This line needs to be in so that it can use the WPA Key entered via WPA_Gui in X
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
#The wireless should take priority if available.
metric 0
## Default connection
# This needs to be at the end
iface default inet dhcp
SAVE this file and reboot!
23
The Hardware
18
All this document is designed to work on a Raspberry Pi Model B (preferably version 2.0), but some may
work with the 256 MB Version.
I’m guessing if you’ve reading this you either have a Pi, an interest in one, or at least held one! Please
note, version 1 has a black headphone socket, and no mount holes. Version 2 has a blue headphone
socket and mount holes in all 4 corners of hte board. (version 1 pictured ablove)
The key specs of Rapsberry Pi (a.k.a RasPi) are:
Linux based operating system
●
●
●
●
●
●
●
●
700 MHz ARM11 CPU
256MB (or 512MB) RAM
SD Card Storage
2 USB ports
Composite and HDMI Video out
Stereo audio out
8 GPIO pins
Wired Ethernet
24
25
How to check what RPi.GPIO version you have
This works for all versions of RPi.GPIO
find /usr | grep -i gpio
And the output will look something like this (although there will be more of it)…
You can see all those lines with 0.5.3a.egg-info telling me I have version 0.5.3a.
How to check your Raspberry Pi Revision number?
There’s a way to see what your Pi Revision is…
cat /proc/cpuinfo
You can see this gives lots of info. Near the bottom is “Revision : 000f”
This tells me I have a Rev 2 Pi, but it’s a bit clunky. There are several different rev. codes for different
Pi models and manufacturers (here’s a list of them). We could write some code to check the cpuinfo
and extract the bit we want, compare it with known revision codes etc. But we don’t need any of that
because, from RPi.GPIO 0.4.0a onwards (September 2012) we can use a built-in RPi.GPIO variable
which does it all for us.
26
DISTROs.
20
NOOBS SELECTER(- RECOMMENDED)- http://www.raspberrypi.org/downloads
Raspbian (Wheezy) (RECOMMENDED)- http://www.raspberrypi.org/downloads
Raspbian - http://www.raspbian.org/ or http://www.raspbian.org/HexxehImages
Login pi
Password raspberry
ArchLinux - http://archlinuxarm.org/packages
RASPBMC - http://www.raspbmc.com/
XBian - http://xbian.org/download/
27
Backing up the Memorycard using the PI (working)
http://learn.adafruit.com/adafruit-raspberry-pi-lesson-1-preparing-and-sd-card-for-your-raspberry-pi/
make-a-backup-image
Use wget to get the file off pastebin.
wget http://pastebin.com/raw.php?i=48fr9BAS
Then rename the file backup.sh
mv raw.php?i=<tab> rpi_clone.sh
If you're not sure that sda is the right card, you can run this command to list the cards connected to your
Pi.
sudo fdisk -l
The SD card slot with your running Pi system will show up as /dev/mmcblk0. Your blank card will be
listed as /dev/sda1 (or possibly /dev/sdb1, if you have more than one USB card readers attached to the
Pi).
Note that you don't enter the '1' - if your card is listed as '/dev/sda1', then you would still enter 'sda' when
you run the script ('sda' is the name of the card, 'sda1' is the name of the first partition on the card).
Ok, so now you should be ready to run the commands
chmod +x rpi_clone.sh
sudo ./rpi_clone.sh sda -f
As noted earlier, the first parameter passed to the script is is the name of the target SD card, in this
case 'sda'. The -f tells the script to entirely re-format the card.
The script will ask you if you're sure you want to initialize the destination card. Type 'y', and hit the return
key.
I edited the scipt to make an mro-rpi-backup.sh (using nano), if you edit out the read commands carefully
you can make the script run without intervention. That also means you can clone to multiple cards one
after another .
do fdisk -l (I found you had to have the card in the reader first, then connect to hub!) fdisk should
show your disks. E.g. sda1, then sdb1 etc.
You can then run using
sudo ./mro-rpi-backup.sh sdb -f && sudo ./mro-rpi-backup.sh sda -f
28
Setup Raspbian Memory Split and config.
raspi-config
I would recommend a 256/256 split and you can comfortmably overclock to 900 MHz (Medium) setting.
Update and Install updated packages!
(First time you run these it might take a while, maybe an hour or so!)
sudo
sudo
sudo
sudo
apt-get update
apt-get upgrade -y
apt-get install rpi-update
rpi-update
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get install -y git dialog
sudo apt-get dist-upgrade
Or run both at once.
sudo apt-get update && sudo apt-get dist-upgrade && sudo apt-get upgrade && sudo
autoremove && sudo autoclean
Recommended Packages to Install (You’ll probably need them later!)
(DON’T RUN THIS ON A 4GB CARD, You’ll run out of space!!!!)
sudo apt-get update
sudo apt-get install usbmount espeak mpg321 ffmpeg imagemagick fbi sox samba samba-common-bin gitcore xboxdrv wminput wmgui jstest-gtk bluetooth bluez-utils bluez-compat bluez-hcidump libusb-dev
libbluetooth-dev libsdl-dev joystick checkinstall pyqt4-dev-tools python-setuptools python-pip pythondev python-cwiid dialog motion flac jstest-gtk iceweasel rpi-update youtube-dl minicom apache2 php5
libapache2-mod-php5 libarchive-dev zbar-tools python-qrtools qtqr -y
Optional Fancies.
sudo apt-get install vlc cups geany tightvncserver blueman arduino gnash browser-plugin-gnash
sudo reboot
RPi-update - Firmware
An easier way to update the firmware of your Raspberry Pi. (not working at school, proxy issue?)
Preparations
You need git installed to use this too. To install run:
sudo apt-get install git-core
29
Installing
To install the tool, run the following command:
sudo wget http://goo.gl/1BOfJ -O /usr/bin/rpi-update && sudo chmod +x /usr/bin/rpiupdate
Updating
Then, to update your firmware, just run the following command:
sudo rpi-update
Randomized Learning
You can add the following line (command) at the end of your '/etc/bash.bashrc' file
sudo nano /etc/bash.bashrc
echo "Did you know that:"; whatis $(ls /bin | shuf -n 1)
Every time you open the terminal you will learn something about a random command.
GitHubs Worth Cloning
Install the software to manage GITHUBS
sudo apt-get install git-core
Then clone the GIT using. (sometimes you have to remove the ‘s’ off the https to get access to the files!)
git clone <git>
https://github.com/rpl/python-wiimote-hacks.git - WiiMote Hacks.
https://github.com/brooksc/mcpipy.git - Minecraft Python Scripts.
https://github.com/martinohanlon/minecraft-renderObj.git - Minecraft Obj
https://github.com/raspberrypi/quake3.git - Quake 3.
https://github.com/chep/snes9x-rpi - Snes9x-rpi
https://github.com/peterlavelle/maplinarm - Maplin Robot Arm.
https://github.com/walac/pyusb.git - Python USB Libs (needed for Robot Arm and Rocket Launcher!)
https://github.com/petrockblog/RetroPie-Setup - RetroPie (Emulation Station!)
https://github.com/dozencrows/motion - Motion for Use with the Pi Camera.
Backing up files to GDrive (Tested)
30
http://raspberrywebserver.com/serveradmin/back-up-your-pi-to-your-googledrive.html#.UjkKbFhmu1s.twitter
The trouble with this is that it syncs with GDrive, i.e. not only will it upload to GDrive, but it will
aslo LEECH down all your GDrive docs!
However this script could be useful for Zipping the entire content of the home directory for use later!!!
Save as Backup.sh
use
cmod -x Backup.sh
to make it executable.
#!/bin/bash
tar -crvf backup_$(date +%y.%m.%d).tar /home/pi --exclude="/home/pi/
google_drive"
gzip backup_$(date +%y.%m.%d).tar
mv backup_$(date +%y.%m.%d).tar.gz ./google_drive
cd ./google_drive
./grive
cd ..
31
PC Software to get familiar with
24
All these apps have portable versions (so you don’t have to install anything, and can run from a memory
stick!)
SSH - KitttySSH or Putty
This will allow you to remotley connect to your Pi, all you have to know is the ipaddress of your pi
(ifconfig), then try connecting to it. MEGA useful and will run on just about any system (there are
portable versions kicking about too!). Note if SSH-ing from Linux (e.g. Live CD), just goto the terminal
and use ‘ssh pi:raspberry@<ipaddress>’ the computer should then try connecting, you might have to
accept a key or similar and enter your password
Note to run a command on the Pi that contineus even if you exit the terminal ssh session then you can
use the Screen utility to prevent it from closing when you disconnect, e.g.
(sudo apt-get install screen)
screen /home/pi/picam.py
WIN32Imager
You will probably use this every once in a while to flash your cards when you screw them up, or find a
new OS you wish to try out! Dead easy to run, just make sure you install the IMG file to the memory
card and not a HDD, many images come bundled with this in a Zip File! I discovered recently that this
program is also really good at producing LIVE USBs of Linux Distros, you download a Linux ISO, you’ll
have to browse for the file (show all files) as it doesn’t list it, but then you an select the USB and it will
produce a working copy. Tested for both Ubuntu (various versions) and Linux Mint!
7Zip
Well worth a mention as it let you Unzip, Uncompact, Uncompress just about anything including TARs.
Advanced IP Scanner
If you want to remote to your Pi and you don’t know the IP address as it’s setup with DHCP and not
STATIC IP address.
UltraVNC (Portable)
At some point you might want to run your PI headless and yet still have access to X and all the wonders
of the GUI (see guide later for setting up VNC), but this app is pretty good and free.
Geany / Ninja IDE. (versions available for both Windoze and PI!)
If you’re coding in Python it’s probably a good place to start, a versatile IDE.
apt-get install ninja-ide
apt-get install geany
32
WinSCP
Very good for similar FTP for PI, great for getting files on / off a Pi Quickly!
Xming / Xming Portable (not got this working for me! :( )
For this I use the portable version, which allows you to not install, run the Xming +putty.bat file. Starts
Xming (from the system tray start a new Putty session) ensure under SSH that X11 is selected (not got
this to work yet!)
MobaXTerm - Works as well as VNC
Free for personal use.
First, you will need to download and extract a copy of MobaXterm (as of 2/9/2013 the current version is 6.5). Once you have
extracted the files, double click on MobaXterm_Personal_6.1
Click on the Sessions button at the top of the window. Choose New Session. Choose SSH as the session type. In the Host
field enter the IP address of your RasPi. Leave the port set to 22. You can also at this point enter the username that you will be
using. Make sure that “X11-Forwarding” is checked. Choose “LXDE desktop” for the remote environment type. Click on OK
at the bottom.
Once you click on OK you will see an X11 window open on your desktop. You may have to move it out of the way to enter
credentials into the SSH window. Once you enter credentials and choose whether or not you want to save your password you
should then (after a couple of moments) see the desktop of your RasPi.
NOTE: I am using the Raspian “wheezy” OS on my Raspberry Pi. However, the instructions above will most likely work for a
majority of Linux distributions as long as XDMCP login is enabled.
LILI USB - Live USB Stick Creator with Persistence.
A nice little utility for windows that will allow you to create a Live CD/USB stick from any distro you
donwload. I found this to be reliable and consistant.
33
Phone / Mobile Device Software
Fing
Free
A good tool to get
an overview of the
devices on your
local network.
iPhone / iPad
Android Version
BerryCam
Free
Remotely take an
view photos from
the rapsberry pi
camera.
iPhone / iPad
Ardumote
£2.49
An app to control
arduinos ,but can
be used to ontrol
GPIO pins
iPhone / iPad
MPod
Free
Prompt
£5.50
ssh from your
iPhone/iPad
iPhone/iPad
Server
Auditor
FREE
A better SSH
program for
iPhone / iPad, and
it’s FREE
iPhone/iPad
Pi Buddy
FREE
iPhone/iPad
https://
github.com/
TheGreenToast
er/web-pins
iPhone/iPod
-
34
Useful Linux Commands
26
Command
Args
Usage.
chmod
-R 775
Sometimes files need their properties changing, readonly and suchlike. To sort that use
sudo chmod -R 775 <filepath>
+r=read , +w=write, +x=executable, -R = recursive.
chown
-R <user>
<folder>
Sometimes you might want to have write access to a folder
and the files withing. Some folders only allow ROOT
access , check using ls -l, but then you can change the
permissions e.g. for apache server / php
sudo chown -R pi /var/www
cd ~
~
Takes you to your home dir.
ls
ls / lsusb/ -l
Lists, either files / folder / devices (lsusb good checking for
usb devices) -l will print out the file attributes too, e.g. write,
executable etc. You can also check ownership of a folder
etc.
mv
<old> <new>
Rename a file, mv <file1.ext> <newname.ext>
cp
cp <current>
<new>
Copy the file from one location to another.
mkdir
<foldername>
Make a Directory within your current directory.
rm
<filename>
Delete / Remove a file (use the -rf if trying to delete a folder
with contents of files!).
ifconfig
ifconfig
Get your current network info.
hcitool
dev / scan
Check for bluetooth devices and what’s happening.
nano
<filename>
Brings up simple text editor for you to mess with config
files etc.
vi
<filename>
Brings up the VI editor, an alternative to Nano and shows
line numbers.
less
<xzy>| less
You know when you run something and it scrolls 12
pages of text up the screen, well the ‘LESS’ command lets
you look through it a page at a time! <press any key to
continue>
apt-get install
<package>
choose some software to install.
apt-get purge
<package>
removes a package from your system! AND all it’s settings
/ config etc.
apt-cache
search
<keyword>
You know you’ve just updated your packages list, well you
can search the cache!!! e.g. ‘apt-cache search chrom’, not
you may want to use ‘| less’
35
history
history
Gives you the previous commands typed at the BASH!
You can run any of these commands using ‘!
<commandno>
e.g. !333 would run command 333 from the list!
dmesg
dmesg | grep ^
<searchterm>
dmesg prints out all the messages from the kernel since
the Pi was last powered ON!, this can be a lot. Using the
grep tool you can channel this text through it and then
search it!
grep
grep ^<term>
search through whatever you trying to push through grep.
>
<filename>
Using this simple symbol you can dump the output from
the bash straight into a specified file for looking at later!
wget
<url>
Great if you just want to grab a file or zip off the internet.
-help
wget –help | less
Great for getting help on commands.
du
du
Gives you current disk usage, good for finding out how
much space you have left (numbers in bytes I think!)
df
df | less
Shows you the size of folder on the PI, good for weeding
out big programs / blockages etc.
-R
chmod -R xyz
-R is used to mean recursive, meaning not just applied to
the file / folder, but all of it’s contents too!!!
ps
ps | grep <xyz>
Lists all the programs running on your pi. Use the Grep to
filter down the long list!!!
&&
<c1> && <c2>
Lets you run one command, wait for it to finish then run the
second, eg. apt-get update && apt-get upgrado
&
<c1> &
Will allow you to run a command or program in the
background and start something else! (run with the &) once
running press enter and the command line will be yours
again.
depmod
depmod -a
Sometimes you will be required to add drivers
manually to Linux (often for wonky hardware!) these
often come in the form of .ko files (when untar’d)
The will often need to be copied to the right folder
e.g. /lib/modules/3.6.11/kernel/drivers/... but then
you need to update the OS to know you’ve put it there!
That is what this command does, at least that’s what I
think it does!
file
file <xyz>
informs you what format your file is.
cat
cat [filename]
| less .
Will just churn out the contents of a file to the
prompt for quick viewing.
fbi
fbi -u -T -t 6
xyz.jpg
FBI is a nice little command line image viewer. You
can run this remotley usying the -T switch. You can
also set it to display a random image from a folder
using /**/* e.g. /home/pi/PiFrame/**/*
whatis
whatis
<command>
e.g. whatis apt-get or whatis mpg123
36
37
A note about the command prompt
When using the command prompt, the colours of headings mean different things.
Also by typing file <xyz> it will tell you what format the file is!
Installing Software / Drivers
Many times in this document you will come across apt-get which is one particular way of installing
updates to software and drivers... However there are alternative managers out there.
Aptitude (base on apt-get) will run in or outside of X.
Synaptic - A software visual installer designed to be used within X.
Using NANO Guide
- http://www.raspberrypi-spy.co.uk/2013/11/quick-guide-to-nano-text-editor-on-the-raspberry-pi/
Control
Meta
Description
CTRL+G
Display the help text
CTRL+X
Close the current file buffer / Exit from nano
CTRL+O
Write the current file to disk
CTRL+R
Insert another file into the current one
CTRL+W
Search for a string or a regular expression
CTRL+\\
ALT+W
Repeat last search
ALT+R
Replace a string or a regular expression
CTRL+K
Cut the current line and store it in the cutbuffer
ALT+6
CTRL+U
Copy the current line and store it in the cutbuffer
Paste from the cutbuffer into the current line
ALT+T
Cut from the cursor position to the end of the file
ALT+A
Mark text at the cursor position
38
CTRL+C
CTRL+_
Display the position of the cursor
ALT+G
CTRL+T
Go to line and column number
Invoke the spell checker, if available
ALT+}
Indent the current line
ALT+{
Unindent the current line
CTRL+Y
Move to the previous screen
CTRL+V
Move to the next screen
CTRL+F
Move forward one character
CTRL+B
Move back one character
CTRL+Space
Move forward one word
ALT+Space
Move back one word
CTRL+P
Move to the previous line
CTRL+N
Move to the next line
CTRL+A
Move to the beginning of the current line
CTRL+E
Move to the end of the current line
ALT+( or ALT+9
Move to the beginning of the current paragraph
ALT+) or ALT+0
Move to the end of the current paragraph
ALT+\\ or ALT+|
Move to the first line of the file
ALT+/ or ALT+?
Move to the last line of the file
ALT+]
Move to the matching bracket
ALT+- or ALT+_
Scroll up one line without scrolling the cursor
ALT++ or ALT+=
Scroll down one line without scrolling the cursor
ALT+< or ALT+,
Switch to the previous file buffer
ALT+> or ALT+.
Switch to the next file buffer
ALT+V
Insert the next keystroke verbatim
CTRL+I
Insert a tab at the cursor position
CTRL+M
Insert a newline at the cursor position
CTRL+D
Delete the character under the cursor
CTRL+H
Delete the character to the left of the cursor
CTRL+J
Justify the current paragraph
ALT+J
Justify the entire file
39
ALT+D
CTRL+L
Count the number of words, lines, and characters
Refresh (redraw) the current screen
ALT+X
Help mode enable/disable
ALT+C
Constant cursor position display enable/disable
ALT+O
Use of one more line for editing enable/disable
ALT+S
Smooth scrolling enable/disable
ALT+P
Whitespace display enable/disable
ALT+Y
Color syntax highlighting enable/disable
ALT+H
Smart home key enable/disable
ALT+I
Auto indent enable/disable
ALT+K
Cut to end enable/disable
ALT+L
Long line wrapping enable/disable
ALT+Q
Conversion of typed tabs to spaces enable/disable
ALT+B
Backup files enable/disable
ALT+F
Multiple file buffers enable/disable
ALT+M
Mouse support enable/disable
ALT+N
No conversion from DOS/Mac format enable/disable
ALT+Z
Suspension enable/disable
Using GREP Properly.
Grep is a very powerful tool. I can be used to find things with a file, a lot of files, or several
directories of files.
Basic syntax
grep <something> <in file>
e.g.
grep 'string' *.txt
Useful for finding the word string in all .txt files in a folder, but could be made better.
Additional Arguments
--color=auto = Makes it easy to read pretty colours!
-R : Recursive (look at all the folders inside your folder too!)
-i : ignore case, so will find all occurences of ‘string’ ‘STRING’ ‘String’ or variants.
40
-n : Prefix each line of output with the 1-based line number within its input file.
-H Print the file name for each match. This is the default when there is more than one file
to search.
so... using
grep --color=auto -iRnH ‘string’ *.txt
Will return everything in all your folders (drilled down from current location), tell you the file it came from,
the line number and be prettily coloured!
A nice simple guide with more examples here
41
SYSTEM
30
Using ‘screen’
http://www.tecmint.com/screen-command-examples-to-manage-linux-terminals/
Often I do a lot of my work remotely with a PI, from a laptop or an ipad via SSH, the only trouble is that
if you’re running a command like wget or someting that will take a long time you are not always in a
position to wait for it to finish. This is where SCREEN comes inhandy
sudo apt-get install screen
What this program allows you to do is open up a virtual screen that you can connect /disconnect from
(while it‘s still doing stuff) and then reconnect back to it later.
To invoke screen type
screen
innocently this will popup with a menu, you’ve just created your virtual screen, it will now work like a
normal SSH window.
When you want to detach from it use
Ctrl+a+d (A bit awkward, but still)
to reattach yourself at a later date use
screen -r
Setting a Static IP (network address)
# Find out what address your router assigned to your RPi.
ifconfig
# Edit the network settings to use a STATIC IP address.
# NOTE: To make it easy use the same settings your router assigned to your RPi.
sudo nano /etc/network/interfaces
# Comment out the DHCP entry. Make the STATIC entry look something like this:
# NOTE: Tweak the address for your STATIC IP address.
auto eth0
iface eth0 inet static
address 192.168.1.xxx
netmask 255.255.255.0
42
broadcast 192.168.1.0
network 192.168.1.255
gateway 192.168.1.xxx
# Reboot the RPi
reboot
How to Change Your Raspberry Pi (or Other Linux Device’s) Hostname
The default hostname for the Raspberry Pi is, creatively enough, “raspberrypi“. What if you want a
different hostname or you want to avoid hostname conflicts on your local network? Read on as we show
you how to quickly change the hostname of a Linux-based device.
Why Do I Want to Do This?
There are two primary reasons why you would want to take a few minutes to edit the local hostname
of a Linux device on your network. The most common reason would simply be customization–it’s fun
to personalize things. Rather than leave your Raspberry Pi music station as plain old “raspberrypi“, for
example, you could rename it to “jukebox“.
The other reason you would want to customize the local host is to avoid name conflicts. If you, for
example, have purchased and set up three Raspberry Pi units, all three of them (assuming a default
Raspbian installation) will attempt to claim the local hostname “raspberrypi“.
The first one will succeed and the next two will fail to resolve their hostnames, leaving them blank in your
router’s device list (as seen in the screenshot above) and unreachable via hostname-based protocols
like Samba file sharing.
Fortunately it’s super simple, assuming you know where to perform a few quick edits, to change the
hostname of your Raspberry Pi (and most other Linux-based devices you have full access to). For
demonstration purposes we’ll be performing the change on a stock Raspbian installation, but the same
file edits will work on Debian, Ubuntu, and most other Linux platforms.
Changing the Host on your Pi
We have so many Raspberry Pi units around the office that a bunch of them are now in conflict. Today
we’re going to fix that by assigning unique names to each Pi unit based on their current function. A
perfect candidate for this renaming is our awesome Raspberry Pi weather station; it will be much easier
to identify it on the network once we change the hostname to “weatherstation“.
43
The first step is to either open up the terminal on the device or to SSH into the device and open up a
remote terminal. Our device is headless and currently running, so we’ll take the remote terminal route
and connect to it via SSH.
At the terminal, type the following command to open the hosts file:
sudo nano /etc/hosts
Your hosts file will look like so:
Leave all of the entries alone except for the very last entry labeled 127.0.1.1 with the hostname
“raspberrypi“. This is the only line you want to edit. Replace “raspberrypi” with whatever hostname you
desire. We replaced it on our device with “weatherstation“. Press CTRL+X to close the editor; agree to
overwrite the existing file and save it.
Back at the terminal, type the following command to open the hostname file:
sudo nano /etc/hostname
This file only contains your current hostname:
Replace the default “raspberrypi” with the same hostname you put in the previous step (e.g.
“weatherstation“). Again, press CTRL+X to close the editor, agree to overwrite the existing file and save
it.
Finally, we need to commit the changes to the system and reboot the system for the changes to take
effect. At the terminal, enter the following command to commit the changes:
sudo /etc/init.d/hostname.sh
Follow that command with:
sudo reboot
Once the system comes back online, you can check the device list in your router to see if the new
hostname has properly resolved:
44
Success! Now instead of wandering the network without a name, our little Raspberry Pi weather station
has a hostname all its own.
Setting up Wi-Fi
http://pingbin.com/2012/12/setup-wifi-raspberry-pi/
Setting up ad-hoc wifi
To actually be able to use wi-fi outdoors, I followed debian's documentation on setting up an ad-hoc
network:
RASPBERRY PI
sudo nano /etc/network/interfaces:
auto wlan0
iface wlan0 inet static
address 192.168.1.1
netmask 255.255.255.0
gateway 192.168.1.2
wireless-channel 1
wireless-essid MYNETWORK
wireless-mode ad-hoc
On the linux laptop: use gnome network manager to connect to MYNETWORK, but set a manual IP
address of 192.168.1.2, with a gateway of 192.168.1.1. Take note that ad-hoc is NOT supported in all of
linux wifi drivers. (Ralink 2500 does not support it, neither do most Realtek chips)
Testing Internet Connection Speed with Wget
If you prefer using wget, or that is what you have installed, the switch is the same. That
is a capital letter “o” and it sends the output straight to null, so you don’t have any files to
delete.
wget -O /dev/null http://speedtest.sea01.softlayer.com/downloads/test100.zip
45
School Site Proxy Info (to remember)
Edit this file to set Permanently Across All Profiles.
sudo nano /etc/apt/apt.conf
Add the following lines:
Acquire::http::proxy “http://10.173.0.28:9090/”;
Acquire::ftp::proxy “http://10.173.0.28:9090/”;
Acquire::https::proxy “http://10.173.0.28:9090/”;
(if you copy and paste, check the “ go across properly!)
save in Nano using ctrl+o, enter, then quit ctrl+x)
Allow programs other than Bash access to a (school) network under Proxy.
In additoin to enable in things like Midori etc (not just the bash use this), is suspect Git Clone will not
work without this addition too!
Edit the following file with NANO (N.B. I think this is needed to used git clone behind a proxy!)
sudo nano /etc/bash.bashrc
add to the bottom
export http_proxy=http://10.173.0.28:9090/
export https_proxy=http://10.173.0.28:9090/
export ftp_proxy=http://10.173.0.28:9090/
Temporarily from the LXTerminal (not ideal and only works for ROOT!)
export http_proxy=http://10.173.0.28:9090
export ftp_proxy=http://10.173.0.28:9090
export https_proxy=http://10.173.0.28:9090
Use ifconfig to check on your Pi’s current network status and then try a sudo apt-get update to see if
it can connect and update!.
Changing the Font Size of the Terminal Text
Run this command and then step through the menus. I can recommend ‘Terminus Font’
16x12 makes it a bit easier to read! (thanks to Lloyd for this one!)
sudo dpkg-reconfigure console-setup
- UTF-8
- Guess Optimal Character Set
46
- Choose Terminus
- 16x32
Choosing which programs run when the Pi boots
/etc/rc.local is a script on the Raspberry Pi which runs when Linux first boots. To edit it, you will need
root privileges:
sudo nano /etc/rc.local
If you want to run one of your Python scripts at start-up, add this to the end of rc.local:
python <yourscriptname>.py
To stop a script running, either delete the line it is on, or comment it out (add a # at the beginning of the
line).
47
Creating Icons to your programs on the desktop in X
Create a new text file called yourname.desktop in the /home/pi/Desktop/ directory, e.g. /home/pi/
Desktop/yourname.desktop
It should contain the following:
[Desktop Entry]
Name=My Name
Comment=My application which does this
Icon=/usr/share/pixmaps/openbox.png
Exec=/usr/bin/leafpad
Type=Application
Encoding=UTF-8
Terminal=false
Categories=None;
Goto GOOGLE and search for xyz.png (the PNG type defintiely works!)
You’re looking for an image that is 48x48 or 64x64 (square)
Use the ADVANCED GOOGLE IMAGE search and look for Icons.
e.g.
[Desktop Entry]
Name=Minecraft
Comment=This *SHOULD* launch Minecraft
Icon=/home/pi/mcpi/minecraft.png
Exec=/home/pi/mcpi/./minecraft-pi
Type=Application
Encoding=UTF-8
Terminal=false
Categories=None;
Name – The name you want displayed
Comment – Your comment
Icon – A file to use for the icon. Your own or have a look in the /usr/share/pixmaps/ directory for
something suitable.
Exec – The executable (can include sudo if your executable uses the IO). Can be the name of an
executable program, or more complex, e.g. Exec=lxterminal –command "less /root/README.TXT"
Executing A Command In LX Terminal via a Desktop Icon
The following will open LX terminal, wait for 5 seconds and then it will close:
[Desktop Entry]
Name=Name to be shown on desktop
Comment=My comment
Icon=/usr/share/pixmaps/openbox.xpm
Exec=lxterminal -t "Tile to display" -e sleep 5
Type=Application
Encoding=UTF-8
Terminal=false
Categories=None;
48
LX Terminal will auto close once the command is complete. You can't give more than 1 command in
the -e launch options (you can't give it "-e dosomething ; sleep 5" for instance as a way to make it hold
showing the result after dosomething.
Running Applications in Kiosk (Fullscreen Mode)
http://www.instructables.com/id/Raspberry-Pi-Wall-Mounted-Google-Calendar/?ALLSTEPS
A good tutuorial on how to setup the screen to show your google calendar, fullscreen using ICEWEASEL
(Firefox equivalent for Pi)
We also want Iceweasel to start automatically so we’ll need to change the autostart options.
sudo nano /etc/xdg/lxsession/LXDE/autostart
add @iceweasel to the list
now press ctrl+x the Y and enter to save the changes
The next step is to get rid of that pesky mouse cursor and stop the screen from going to powersave/
sleep mode.
First we’ll install Unclutter to get rid of the cursor when it’s not in use.
sudo apt-get install unclutter
Now we need to edit the /etc/lightdm/lightdm.conf file to prevent powersave/sleep mode
sudo nano /etc/lightdm/lightdm.conf
Move down to: [SeatDefaults]
Change this line:
#xserver-command=X
to this:
xserver-command=X -s 0 –dpms
now press ctrl+x the Y and enter to save the changes
A bit of Optimising / Tweaking (in Testing)
https://extremeshok.com/2012/07/22/raspberry-pi-raspbian-tuning-optimising-optimizing-for-reducedmemory-usage/
Replace Bash shell with Dash shell | Save: +1 MB RAM
Replacing Bash with Dash will increase the system’s overall performance ie. speed up the system boot, reduce
disk space, use fewer libraries (save memory) and is more reliable:
Dash is an acronym for Debian Almquist shell (dash). It is a Unix and Linux shell which is much smaller than bash
but still aiming at POSIX-compliancy. dash is a POSIX-compliant implementation of /bin/sh that aims to be as small
as possible. dash is a direct descendant of the NetBSD version of ash (the Almquist SHell), ported to Linux in early
1997. It was renamed to dash in 2002.
49
sudo dpkg-reconfigure dash
50
Setting up VNC
VNC - http://myraspberrypiexperience.blogspot.co.uk/p/setting-up-vnc.html
sudo apt-get install tightvncserver
vncserver :1 -geometry 1280x800 -depth 16 -pixelformat rgb565
- use Advanced IP Scanner to find the IP address (although is listed before you login!)
- Use SSH to run the VNC command.
- Use UltraVLC (set to ultramode with the IP followed by :1 (this is the connection number you setup)
Running VNCServer at Startup
http://learn.adafruit.com/adafruit-raspberry-pi-lesson-7-remote-control-with-vnc/running-vncserver-at-startup
Step 1.
Open a Terminal session on the Pi, or connect using SSH. A new terminal or SSH session will
automatically start you off in your home directory of /home/pi. If you are not in this directory, change to it
by typing:
cd /home/pi
Then cd to the .config directory by typing:
cd .config
Note the '.' at the start of the folder name. This makes it a hidden folder that will not show up when you
type 'ls'.
Step 2.
Issue the command below to create a new directory inside .config called 'autostart'.
mkdir autostart
cd into that new directory by typing:
cd autostart
Step 3.
All that remains is to edit a new configuration file. So type the following command to open the nano
editor on the new file:
nano tightvnc.desktop
Edit the contents of the file with the following text.
[Desktop Entry]
Type=Application
Name=TightVNC
Exec=vncserver :1
StartupNotify=false
Type ctrl-X and then Y to save the changes to the file.
Thats all there is to it. The next time you reboot the VNC server will restart automatically.
Web Interfacing with your Pi.
webiopi
http://trouch.com/2012/08/21/webiopi-control-your-pis-gpio-with-a-browser/
51
Installation
You only need Python, either 2.7 or 3.2. Download, then extract and install WebIOPi. The setup script will
automatically download and install required dependencies using apt-get. You may have to manually install GCC
and Python development headers if you are not using Raspbian.
$
$
$
$
wget http://webiopi.googlecode.com/files/WebIOPi-0.6.0.tar.gz
tar xvzf WebIOPi-0.6.0.tar.gz
cd WebIOPi-0.6.0
sudo ./setup.sh
Running WebIOPi
Finally, run Python using webiopi command :
$ sudo webiopi [-h] [-c config] [-l log] [-s script] [-d] [port]
Options:
-h, --help
Display this help
-c, --config file Load config from file
-l, --log
file Log to file
-s, --script file Load script from file
-d, --debug
Enable DEBUG
Arguments:
port
Port to bind the HTTP Server
You're done, and ready to enjoy WebIOPi ! But the server and GPIO state will be lost when you'll stop the script
(CTRL-C) or close the terminal.
Running WebIOPi (Daemon)
You can also start/stop the background service, the file /etc/webiopi/config will be used :
$ sudo /etc/init.d/webiopi start
and
$ sudo /etc/init.d/webiopi stop
Auto start at boot
You can even setup your system to start webiopi at startup :
$ sudo update-rc.d webiopi defaults
Usage
If your are directly using your Raspberry Pi with keyboard/mouse/display plugged, open a browser to http://
localhost:8000/
If your Raspberry Pi is connected to your network, you can open a browser to http://raspberrypi:8000/ with any
device of your network. Replace raspberrypi by its IP.
You can even add a port redirection on your router (and/or use IPv6) to control your GPIOs over Internet !
Default user is "webiopi" and password is "raspberry"
By choosing the GPIO Header link on the main page, you will be able to control GPIO using a web UI which looks
like the board header.
● Click/Tap the OUT/IN button to change GPIO direction.
● Click/Tap pins to change the GPIO output state.
52
53
Buddy Pi Setup - (part Tested)
https://github.com/TheGreenToaster/web-pins
web-pins
This is a simple interface for reading and controlling the GPIO pins on the Raspberry Pi
There are a few steps needed.
Install the requirements.
sudo apt-get update && apt-get upgrade
sudo apt-get install apache2 php5 mysql-client mysql-server tomcat6 vsftpd
Install GPIO Python library
wget http://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.1.0.tar.gz
tar zxf RPi.GPIO-0.1.0.tar.gz
cd RPi.GPIO-0.1.0
sudo python setup.py install
While in the www directory clone the web-pins folder
cd /var/www
git clone https://github.com/TheGreenToaster/web-pins.git
In order to allow the PHP to use the Python scripts the PHP user needs to be added to the sudoers file.
To enter the sudoers file use the command
sudo visudo
Next add the fallowing line to the end of the file and save it
54
www-data ALL=(ALL) NOPASSWD: ALL
Usage
In order to read the 0 pin the url is.
raspberrypiaddress/pi-read.php?pin=0
Simply replace the "0" with and number 0-7 to read that pin.
In order to set the value of pin 0 to high the url is.
raspberrypiaddress/pi-write.php?io=1&pin=0
To set value to low change
io=1
to
io=0
The "raspberrypiaddress"should be changed to the IP address of your pi.
Sound on the Pi.
Sound on the Pi is a funny, funny thing. The ALSA support isn’t great, but it seems to work *sometimes*
Check Alsa & remove Pulse!
First ensure the latest Alsa stuff is installed.
sudo apt-get install alsa-tools alsa-utils mpg321
sudo apt-get --purge remove pulseaudio
Test the sound using
sudo aplay /usr/share/sounds/alsa/Front_Center.wav
Force HDMI sound using
sudo amixer cset numid=3 <n>
where n=2 HDMI, n=1 Headphones, n=0 AUTO!
55
Making the Pi Speak
It is possible to make the Pi speak to you (think MS Voice) Simply install espeak
sudo apt-get update
sudo apt-get install espeak
the call the command using
espeak “Hello World”
You can find more info about using espeak, the various voices etc here.
There are other more complicated programs you can use e.g. Festival (reasons why are listed here http://www.element14.com/community/blogs/mirandasoft/2013/04/13/raspberry-pi-project-dedicatedspeech-synthesizer-without-gui
another version that can b used is FLITE, (Festival Lite)
sudo apt-get install flite
sudo flite -t ‘This is how you test it!’
To list all the voices available then us
sudo flite -lv
suod flite -voice <voice> -t ‘Testing AGAIN!’
SOX - The Swiss Knife of WAV / Raw audio on Linux
sudo apt-get install sox.
This program will allow you to convert / trim chop etc WAV or RAW audio files.
I found this useful in the PiRateRadio project listed later where I needed to convert audio to 22050 and
single (mono) channel for broadcasting over the FM!
sox <input file> -r 22050 <output file>
or you could import sound from espeak (see above) then PIPE this into sox
sudo espeak --stdout “Stick anything in here” | sox -t wav - -r 22050 test.wav channel
1
The sox tool needs to know what it is receiving, hence the ‘-t wav’, the next innoculous ‘-’ is actually the
input from the PIPE, ‘-r 22050’ resamples the audio.
further instuctions can be found here - http://billposer.org/Linguistics/Computation/SoxTutorial.html
imporing sound from a mic
sox -t alsa hw:1,0 -r 22050 testmic.wav silence 1 0 0.5% -1 1.0 1% &
56
MPG321
This handy tool lets you convert MP3s into WAVs for use with programs like SOX
sudo apt-get install mpg321
sudo mpg321 -w <output file> <input file>
I don’t know why the arguments seem backwards!
57
Turning your Raspberry Pi into an FM Transmitter
http://www.daveconroy.com/how-to-turn-your-raspberry-pi-into-a-fm-transmitter/
Grab the code
wget http://www.daveconroy.com/SampleCode/Pifm.tar.gz
tar -zxvf Pifm.tar.gz
Attach the Antennae
Find an 8 inch piece of plain wire, and attach it to the GPIO4
port on your Pi. Technically the is step is optional, but my
transmission range went from 200ft to 8 inches without it.
Use the picture below as a reference.
At school this made a difference of edge of my
room to the entire building!!!!
Step 3 – Run the Code
Usage: sudo ./pifm wavfile.wav [freq] [sample rate]
The second command line argument is the
frequency to transmit on, as a number in Mhz. For
example, this will transmit on 100.1 FM
sudo ./pifm sound.wav 100.1
You can use whatever frequency you'd like (88->108).
If you’re making your woen audio to bew palyed back out of theis, then you need to use 22050 sampling,
and make it mono. I’m not sure if that’s limitation of the pifm program? But a quick convert using SOX
will do the job!
sox <input file> -r 22050 <output file>
Or if you want to play back an mp3… then mpg321 then pipe into Sox.
sudo mpg321 -w <output file> <input file>
sudo mpg321 -s <input file> | sox - -r 22050 <output file>
sudo ./pifm <outfputfile> 101
Writing a Script to Monitor Mic Input
while [ true ]
do
#espeak --stdout "test 1234567890"|sox -t wav - -r 22050 test3.wav && ./pif$
#espeak --stdout "this is just another test to see if this little program w$
58
sudo sox -t alsa hw:1,0 -r 22050 testmic.wav silence 1 0 0.5% -1 1.0 1% &
./pifm testmic.wav 101
rm testmic.wav
#
done
A Better Live Mic Solution
http://www.raspberrypi.org/phpBB3/viewtopic.php?t=33526
arecord -fS16_LE -r 22050 -Dplughw:1,0 - | sudo ./pifm - 101 22050
Alright so:
arecord
Program we are using to record audio.
---------------------------------------------------------fS16_LE
Output 16-bit data. Needed this way for PiFM to read it.
---------------------------------------------------------r 22050
This specifies sampling rate to output recording. 22,050 is a good balance for speed and quality.
---------------------------------------------------------Dplughw:1,0
This is where you may need to modify. The '1' specifies card number and '0' is the device number I think. To find
this out for your device, use
arecord -l
to see all of the audio devices connected.
---------------------------------------------------------
Here it means to print output to standard out.
--------------------------------------------------------|
Pipe the standard out from previous command to next command's standard input.
--------------------------------------------------------sudo ./pifm - 100.1 22050
This is explained in the link at the top. '-' means use standard input for "file"(Remember we piped it). '100.1' is the
frequency in Mhz to transmit and '22050' is the sampling rate of the input. Actually if you change the sampling rate
lower it will output a low pitch sound and higher will do a high pitch sound, kind of a voice changer.
59
Playstation Microphones
If like me you have some old consoles kicking about it is worth noting that the Raspberry Pi will work
well with usb most microphones. I have tried a variety and all have worked. I have tried USB one's
like the ones you got with Rockband or Boogie (well worth picking up a cheap one!) or perhaps just as
useful there's one on the PS3 Eyetoy, you can pick these up VERY cheaply from Game (used to be
Gamestation, or Granger Games).
If you wish to use the PS2 Microphones (from Singstar) then please note apparently they will work, but
the reciever converts the Blue Mic into the left channel, and the Red to the right (although when I tested
it I got nothing from the RED!), so you simply get stereo input. Probably enough for most projects, but
for some like voice recognition they often only use the LEFT channel, the blue one! Apparently the
wireless mics work too!
60
Stream and Play Internet Radio Stations (Tested)
http://contractorwolf.wordpress.com/raspberry-pi-radio/
http://www.bobrathbone.com/raspberrypi/Raspberry%20PI%20Radio.pdf
http://www.instructables.com/id/Arduino-Raspberry-Pi-Internet-Radio/?ALLSTEPS
http://www.jan-holst.dk/pi-radio/pi-radio.html
http://www.suppertime.co.uk/blogmywiki/piradio/ - Setup that uses switches.
MPD - http://web.archive.org/web/20130623193912/http://miro.oorganica.com/raspberry-pi-mpd/
I’ve just setup MPD (Music Player Daemon) on my Rpi and it works beautifully.
Let get down to it:
Taking advantage of debian APT it is very simple to set it up:
sudo apt-get install mpd mpc
Where mpd is the daemon and mpc is the client.
"Radio Paradise" is the first station we'll add to get us off to a funky-retro start. To do that
we use mpc add as follows:
cd ~
(no add your stream in this form! -> mpc add http://stream-sd.radioparadise.com:8056)
I went ot planet rock instead and downloaded their live stream, or rather the link to ithtat would play
straight through XBMC (Playlist) - m3u (open this file as a test file, copy the link to the mp3 stream!)
mpc add http://tx.sharp-stream.com/icecast.php?i=planetrock.mp3
mpc play 1
You can add additional stations useing mpc add
The Arrow - http://ice-sov.musicradio.com/ArrowMP3
Kerrang - http://icy-e-03.sharp-stream.com/kerrang.aac
To list all the radiostations stored / current playlist
mpc playlist
You can get the number of the station from this.
To find out what the current song / track is use
mpc current
To tidy up the playlist you can use
mpc del <number>
To alter the volume you can use.
61
mpc volume <%>
A selection of Radiostations to tune into.
The Smooth Lounge: $ mpc add http://listen.radionomy.com/the-smooth-lounge
Radio Nova: $ mpc add http://radionova128.media.vistatec.ie:80
Newstalk: $ mpc add http://newstalk.fmstreams.com:8080
ClassicFM: - mpc add http://ice-the.musicradio.com:80/ClassicFMMP3
# Add BBC channels to MPC
mpc add http://bbcmedia.ic.llnwd.net/stream/bbcmedia_intl_lc_radio1_p?
s=1365376033&e=1365390433&h=a0fef58c2149248d6bff1f7b7b438931
mpc add http://bbcmedia.ic.llnwd.net/stream/bbcmedia_intl_lc_radio2_p?
s=1365376067&e=1365390467&h=d43dc8ae0f888809462a6cb7c389b46b
mpc add http://bbcmedia.ic.llnwd.net/stream/bbcmedia_intl_lc_radio3_p?
s=1365376123&e=1365390523&h=d53cf2a92272f3289b314a2251d23bc8
mpc add http://bbcmedia.ic.llnwd.net/stream/bbcmedia_intl_lc_radio4_p?
s=1365376126&e=1365390526&h=ed9a0642b30c422b07fbcd8683c52335
mpc add http://bbcmedia.ic.llnwd.net/stream/bbcmedia_intl_lc_5live_p?
s=1365376271&e=1365390671&h=e0d82133f35ae74d41d5eab6b9c150a6
mpc add http://bbcmedia.ic.llnwd.net/stream/bbcmedia_intl_lc_6music_p?
s=1365376386&e=1365390786&h=de40a9915206c4402c73e3766dc3fec0
A long list of stations (choose the MP3 option if available) can be found here - http://media-ice.musicradio.com/ or just Google ‘UK Radio M3U’
to find more links. (Save the M3U files, open in notepad/nano/text editor and copy link, use mpc add!)
http://www.radiofeeds.co.uk/mp3.asp
N.B. Not all radio stations broadcast 24 hours a day!
Each one will get a new number!, then use mpc play x to play it.
Note this runs like a daemon, whenever you reboot the Pi it will start playing the station again. Use
sudo mpc stop
This will just cancel the station playing NOT the daemon that will stay resident! :)
Using MPD - Music Player Daemon
To kill the daemon use :
sudo /etc/init.d/mpd stop
To restart the daemon use
sudo /etc/init.d/mpd start
or
sudo /etc/init.d/mpd restart
62
Check the status using
mpc
Autostart MPC without Daemon (MPD)
You can start mpc without mpd (but why wopuld you? by editing the etc/rc.local)
# Start radio when pi turns on
sudo nano /etc/rc.local
#At the bottom add the following line
mpc play
Control using mpod App like mpod or Android MPDroid?
63
Download music from GrooveShark (CLI) (TESTED but won’t work on school
network)
http://misapuntesde.com/post.php?id=241
People loves music and loves to accumulate hundreds of thousands of songs on their hard drives.
Today we have services like Spotify or GrooveShark to listen online what we want without having to
store them on our HDs...
...but if you are human and you still want to store it, we will see a way to download music from the
command line, as the pros likes ;)
You must to download the following code from the GitHub repositories:
git clone https://github.com/jacktheripper51/groove-dl.git
cd groove-dl/python
Enter the Python folder and find the song you like writing ./groove.py 'query'
Example:
sudo python groove.py ‘eve 6 rescue’
Choose which file to download,
then use
mplayer <filename>
to test!
64
Karaoke on the PI (Tested)
http://www.pi-fun.com/index.php?cID=1039
Installation
We don't need too much really.
First, make sure your Pi is up-to-date.
sudo apt-get update
sudo apt-get upgrade
Also, we recommend setting your overclocking on medium or turbo and you will need to enable SSH.
This is all done in:
sudo raspi-config
Set OVERCLOCK to medium (900 Hz)
We'll be using whitey as our youtube interface, which in turn uses omxplayer to play video.
sudo apt-get install youtube-dl
sudo youtube-dl --update
sudo youtube-dl -U
This installs the youtube side of things. Now for the interface
sudo apt-get install python-setuptools
sudo easy_install whitey
sudo apt-get install omxplayer
Now the Whitey side of things should be set up. Test it by running
pi-yt.
If you get gerrors you’ll have to do what I did which is replace a particular file!
cd /usr/local/lib/python2.7/dist-packages/whitey-0.4-py2.7.egg/yt/
mv __init__.py __init__.py.old
sudo wget http://github.com/rjw57/yt/blob/master/src/yt/__init__.py
Try it again!
Blanking the Console Screen
Another thing we want to do is blank the screen and remove the flashing cursor before playing any
videos, otherwise the video plays over any text you already have on screen (such as the login). Also,
we'll be starting and stopping pi-yt after every song, so we'll set up a simple script file to do all this for us.
Make sure you are in the /home/pi directory.
sudo nano k.sh
Now we need to add the following lines. You don't have to call the file k.sh btw, it's just what we used.
sudo dd if=/dev/zero of=/dev/fb0
sudo setterm -cursor off > /dev/tty1
pi-yt
65
Those first two lines clear the screen and remove the cursor. Now save the file (Ctrl-X) and lets make it
runnable.
sudo chmod 755 k.sh
Test this by running the file:
./k.sh
Now we will set up another script that will execute the microphone capture command. It's quite
a long-winded command hence the use of a script, as we also need to run this after every song.
Create a file like you did before; we called our one r.sh. Add the following line to it:
alsaloop -C hw:1,0 -P hw:0,0 -c 1 -t 12000
Note we are assuming you haven't got any other hardware plugged in. Your microphone should
be hw:1,0 and your sound output should be hw:0,0. This should be the case for most of us! Save
this file and again, make it executable with sudo chmod 755 [filename]
if you wish to use more than 1 mic use
arecord --list-devices
to get the device lists, the usual is hw:0,0
usually listed as
Subdevice #0: subdevice #0
66
Voice Recognition on the Pi using Google Voice API
http://blog.oscarliang.net/raspberry-pi-voice-recognition-works-like-siri/
sudo apt-get install ffmpeg
Create a script called Speech2text.sh
#!/bin/bash
And to make it executable.
echo "Recording... Press Ctrl+C to Stop."
arecord -D "plughw:1,0" -q -f cd -t wav | ffmpeg
-loglevel panic -y -i - -ar 16000 -acodec flac
file.flac > /dev/null 2>&1
chmod +x speech2text.sh
To run it
./speech2text.sh
echo "Processing..."
wget -q -U "Mozilla/5.0" --post-file file.flac -header "Content-Type: audio/x-flac; rate=16000"
-O - "http://www.google.com/speech-api/v1/
recognize?lang=en-us&client=chromium" | cut -d\"
-f12 >stt.txt
echo -n "You Said: "
cat stt.txt
rm file.flac
> /dev/null 2>&1
Asking Wolfram Alpha Questions
wget https://pypi.python.org/packages/source/w/wolframalpha/wolframalpha-1.0.2.zip
unzip wolframalpha-1.0.2.zip
sudo apt-get install python-setuptools easy_install pip
sudo python setup.py build
sudo python setup.py install
Getting the APP_ID
To get a unique Wolfram Alpha AppID, signup here for a Wolfram Alpha Application ID.
You should now be signed in to the Wolfram Alpha Developer Portal and, on the My Apps tab,
click the “Get an AppID” button and fill out the “Get a New AppID” form. Use any Application
name and description you like. Click the “Get AppID” button.
67
68
#!/usr/bin/python
import wolframalpha
import sys
Save as queryprocess.py
You may have to chmod 775 it.
# Get a free API key here http://
products.wolframalpha.com/api/
# This is a fake ID, go and get your own, instructions
on my blog.
app_id='6GG85Y-HGPWRKTG2L'
client = wolframalpha.Client(app_id)
query = ' '.join(sys.argv[1:])
res = client.query(query)
if len(res.pods) > 0:
texts = ""
pod = res.pods[1]
if pod.text:
texts = pod.text
else:
texts = "I have no answer for that"
# to skip ascii character in case of error
texts = texts.encode('ascii', 'ignore')
print texts
else:
print "Sorry, I am not sure."
test the script using
sudo ./queryprocess.py “What is the capital city of Germany”
Text To Speech
From the processed query, we are returned with an answer in text format. What we need to
do now is turning the text to audio speech. There are a few options available like Cepstral
or Festival, but I chose Google’s speech service due to its excellent quality. Here is a good
introductions of these software mentioned.
First of all, to play audio we need to install mplayer:
sudo apt-get install mplayer
We have this simple bash script. It downloads the MP3 file via the URL and plays it. Copy and
call it
text2speech.sh
#!/bin/bash
say() { local IFS=+;/usr/bin/mplayer -ao
alsa -really-quiet -noconsolecontrols "http:/
/translate.google.com/translate_tts?
tl=en&q=$*"; }
say $*
69
And to make it executable.
sudo chmod +x text2speech.sh
To test it, you can try
./text2speech.sh "My name is Oscar and I am testing the audio."
If it errors try
sudo nano /etc/mplayer/mplayer.conf
And put in the line at the end:
nolirc=yes
#!/bin/bash
Extended script for longer pieces of text.
Save over the top of text2speech.sh
INPUT=$*
STRINGNUM=0
ary=($INPUT)
for key in "${!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
for key in "${!SHORT[@]}"
do
say() { local IFS=+;/usr/bin/mplayer -ao alsa -reallyquiet -noconsolecontrols "http://translate.google.com/
translate_tts?tl=en&q=${SHORT[$key]}"; }
say $*
done
Combining Speech to Text and Text to Speech.
#!/bin/bash
echo "Recording... Press Ctrl+C to Stop."
./speech2text.sh
Save the script as main.sh
QUESTION=$(cat stt.txt)
echo "Me: ", $QUESTION
70
ANSWER=$(python queryprocess.py $QUESTION)
echo "Robot: ", $ANSWER
./text2speech.sh $ANSWER
sudo chmod 775 text2speech.sh
./main.sh
Alternative Google Voice Settings / Script
http://www.daveconroy.com/turn-raspberry-pi-translator-speech-recognition-playback-60-languages/
echo "Recording your Speech (Ctrl+C to Transcribe)"
arecord -D plughw:0,0 -q -f cd -t wav -d 0 -r 16000 | flac - -f --best --sample-rate 16000 -s -o
daveconroy.flac;
echo "Converting Speech to Text..."
wget -q -U "Mozilla/5.0" --post-file daveconroy.flac --header "Content-Type: audio/x-flac;
rate=16000" -O - "http://www.google.com/speech-api/v1/recognize?lang=en-us&client=chromium" | cut d\" -f12 > stt.txt
echo "You Said:"
value=`cat stt.txt`
echo "$value"
Microsoft Translation and Google Text to Speech
Now that we can record our voice and convert it into text, we need to translate it to our desired foreign language. I would
love to be able to use Google’s Translate tool for this, but unfortunately there is a20$ sign up fee for use of this API. I plan on
purchasing this for myself, but I wanted to make this project free so every one had an opportunity to try it.
As an alternative, we will be using Microsoft’s translate service which currently is still free for public use. The list of supported
languages and their corresponding codes can be found here. In our previous example we used a simple shell script, but for the
translation and playback process – I’ve written a more powerful python script.
All of this code can be found on my github repository (contributions welcome!).
Lets first create the file:
sudo nano PiTranslate.py
and add the following contents
71
import json
import requests
import urllib
import subprocess
import argparse
parser = argparse.ArgumentParser(description='This is a demo script by DaveConroy.com.')
parser.add_argument('-o','--origin_language', help='Origin Language',required=True)
parser.add_argument('-d','--destination_language', help='Destination Language', required=True)
parser.add_argument('-t','--text_to_translate', help='Text to Translate', required=True)
args = parser.parse_args()
## show values ##
print ("Origin: %s" % args.origin_language )
print ("Destination: %s" % args.destination_language )
print ("Text: %s" % args.text_to_translate )
text = args.text_to_translate
origin_language=args.origin_language
destination_language=args.destination_language
def speakOriginText(phrase):
googleSpeechURL = "http://translate.google.com/translate_tts?tl="+ origin_language +"&q=" + phrase
subprocess.call(["mplayer",googleSpeechURL], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def speakDestinationText(phrase):
googleSpeechURL = "http://translate.google.com/translate_tts?tl=" + destination_language +"&q=" + phrase
print googleSpeechURL
subprocess.call(["mplayer",googleSpeechURL], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
args = {
'client_id': '',#your client id here
'client_secret': '',#your azure secret here
'scope': 'http://api.microsofttranslator.com',
'grant_type': 'client_credentials'
}
oauth_url = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13'
oauth_junk = json.loads(requests.post(oauth_url,data=urllib.urlencode(args)).content)
translation_args = {
'text': text,
'to': destination_language,
'from': origin_language
}
headers={'Authorization': 'Bearer '+oauth_junk['access_token']}
translation_url = 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate?'
translation_result = requests.get(translation_url+urllib.urlencode(translation_args),headers=headers)
translation=translation_result.text[2:-1]
speakOriginText('Translating ' + translation_args["text"])
speakDestinationText(translation)
For the script to run we need to import a few python libraries and a media player.
sudo apt-get install python-pip mplayer
sudo pip install requests
The last thing we need to do before we can run the script is sign up for a Microsoft Azure Marketplace API key. To do so,
simply visit the marketplace, register an application, and then enter your client id and secret passcode into the script above.
Now we can run the script:
sudo python PiTranslate.py -o en -d es -t "hello my name is david conroy"
72
Putting it all Together
It is actually very easy to combine the two scripts we created in this tutorial. In fact, it only takes one line of code to be added to
the bottom of stt.sh shell script we created earlier (assuming PiTranslate.py and stt.sh are in the same directory).
sudo nano stt.sh
python PiTranslate.py -o en -d es -t "$value"
For those of you who skipped around in this tutorial, here is the entire script again with that line added:
echo "Recording your Speech (Ctrl+C to Transcribe)"
arecord -D plughw:0,0 -f cd -t wav -d 0 -q -r 16000 | flac - -s -f --best --sample-rate 16000 -o daveconroy.flac;
echo "Converting Speech to Text..."
wget -q -U "Mozilla/5.0" --post-file daveconroy.flac --header "Content-Type: audio/x-flac; rate=16000" -O - "http://
www.google.com/speech-api/v1/recognize?lang=en-us&client=chromium" | cut -d\" -f12 > stt.txt
echo "You Said:"
value=`cat stt.txt`
echo "$value"
#translate from English to Spanish and play over speakers
python PiTranslate.py -o en -d es -t "$value"
Now, run the Speech To Text script again, and it will translate it from English to Spanish by default.
./stt.sh
Both the origin and destination languages have to be supported by Microsoft Translate and Google Translate in order for this
script to work.
Language Codes:
Microsoft
Google
Mounting a USB the Easy Way!
Install a little app called USBMount,
sudo apt-get install usbmount
The USB HDD or Pendrive should then appear as /media/usb[num] starting from zero.
73
Type ‘df’ to find the exact path.
...Or the hard way
http://elinux.org/RPi_Adding_USB_Drives
Printing on a Pi.
Guide
First install CUPS - Linux Print Drivers
sudo apt-get install cups
Add the Pi user to the lpadmin group (for administrating printers!)
sudo usermod -a -G lpadmin pi
Use an internet browser to browse to
http://127.0.0.1:631
You will be prompted for a username and password - enter your normal pi username and password
Setting up an AirServer (for Printing) - See Here
N.B. When I did this the print margins were all to cock, might be worth checking this.
74
Video on the Pi
Youtube-dl
I’d strongly recoomend using OMXPlayer for all your command line needs. Othersiwe try using xbmc
(gull distro!)
sudo apt-get-install omxplayer
sudo apt-get install youtube-dl
youtube-dl can update itself to the newest version (you should do this regularly):
sudo youtube-dl -U
sudo youtube-dl -U
That's not a mistake: if installed for the first time, it needs two updates.
Then run
sudo youtube-dl -g url
where "url" is the url of the website that contains the video. youtube-dl will output the video url then. Play it with
omxplayer "vurl"
where vurl is the video url you got from youtube-dl. You must use single or double quotes
Minimal Kiosk Browser (installed but untested!)
A browser for the Pi with YouTube Support???
http://steinerdatenbank.de/software/kweb_manual.pdf
“Minimal Kiosk Browser is a small and fast web browser based on the webkit engine (same as Midori or
Chromium) with support for playing audio and video files (including m3u paylists) and web video (youtube
and other websites supported by youtube-dl and HTML5 video) with omxplayer. It also supports opening
PDF files directly from the browser (using either mupdf or xpdf) and downloading files of any kind (using
wget).”
Installation:
Open a terminal (or from the command line):
First you need to install some support programs (or make sure, that they are installed).
75
sudo apt-get install xterm xpdf youtube-dl
sudo youtube-dl -U
sudo youtube-dl -U
(yes, twice!)
To install Minimal Kiosk Browser:
wget http://steinerdatenbank.de/software/kweb_1.2.tar.gz
tar -xzf kweb_1.2.tar.gz
cd kweb-1.2
sudo ./install.sh
To provide a default homepage:
CODE: SELECT ALL
cp Examples/homepage.html ~/
76
Presenting on the Pi - Screenly. - (TESTED)
http://www.screenlyapp.com/ose.html
I came across this little gem while browsing. Basically it is possible to install this little bit of software on
a Pi,m you just hook it up to a screen and it will auto-load the interface and content (you have previously
set via web GUI on another PC!), it is capable of playing MP4 videos, displaying webpages and images
(both web based and locally!) Imagine a rolling presentation, ace for walls, displays etc.
Install Screenly OSE yourself
Configure the Raspberry Pi
First, flash the SD card and install Raspbian Wheezy. Instructions are available here.
During the first boot, you should be presented with a configuration screen (raspi-config). In raspi-config, make sure
you make the following changes:
●
●
●
●
●
●
●
●
●
Expand the root file system (required)
Disable overscan (depends on your display)
Change keyboard mapping (optional)
Change time zone (optional, but Screenly's scheduling uses this)
Enable SSH (optional)
Configure boot behavior to boot into X (required)
Change password for 'pi' user (recommended)
Change memory split to 50%/50% (ie. 128/128 or 256/256 depending on your Raspberry Pi version
(recommended)
Once you've made all these changes, you must restart your Raspberry Pi
Install Screenly OSE
After you've performed all of the above changes and rebooted, open a terminal (ctrl+alt+F1) or SSH session and as
the user 'pi' run:
$ curl -sL https://raw.github.com/wireload/screenly-ose/master/misc/install.sh | bash
(If you're running the installation over SSH, running the installation through a 'screen' session is highly
recommended.)
Assuming everything went well, reboot your system. Screenly should now load.
Upon boot, Screenly's management URL should show up on the screen (e.g.http://aaa.bbb.ccc.ddd:8080). To
manage the content, open up this URL on a different computer. Don't try to manage the content directly on the
Raspberry Pi using a keyboard and mouse. That won't work.
Adding YouTube Video links! :)
http://nerdlogger.com/2013/11/21/notes-on-getting-the-most-out-of-screenly-ose-for-raspberry-pi/
77
http://youtube.com/djsalkjfklds change it by adding ss in front so the URL reads http://ssyoutube.com/
djsalkjfklds) and load that page. Don’t worry about the “Get me out of here page that sometimes comes up” it’s
just that if you’re logged into youtube is will use https instead of http. You can take the ‘s’ out if you like.
Problems with Screenly.
I tried linking screenly to flickr accoutn, of course it doews not handle flash, which many of the flickr
players / displayers do. I tried installing GNASH, but not still dabbling with this. I think that this would be
ideal for displaying kids work, or displaying a or a selectyion of photos about a topic.
I also found no EASY way to quit the presentation., also no quick way to add a WHOLE host of photos
etc, without editing config fitles! - Worked beautifully with BBC site!
To do this, simply press ctrl + alt + F1.
To return to X, press ctrl + alt + F7.
Disabling Screenly
cd /home/pi/.config/lxsession/LXDE
sudo nano autostart
(remove the screenly entry!)
edit
cd /etc/xdg/lxsession/LXDE
sudo mv autostart.bak autostart
edit
sudo nano /etc/lightdm/lightdm.conf
and remove the ‘-nocursor’ from
xserver-command=X -nocursor
Making a Program LOOP FOREVER
On the Raspberry Pi master just create a simple bash script (you could save it as "forever") ...
while true
do
#Put anything you like in here!!!!
#avconv -re -i movie.avi -vcodec copy -an -f avi udp://239.0.1.23:1234
done
Don't forget to either make the script executable or run it by prepending the name of the bash script with sh, eg "sh
forever".
78
Making a program repeat every so often (CRON Jobs!)
CRON is a very cool way of making a process, program, or script run at set times. The Pi comes setup
with no CRON task running, however you can edit what you want it to do on a regular basis using
sudo crontab -e
It is very important to ensure the sudo command is used!
Once you are in the file you can then add the following line, just change the directory to point to where
your file is saved. (this example is set to repeat every 60 minutes, it then runs the command ‘python
<path of script>)
*/60 * * * * python /home/pi/twitter/TweetTemp.py
The Cron job takes the form of.
1 2 3 4 5 /root/backup.sh
Where,
●
●
●
●
●
●
1: Minute (0-59)
2: Hours (0-23)
3: Day (0-31)
4: Month (0-12 [12 == December])
5: Day of the week(0-7 [7 or 0 == sunday])
/path/to/command - Script or command name to schedule
79
HARDWARE
45
Cases
Sometimes you’ll want to put your Pi in a case.
For schools try something like the
http://www.skpang.co.uk/catalog/cover-withbreadboard-area-for-raspberry-pi-large-p1101.html which is clear and has space / included
breadboard if you’re going to do some electronics.
or the Pi Bow is very popular and makes it easy to
get to your Pi!
http://shop.pimoroni.com/ (they now do a couple
of addons if you have the camera module!) I
prefer TOXIC to rainbow!
or if you have plenty of lego then build your
own, full PDF instructions here! - https://
sites.google.com/a/mandell.org/raspberrypi/pimac
You don’t have to be too careful, use what you’ve
got, it just gives you a rough idea!
80
For media centres I like just plain black!
81
Raspberry-Pi-GPIO-Layout-Revision-2
By Matt | Published March 10, 2013 | Full size is 1000 × 471 pixels
Ultimate Pin-Out Diagram
http://www.pighixxx.com/wp-content/uploads/edd/2013/11/rasp_v3.png
82
http://www.raspberrypi.org/archives/1417
http://log.liminastudio.com/writing/tutorials/tutorial-how-to-use-your-raspberry-pi-like-an-arduino
http://www.youtube.com/watch?feature=player_embedded&v=q_NvDTZIaS4#!
http://jeremyblythe.blogspot.co.uk/2012/07/raspberry-pi-gpio-and-motion.html
http://flask.pocoo.org/docs/quickstart/
83
Connecting a Pi to the outside world
For this I recommend using a Pi Cobbler Kit and a breadboard, bell (single strand) wire. Some gummie
sweet! (tested with JellyBabies!)
PIN Basics
First thing is first, there are ton of ways to connect up a Pi to breadboards etc. I would recommend using
a Cobbler Kit or similar. When addressing GPIOs in the later scripts you are not addressing the PIN
number, but you’re using these pinouts. (GPIO.BOARD) the first diagram or GPIO.
More here - http://elinux.org/RPi_Low-level_peripherals
84
Making an LED Flash
To make a single simple LED Flash, you wire a resistor to +3.3v (pin 1), then connect the resistor to the
LED (curved side), then connect the flat side to whichever pin you want to use GPIO7 is an easy one.
This is the 7th Pin as they go 1,2 along the top, 3,4 then 5,6 then 7. The only WEIRD bit is that you’re
turning the LED ON when you set this pin to FALSE (0)
This python script should do it.
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
#Set your pins as either inputs or outputs!
(IN or OUT)
GPIO.setup(11, GPIO.OUT)
while 1:
#Turn the LED ON!
GPIO.output(11, False)
sleep(1)
#Turn the LED OFF!
GPIO.output(11, True)
sleep(1)
Now try creating a three coloured LED setup.
85
ScratchGPIO – Introduction for Beginners (untested)
by cymplecy -
Scratch Controlling the GPIO Pins on a Raspberry Pi Part 1 of 4 (Version 4)
This post is intended to make it as Simple as Pi to get up and running and make your Raspberry Pi
control some lights and small motors and to respond to switches and sensors. Minimum Requirements
– a Raspberry Pi with Raspbian installed (a working internet connection is very handy but not required)
a breadboard, some Light Emitting Diodes (LEDs), some resistors and some wire connectors. Total
cost £5-£10. Blue italics are extra information for those who like to understand things a bit more - Pink
italics are for the more advanced users and can be completely ignored by normal users. How to get a
Raspberry Pi to control the GPIO Pins using Scratch —————————————————————
Your Raspberry Pi needs to be connected to the internet to install the software but not needed to run
ScratchGPIO. Copy the text below ( left click just before the s of sudo and drag right until all the text in
the line as been selected) then right-click and select copy. Open up an LX Terminal window and select
Edit and the Paste that into an LX Terminal window and run it to download the installer.
sudo wget http://goo.gl/dANpKr -O isgh.sh
Once the installer has been downloaded then just type (or copy and paste the text below as before)
sudo bash isgh.sh
(If logged in as a different user to standard pi, then type sudo bash install_scratchgpio3.sh
yourusername) This will install all the necessary extra software and some simple examples. (If you do
not have internet on your Pi then, put your SD card into a card reader and try using your browser to
right-click and save the script direct to your SD card and then put it back into you Pi and run the second
instruction) Connecting Components Up ———————————————————————
EXTREME care should be taken when connecting hardware to the GPIO pins.You can cause your Pi to
die by connecting the wrong things together – only do this if your confident of your ability to follow
instructions correctly
AT A MINIMUM - get a breadboard and use some female-male 0.1 leads
(available from lots of on-line suppliers or your local Maplin shop) Check out GPIO pin guides to make
sure you know what pins are what. Wire up Pin 1 (3.3V) to (at least) a 330ohm resistor – connect that
resistor to the long lead of an LED and then connect other end of LED to Pin 6 (0V).
86
It should light up. If it doesn’t try reversing your LED. Now move the lead from Pin 1 to Pin 11.
Using ScratchGPIO Run the special Scratch icon (Scratch GPIO) on your desktop. (It is actually a
completely normal version of Scratch, it just runs a little Python background program as well that
handles communications between Scratch and the GPIO and automatically enables Scratch’s Remote
Sensor Connections(RSC)) To test out control from Scratch, click on File then Open and then click on
the My Projects button and select blink11 and click on OK. Once the project opens, just click on the OK
to enable Remote Sensor Connections. To run the script just click on the Green Flag.
Your LED should now blink on for 1 second and off for 2 seconds – see trouble
shooting if this doesn’t happen. What more can I do with Scratch and the GPIO As it comes, you can
control six pins as outputs (Pins 11,12,13,15,16 and 18) and treat all the rest as simple inputs
(22,7,3,5,24,26,19,21,23,8 and 10) (GPIO pin numbers/ordering do not follow anything that makes sense
to most people so you just have to go with the seemingly random numbering arrangement) As you can
see in the blink11 script , you can simply use a broadcast message telling Pins to go on or off (Up to
87
3.3V and down to 0V) The valid messages are
messages.
along with the corresponding pin off
You can also say
And you can replace the word
onwith high and replace off with low if you want to talk in pure logic levels. You can combine message
together to make a single broadcast so to turn Pin11 and Pin13 on and all others off you can say
or
Alternatively you can use the pinpattern broadcast to achieve the same result e.g:
This will also set just pins 11 and 13 on. Inputs To check an input, you
should go into the Sensing block and click on the word “slider” at the bottom and you’ll notice that you
have pins 22,7,3,5,24,26,19,21,23,8 and 10.
If you connect a switch to
one of these pins (through a resistor don’t forget) to OV, then you can detect when the switch is open or
closed. The inputs will normally read 1 and go to 0 when they are connected (through a resistor) to
ground. Click on the checkbox next to pin7 and try it out. Using variables instead of broadcasts For more
advanced Scratchers, you can use variables instead (or as well as broadcast messages) . For example:
88
create a global variable called pin11 To make pin11 go on or off use
On can be
replaced with high or 1 and off can be replaced with low or 0 so that you can use whatever logic scheme
you’d like. To set all outputs to on or off use
To use a “bit-pattern” to set/unset
multiple outputs simultaneously use
(this will set Pin 11 , Pin 13, Pin 16 and
Pin 18 on and Pins 12 and 15 off) Note – currently there is an unfortunate “bug” in Scratch in that it
remembers variable states and only sends changes out.
Even when you press the Green Flag, it will
not send the state of all the variables out, it will only send them when a variable changes. I recommend
(nay insist even!) setting any gpio variables to an invalid value – say a full-stop and then to their initial
state in a Green Flag start-up script.
Need more Pins as outputs? If you need more
than 6 pins to be outputs then, for example, you can use broadcast config22out to change pin22 from
being an input to being an output. All the pins can be re-configured this way. I for some reason, you
need more input pins you can use broadcast config11in to change pin 11 from an output to an input Part
2 – using Motors and varying brightness of LEDsTroubleshooting To test if the software necessary to
control the GPIO is correctly installed open a LXTerminal session and type
sudo python blink11.py
If this doesn’t give an error but doesn’t make a LED on Pin 11 blink then we have real problems Houston
Try connecting the lead going to Pin 11 back to Pin 1 to make sure the LED lights up then just in case
you have a loose connection.
89
Controlling GPIO remotely using Arduino Remote on iPhone / iPad
http://www.samratamin.com/blog/raspberry-pi-iphone-control-a-rpi-with-an-iphone-in-2-minutes/
Setup the your Hardware accordingly.
You will need to know the ip-address of your Pi to connect to it on port 7777. (I tried this on the school
network, via the GST wireless (it does not require you to log in, but it will allow you to connect to other
devies). This is what you will use to connect to it alter!
ifconfig will give you the ip address.
sudo apt-get install rpi.gpio
wget http://samratamin.com/RaspPi/Ardumote
(This did not work for me, I had to access the site and download the script manuallly!) Saved it
as a PY file (using SSH on the pi!)
You also need to install the app on the iphone
/ ipad (around £3 if memory serves!)
# Ardumote.py
#
# A quick python script to control a Raspberry Pi (running Debian Wheezy aka Raspbian) from iPhone using the Ardumote/
HD App.
# Download the App Here: (iPhone Version) http://bit.ly/PoChFK
#
(iPad Version) http://bit.ly/S8RUmv
#
# INSTRUCTIONS:
# This script requires you to first install the GPIO Library in Raspbian (Debian Wheezy):
#
1) SSH into your Raspberry Pi
#
2) Get and install the GPIO Library:
#
~$ sudo apt-get install rpi.gpio
#
3) Copy this script to your Pi or directly download it to the Pi:
#
~$ wget http://samratamin.com/RaspPi/Ardumote
#
3) after installing the library, run this python script:
#
~$ sudo nice -n 10 python Ardumote
#
* Note the "nice -n 10" sets process priority. If operations are very important,
use a lower number than 10)
#
4) Configure the messages on the Ardumote app and enjoy!
#
#
5) Modify/Handle Messages in this script and control anything else you want!
#
# Samrat Amin, 2012
#
import socket
import RPi.GPIO as GPIO
import os
GPIO.setmode(GPIO.BOARD) #Set Pin Mode according to Board Layout
#----------------------------------------------------------------------------# GPIO Pins SETUP
#Outputs in Pin Number for P1 Header. For example, GPIO.setup(7, GPIO.OUT) is for P1-07 (GPIO 4)
GPIO.setup(3, GPIO.OUT)
GPIO.setup(5, GPIO.OUT)
GPIO.setup(7, GPIO.OUT)
GPIO.setup(8, GPIO.OUT)
GPIO.setup(10, GPIO.OUT)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
90
#Inputs
#----------------------------------------------------------------------------RxSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
TxSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
IP = '0.0.0.0'
InPort = 7777
OutPort = 7777
RxSock.bind((IP,InPort))
while True:
#
#
data = RxSock.recvfrom(512)
message = data[0]
senderinfo = data[1]
senderIP = senderinfo[0]
print "message received: ", message
print "message length: ", len(message)
print "sender's IP: ", senderIP
#----------------------------------------------------------------------------# Handle Messages for Shutdown & Reboot
if (message == 'Reboot'):
print "Rebooting System"
TxSock.sendto('Rebooting System...',(senderIP,OutPort))
os.system('reboot')
if (message == 'Shutdown'):
print "Shutting System Down Now..."
TxSock.sendto('Shutting System Down...',(senderIP,OutPort))
os.system('sudo shutdown now -h')
#----------------------------------------------------------------------------#----------------------------------------------------------------------------# Handle Messages for GPIO Pins
#PIN 3
if (message == 'P3H'):
print "Pin 3 is now High"
GPIO.output(3, True)
TxSock.sendto('Pin 3 is now High',(senderIP,OutPort))
elif (message == 'P3L'):
print "Pin 3 is now Low"
GPIO.output(3, False)
TxSock.sendto('Pin 3 is now Low',(senderIP,OutPort))
#PIN 5
if (message == 'P5H'):
print "Pin 5 is now High"
GPIO.output(5, True)
TxSock.sendto('Pin 5 is now High',(senderIP,OutPort))
elif (message == 'P5L'):
print "Pin 5 is now Low"
GPIO.output(5, False)
TxSock.sendto('Pin 5 is now Low',(senderIP,OutPort))
#PIN 7
if (message == 'P7H'):
print "Pin 7 is now High"
GPIO.output(7, True)
TxSock.sendto('Pin 7 is now High',(senderIP,OutPort))
elif (message == 'P7L'):
print "Pin 7 is now Low"
GPIO.output(7, False)
TxSock.sendto('Pin 7 is now Low',(senderIP,OutPort))
#PIN 8
if (message == 'P8H'):
print "Pin 8 is now High"
GPIO.output(8, True)
TxSock.sendto('Pin 8 is now High',(senderIP,OutPort))
elif (message == 'P8L'):
print "Pin 8 is now Low"
GPIO.output(8, False)
TxSock.sendto('Pin 8 is now Low',(senderIP,OutPort))
#PIN 10
if (message == 'P10H'):
print "Pin 10 is now High"
GPIO.output(10, True)
TxSock.sendto('Pin 10 is now High',(senderIP,OutPort))
91
elif (message == 'P10L'):
print "Pin 10 is now Low"
GPIO.output(10, False)
TxSock.sendto('Pin 10 is now Low',(senderIP,OutPort))
#PIN 11
if (message == 'P11H'):
print "Pin 11 is now High"
GPIO.output(11, True)
TxSock.sendto('Pin 11 is now High',(senderIP,OutPort))
elif (message == 'P11L'):
print "Pin 11 is now Low"
GPIO.output(11, False)
TxSock.sendto('Pin 11 is now Low',(senderIP,OutPort))
#PIN 12
if (message == 'P12H'):
print "Pin 12 is now High"
GPIO.output(12, True)
TxSock.sendto('Pin 12 is now High',(senderIP,OutPort))
elif (message == 'P12L'):
print "Pin 12 is now Low"
GPIO.output(12, False)
TxSock.sendto('Pin 12 is now Low',(senderIP,OutPort))
#PIN 13
if (message == 'P13H'):
print "Pin 13 is now High"
GPIO.output(13, True)
TxSock.sendto('Pin 13 is now High',(senderIP,OutPort))
elif (message == 'P13L'):
print "Pin 13 is now Low"
GPIO.output(13, False)
TxSock.sendto('Pin 13 is now Low',(senderIP,OutPort))
#PIN 15
if (message == 'P15H'):
print "Pin 15 is now High"
GPIO.output(15, True)
TxSock.sendto('Pin 15 is now High',(senderIP,OutPort))
elif (message == 'P15L'):
print "Pin 15 is now Low"
GPIO.output(15, False)
TxSock.sendto('Pin 15 is now Low',(senderIP,OutPort))
#----------------------------------------------------------------------------#MRO ADDED CODE TO TIDY UP CONNECTIONS.
finally:
GPIO.cleanup() # this ensures a clean exit
Finaly set up the remote app to use Pin 7, add the code “P7” for Pin 7, this will toggle on / off on pin 7.
Pins 3,5,7,8,10,11,12,13,15 are enabled for I/O by default on the Ardumote python script, so you can use
messages “P3″, “P5″, etc on switches in the Ardumote App. You can always add more yourself!
92
Powering Mains
http://www.youtube.com/watch?v=3Pikhq99q5E
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=37&t=43625
Wiring up a lamp (brown wire to relay=?)
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
light_routledge = 7
GPIO.setwarnings(False)
GPIO.setup(light_routledge,GPIO.OUT)
GPIO.output(light_routledge,True)
while (True):
GPIO.output(light_routledge,False)
time.sleep(3)
GPIO.output(light_routledge,True)
time.sleep(3)
Singing / Screaming Jelly Baby (Probably works with Fruit Pastels too!)
http://www.ocr.org.uk/Images/125881-recipe-card-singing-jelly-baby.pdf
Once connected, strip a pair of decent length wires and connect to pins 3 and 25. Strip the other end
of the wires (about 2 cm) and stick into the Jelly Baby to make the switch. The guide suggests you
download mpg321 and an MP3, this was blocked at school, so I just got it to write whatever message
they liked on the end. I also found the 1 second time delay was FAR too long. Set to a tenth of the time
for more accuracy!
wget https://github.com/Rob-Bishop/RaspberryPiRecipes/raw/master/la.mp3
Original Script
Revised Script
# First we need to import the libraries that
# we need
# Import the time library so that we can make
# the program pause for a fixed amount of time
import time
import RPi.GPIO as GPIO
import os
GPIO.cleanup()
GPIO.setmode(GPIO.BOARD)
import time
# Import the Raspberry Pi GPIO libraries that
# allow us to connect the Raspberry Pi to
# other physical devices via the General
# Purpose Input-Output (GPIO) pins
# Set pin 3 on the GPIO header to be an input
GPIO.setup(3,GPIO.IN)
while True:
if GPIO.input(3) == False:
93
import RPi.GPIO as GPIO
# Import the os library so that we can make
# our program call other programs that run on
# the Raspberry Pi
#os.system(‘mpg321 la.mp3
&’)
print ‘Ouch! Stop it!’
time.sleep(0.1)
import os
# Now we need to set-up the General Purpose
# Input-Ouput (GPIO) pins
# Clear the current set-up so that we can
# start from scratch
GPIO.cleanup()
# Set up the GPIO library to
# use Raspberry Pi board pin
# numbers
GPIO.setmode(GPIO.BOARD)
# Set pin 3 on the GPIO header to be an input
GPIO.setup(3,GPIO.IN)
# This loop runs forever and plays the mp3
# file when the two wires are touching
while True:
# Check to see if pin 3 on the GPIO
# header is connected to the ground pin
if GPIO.input(3) == False:
# If it’s connected to ground
# then play the mp3 file
os.system(‘mpg321 la.mp3 &’)
# Wait for a second before repeating
# the loop
time.sleep(1)
It’s worth noting though that the command
os.system(‘<something>’)
Allows you to run any command or program you can from the terminal (we launched quake3)
os.system(‘./quake3/ioquake3.arm’)
If you do want to get the MP3 working, you might have to force the sound through the headphone
socket.
Also on one Pi I thought the GPIO Python libraries weren’t installed, however in hindsight I think this may
have been a typo that caused it, not as it was actually missing. However just in case you can always
use an
apt-cache search GPIO
I believe the python library is called Python-GPIO or similar (use the search!). Just do an
apt-get install
using the result you found!.
Make sound playback through the headphone socket
94
By default the output is set to automatically select the interface (HDMI if available otherwise analog). You can force
it to use a specific interface using :
sudo amixer cset numid=3 <n>
Where <n> is the required interface : 0=auto, 1=analog, 2=hdmi. To force the Raspberry Pi to use the analog
output :
sudo amixer cset numid=3 1
You will need to run the modprobe command again when your Pi is rebooted/restarted.
Playing A WAV File
In order to play a WAV file we need a file to play. Type the following command to download a test WAV file :
sudo wget http://www.freespecialeffects.co.uk/soundfx/sirens/police_s.wav
Now we can play it :
sudo aplay police_s.wav
sudo alsamixer
#Check Audio Volume.
95
Pi Camera Module
Initial installation and setup.
http://www.youtube.com/watch?
feature=player_embedded&v=GImeVqHQzsE
http://www.linuxuser.co.uk/tutorials/pi-cameraquick-installation-guide
How to use the Raspberry Pi camera software
raspivid is a command line application that allows you to capture video with the camera module, while the
application raspistill allows you to capture images.
-o or –output specifies the output filename and -t or –timeout specifies the amount of time that the preview will be
displayed in milliseconds. Note that this set to 5s by default and that raspistill will capture the final frame of the
preview period.
-d or –demo runs the demo mode that will cycle through the various image effects that are available.
Example commands
Capture an image in jpeg format:
raspistill -o image.jpg
To quickly view the image from the command prompt install fbi and use the simple command
sudo apt-get install fbi
fbi image.jpg
This will display the image on the screen and you will be able to use the + and - keys to zoom in and out.
Capture a 5s video in h264 format:
raspivid -o video.h264
Capture a 10s video:
raspivid -o video.h264 -t 10000
Capture a 10s video in demo mode:
raspivid -o video.h264 -t 10000 -d
To see a list of possible options for running raspivid or raspistill, you can run:
raspivid | less
raspistill | less
96
Use the arrow keys to scroll and type q to exit.
To shoot video with the Raspberry Pi Camera
From the command line, type…
raspivid -o filename.h264 -t 20000
…where filename is a file name of your choice.
This will store the output .h264 stream in a file called “filename.h264″ and will stop recording after 20000
milliseconds (20s). (It defaults to 1080p @ 30 frames per second).
There are a couple of other useful little options you might want to know about. By default, the image is
flipped vertically, meaning you see a mirror image of what you filmed.
Depending on which way round you hold the camera, you might want to flip it either horizontally,
vertically or both. You can do that by adding -vf and/or -hf to the command, like this…
raspivid -o filename.h264 -t 20000 -vf -hf or
raspivid -o filename.h264 -t 20000 -vf or
raspivid -o filename.h264 -t 20000 -hf
97
Using Raspicam in Python (untested)
apt-get install python-picamera
or
apt-get install python3-picamera
Example usage:
import picamera
from time import sleep
camera = picamera.PiCamera()
camera.capture('image.jpg')
camera.start_preview()
camera.vflip = True
camera.hflip = True
camera.brightness = 60
camera.start_recording('video.h264')
sleep(5)
camera.stop_recording()
Also you can do things like this:
for i in range(100):
camera.brightness = i
sleep(0.1)
and watch the preview flow through the brightness levels.
The library has many configurations – you can change the brightness, contrast, saturation, image effects, exposure
modes and such, as well as optionally show a live preview of the camera’s view. You can capture single images
and sequences of images as well as video streams
Berrycam Photos (Tested)
http://www.fotosyn.com/berrycam-support/?app
Save all
this as
Berrycam.py
#!/usr/bin/env python
#
# BerryCam.py
# BerryCam - Raspberry Pi Camera Controller for use with iOS devices
#
# Created by James Moore on 22/05/2013.
98
then run
using
sudo python
berrycam.py &
so it runs
in the
background.
# Copyright (c) 2013 Fotosyn. All rights reserved.
#
# Raspberry Pi is a trademark of the Raspberry Pi Foundation.
# IOS is a trademark or registered trademark of Cisco in the U.S. and other countries and is
used by Apple Inc. under license.
import SimpleHTTPServer, SocketServer
import urlparse
import os
PORT = 8000 # CHange this if you wish to listen on a different port
class BerryCamHandler (SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
# Parse query data
parsedParams = urlparse.urlparse(self.path)
queryParsed = urlparse.parse_qs(parsedParams.query)
# Add 'berrycam' prefix to URL to perform query
if parsedParams.path == "/berrycam":
awb = "'" + queryParsed['awb'][0] + "'" # Set AWB mode
mm = "'" + queryParsed['mm'][0] + "'" # Set metering mode
ev = queryParsed['ev'][0] # Set EV compensation
ex = "'" + queryParsed['ex'][0] + "'" # Set exposure mode
sh = queryParsed['sh'][0] # Set image sharpness
br = queryParsed['br'][0] # Set image brightness
co = queryParsed['co'][0] # Set image contrast
sa = queryParsed['sa'][0] # Set image saturation
#iso = queryParsed['iso'][0] # Set capture ISO - NOT YET IMPLEMENTED
ifx = "'" + queryParsed['ifx'][0] + "'" # Set image effect
#cfx = "'" + queryParsed['cfx'][0] + "'" # Set colour effect - NOT YET IMPLEMENTED IN
BERRYCAM
#rot = queryParsed['rot'][0] # Set image rotation - NOT YET IMPLEMENTED IN BERRYCAM
filequality = queryParsed['fquality'][0]
filewidth = queryParsed['fwidth'][0]
fileheight = queryParsed['fheight'][0]
filefolder = queryParsed['ffolder'][0]
fileseq = queryParsed['fseq'][0]
hflip = queryParsed['hf'][0]
#exifmake = queryParsed['exifmake'][0]
#filewidth = 2592 #- ((2592/4)*filesize) # Take the values passed, divide by 4 and
multiply to get new size
#fileheight = 1944 #- ((1944/4)*filesize) # Take the values passed, divide by 4 and
multiply to get new size
#Exposure mode options :
#off,auto,night,nightpreview,backlight,spotlight,sports,snow,beach,verylong,fixedfps,antishake,
fireworks
#AWB mode options :
#off,auto,sun,cloud,shade,tungsten,fluorescent,incandescent,flash,horizon
#Image Effect mode options :
#none,negative,solarise,sketch,denoise,emboss,oilpaint,hatch,gpen,pastel,watercolour,film,blur,
saturation,colourswap,washedout,posterise,colourpoint,colourbalance,cartoon
#Metering Mode options :
#average,spot,backlit,matrix
directory = 'berrycam/' + str(filefolder)
if not os.path.exists(directory):
os.makedirs(directory)
# Build
command
command
command
up a raspistill command line string
= "raspistill -v" # Initiate command for Raspicam
+= " -awb " +
str(awb) # Define WB
+= " -mm " +
str(mm) # Define Metering Mode
99
command += " -ev " + str(ev) # Define the Exposure Adjustment
command += " -ex " +
str(ex) # Define Exposure Mode
command += " -sh " + str(sh) # Define Image Sharpness
command += " -br " + str(br) # Define Image Brightness
command += " -co " + str(co) # Define Image Contrast
command += " -sa " + str(sa) # Define Image Saturation
#command += " -ISO " + str(iso) # Define Image ISO - NOT YET IMPLEMENTED
command += " -ifx " +
str(ifx) # Define Image Effect
#command += " -cfx " +
str(cfx) # Define Colour Effect - NOT YET IMPLEMENTED IN
BERRYCAM
#command += " -rot " +
str(rot) # Define Image Rotation - NOT YET IMPLEMENTED IN
BERRYCAM
command += " -q " + str(filequality) # Define Image Quality
command += " -w " + str(filewidth) # Define output image width
command += " -h " + str(fileheight) # Define output image height
#command += " -o /berrycam/" + str(filefolder) + "/IMG-" + str(fileseq) +".jpg"
command += " -o berrycam/" + str(filefolder) + "/IMG-" + str(fileseq) +".jpg"
#command += " -x IFD1.Make=" + str(exifmake) #Define Make for ESIF Data 'Raspberry
Pi'
if hflip == "1":
command += " -hf "
else:
command += ""
os.system(command)
self.processRequest(queryParsed)
else:
# Default to serve up a local file
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self);
def processRequest(self, query):
self.send_response(200)
httpd = SocketServer.TCPServer(("", PORT), BerryCamHandler)
print "B E R R Y C A M -- Listening on port", PORT
print "Please ensure your BerryCam App is installed and running on your iOS Device"
httpd.serve_forever()
100
Time Lapse Photos
Another great feature of the utility is the easy capture of a series of images over a specified
period of time. You could write your own software to do this but for speed you can’t beat the time
lapse options provided :
raspistill -o myimage_%d.jpg -tl 2000 -t 25000
The -tl option sets the time between photos (in milliseconds) and the -t option sets the total time
the sequence will last. So in this example a photo will be taken every two seconds (2000ms) for a
total time of twenty five seconds (25000ms).
In this example we take a photo every minute (60000 milliseconds) for a total time of 2 hours (2 x
60 x 60 x 1000 milliseconds) :
raspistill -o myimage_%d.jpg -tl 60000 -t 7200000
The “%d” results in a sequence of numbered images being produced. In this case you would get
images named :
myimage_1.jpg
myimage_2.jpg
myimage_3.jpg
myimage_4.jpg
...
If you change the “%d” to “%04d” you can pad the numbers with zeroes to always give four
digits. I much prefer this as it gives you a sequence that looks like :
myimage_0001.jpg
myimage_0002.jpg
myimage_0003.jpg
myimage_0004.jpg
...
Time Lapse Video from Stills.
http://www.raspberrypi-spy.co.uk/2013/05/creating-timelapse-videos-with-the-raspberry-pi-camera/
Step 1 – Taking the time-lapsed photos
This command will take a photo every 60 seconds (60000 milliseconds) for 2 hours (7200000 milliseconds)
resulting in a sequence of 120 images.
raspistill -o myimage_%04d.jpg -tl 60000 -t 7200000
The “%04d” will result in a four digit number appearing in each filename.
myimage_0001.jpg
myimage_0002.jpg
...
myimage_0119.jpg
myimage_0120.jpg
101
Step 2 – Combine images into MP4 video
Once you’ve got your image sequence you will need a method to stitch them together. I decided to use “avconv”.
You can install this useful library with the following command :
sudo apt-get -y install libav-tools
To construct the video file from your image sequence you use the command shown below. Although it appears on
multiple lines for readability it should be entered as a single line on the command line :
avconv -r 10 -i myimage_%04d.jpg -r 10 -vcodec libx264 -crf 20 -g 15 timelapse.mp4
The video will be the full resolution of the default image size (2592×1944).
To crop the images and create a more standard 1280×720 resolution video you can use the following command :
avconv -r 10 -i timelapse_%04d.jpg -r 10 -vcodec libx264 -crf 20 -g 15 -vf
crop=2592:1458,scale=1280:720 timelapse.mp4
The “vf” option defines a video filter. In this case two filters which crop the incoming image to 2592×1458 and then
scale them to 1280×720.
The “r” option tells avconv to create a video with a frames per second of 10. It appears twice to prevent avconv
dropping frames that it thinks are similar.
The “crf” option tells avconv to aim for a quality level of “20″ which is a good starting point. Lowers values are better
but will increase the file size.
The “-g” option sets the GOP value. The YouTube Advanced Encoding Settings page recommends that the GOP
should be set to half the frame rate so this is set to 15.
The conversion process is very slow on the Pi compared to doing the same thing on a desktop PC. For long
sequences with hundreds of frames I would recommend downloading an appropriate version of Libav on your
desktop or laptop and build your MP4 files much faster!
102
Converting the Video output
http://raspi.tv/2013/how-to-shoot-video-and-convert-it-to-something-you-can-edit-in-pinnacle-and-otherprograms
ffmpeg -r 30 -i video_in.h264 -vcodec copy video_out.mp4
Extra Tricks by Bill Tidey
Bill posted these tips in the Pi forums and they were too good not to share…
ffmpeg -f lavfi -i aevalsrc=0 -r 30 -i test.h264 -shortest -c:v copy -c:a aac -strict experimental testo.mp4
…adds a silent audio channel as some video editors don’t work without this.
ffmpeg -i test.mp3 -r 30 -i test.h264 -shortest -c:v copy -c:a aac -strict experimental testo.mp4
…adds a real audio track where the test.mp3 should normally be longer than the video as the output is
the shortest.
103
Watermarking with another Graphic!
Firstly install a wonderful gem piece of software called
imagemagick, if it works in the GIMP or Photoshop you
can probably do something similar with imagemagick
from the command line. This is a VERY complex
beasty! With more arugments than I’d care to guess.
But I thought hell, let’s dive in.
sudo apt-get install imagemagick
Full manual for ImageMagick here.
I created a nice little MRO Pi logo in cooltext (and saved it!), didn’t try this on the Pi, but used WinSCP to
get it on the Pi.
I already had some stock images on the Pi (in a folder!), I put the logo in there too!
First I found I had to resize the logo as the captured images from the Pi camera are 2592x1944 pixels
I used the command
convert CT_Pi_Logo.png 1000% CTI_Pi_Big.png
Which converted the image (I could go from JPG to PNG if I wanted!), but also increased the size tenfold
(1000%) I found this a bit massive and went for (500% in the end!) The -adaptive-resize gave me much
better quality!
convert CT_Pi_Logo.png -adaptive-resize 500% CTI_Pi_Big.png
I then tried various commands to move the logo round. (notice the logo is called first, to put on top of
the other image, if you do it the other way round it crops down the large image to small! I used the
composite command to put them together. I found you could use -gravity south to define how low on the
page (I assume North is at the top!)
composite CTI_Pi_Big.png myimage_11.jpg -gravity south test.png
A much better way of doing this was to use exact pixel co-ordinates (starting 0,0 in the top left!)
So finally I used
composite -geometry +100+1700 CTI_Pi_Big.png myimage_11.jpg
test.png
to put the image in the bottom left corner!
Using the Pi Camera module with Motion
104
See my guide for setting up motion for the PS3 camer for further details. However to use the raspberry
pi camera you need a modified version of Motion (motion-mmal) and a custom config file. I tried
compiling it from source but could not get it work (configure/make/make install). Not only would it not
work it refused to detect the special config file required. So I used
sudo apt-get purge motion
To clean it from the system, then used the binary available here (Dropbox blocked at school) but you can
download the tarball.
I copied the files to the Pi (in their own folder) and had some success using
sudo ./motion -n -c motion-mmal.conf
where the -n means you SHOULD be able to stop the camera from the command prompt rather than
running it as a service and -c lets you choose the custom config file. I had some success with this,
however it did seem to crash the Pi on several occasions (the keyboard stopped working!) Will do
further tests, it was also unresponsive across my local network (where I wish to view the camera results
via the browser!)
The key command in the .conf file to access the Pi camera is
mmalcam_name vc.ril.camera
.... not
/dev/video0
105
Creepy Face Tracking (Partly Tested)
http://learn.adafruit.com/downloads/pdf/creepy-face-tracking-portrait.pdf
http://learn.adafruit.com/creepy-face-tracking-portrait/software
https://www.youtube.com/watch?v=3rhnfBSjj6w
Binary Installation
Execute the following commands to get the
binaries:
mkdir ~/creepyportrait
cd ~/creepyportrait
wget https://github.com/tdicola/
creepyportrait/raw/master/
creepyportrait_1.0_raspberrypi.tar.gz
tar xvf
creepyportrait_1.0_raspberrypi.tar.gz
sudo ./install_dependencies.sh
Answer yes to the questions about updating and installing packages that come up when
theinstall_dependencies.sh script is run. This script is provided in openFrameworks and will install all the
necessary libraries for running openFrameworks applications like the creepy portrait.
Usage
To run the program first make sure either the Raspberry Pi camera or a webcam is attached to your
Raspberry Pi.
Note: If you're using the Raspberry Pi camera for the first time, make sure to follow these instructions to
enable it with the raspi-config command.
First run the program with no command line parameters by executing:
./creepyportrait
You should see the program usage and an error message about no video device being selected. If you're
using a webcam, note the device ID number of the webcam you want to use.
To run the program with the Raspberry Pi camera execute:
./creepyportrait pi
Or to run the program with a webcam execute:
./creepyportrait (video device ID)
Where (video device ID) is the ID of the webcam from above. For example if you're using device ID 0 you
would execute './creepyportrait 0' (without quotes).
It should take about 30-60 seconds for the program to start and display the skull. You should also see
video from your camera in the upper left corner, and every ~2 seconds a green box appear over the largest
detected face in the video. Make sure you have a decent amount of light on your face or else the detection
won't be very reliable.
106
You can press the following buttons on the Raspberry Pi's keyboard to control the application:
●
●
V - Hide or show the video in the upper left corner.
M - If you're running with more than one 3D model (see further below), change between
rendering different models. On the Raspberry Pi, for now only one model can be loaded in
memory at a time.
●
Escape or Ctrl-C - Close the application.
You can run the program with a different 3D model by specifying it in a second command line parameter.
The possible values are:
●
●
●
●
skull
jackevil
jackhappy
all
Skull is the default model. Unfortunately even on the Raspberry Pi model B there isn't enough memory to
load all models at once, so pick your favorite one and use it when you run on the Pi.
For example to run with the evil jack-o-lantern using the Raspberry Pi camera you would execute:
./creepyportrait pi jackevil
Continue on if you want to download and compile openFrameworks and the code for the creepy portrait. If
you just want to run the creepy portrait you can stop here, you're done!
Fixing RaspVid / RaspImage for Headless streaming
http://www.darkoperator.com/blog/2013/5/23/fixin-raspistill-and-raspivid-for-headless-streaming-onthe.html
QRCodes on the Pi.
http://www.linux-magazine.com/Online/Features/Generating-QR-Codes-in-Linux
http://linuxg.net/scan-qr-codes-in-ubuntu-with-libdecodeqr-simpletest/
http://linuxaria.com/pills/qr-code-in-linux?lang=en
Qreator???
http://ralgozino.wordpress.com/2011/06/13/how-to-create-and-decode-a-qr-code-in-python-using-qrtools/
- ZBar https://github.com/herbyme/zbar QR Code Checker.
http://zleap.net/python-qr-code-reader/ - Full working Pi Setup.
First install the Python QR Tools.
sudo apt-get install python-qrtools zbar-tools qtqr
107
Then run
sudo nano webcamreader.py
and add
qrtools
qrtools import QR
myCode = QR()
print myCode.decode_webcam()
print myCode.data
print myCode.data_type
print myCode.data_to_string()
import
from
Save it and and in X run
sudo python webcamreader.py
This will make a basic script (must be run in X) which will allow you to read a
QRCode, it uses ZBar as a basis. However you have to click once it has recognised
the QRCode. It will then output the info to the screen.
Generating QR Codes on the Pi.
To Generate QR Codes you can use QtQr
https://code.google.com/p/qtqr/
(will also read codes too!)
Generating QR Codes online
http://qrcode.kaywa.com/ - Basic B&W
http://www.qrstuff.com/ - More Colourful.
http://www.visualead.com/qr-code-generator/ - More advanced more / colourful / logo
http://www.qrcode-monkey.com/ - Advanced with logo
Using ZBar from the Shell
you can then run zbarcam from the prompt.
or
zbarcam --nodisplay
(you can run from the terminal)
Python Quick Example (calling ZBarCam)
based on - http://ralsina.me/weblog/posts/BB913.html
import os
p=os.popen('zbarcam --nodisplay','r')
print 'scanning'
while True:
barcode = p.readline()
print 'Got barcode:', barcode
108
#The returned code is made up of 2 parts, the type : data
type = barcode.split(':')[0]
print type +' '
code = barcode.split(':')[1]
print code +' '+str(len(code))
#You need to remove the return extra character from the string!
code =code [0:-1]
#os.system('chromium http://www.goodreads.com/search/search?q=%s'%isbn)
#This might launch Quake3.
if (code=='quake3'):
os.system('/home/pi/quake3/./ioquake3.arm')
elif (code=='minecraft'):
os.system('espeak "This will launch MINEcraft!"')
else:
print 'Everything Else'
os.system('espeak "Yipee Kye Aye Mother!"')
Careful when you copy and past that it taskes across the single quotes ‘
Video for Linux Driver for Raspberry Pi Camera (so camera shows as /dev/video0!)
http://www.linux-projects.org/modules/sections/index.php?op=viewarticle&artid=14
How to install or upgrade UV4L on Raspbian (for the Raspberry Pi)
To install UV4L open a terminal and type the following commands:
wget http://www.linux-projects.org/listing/uv4l_repo/lrkey.asc && sudo apt-key add ./lrkey.asc
Add the following line to the file /etc/apt/sources.list :
deb http://www.linux-projects.org/listing/uv4l_repo/raspbian/ wheezy main
sudo apt-get update
sudo apt-get install uv4l uv4l-raspicam
The last two commands will upgrade UV4L to the most recent version, if it's already installed.
If you want the driver to be loaded at boot, also install this optional package:
sudo apt-get install uv4l-raspicam-extras
Now the UV4L core component and the Video4Linux2 driver for the CSI Camera Board are installed. If you occasionally get unexpected errors
from the driver, consider updating the firmware with the following command:
sudo rpi-update
For detailed informations, options, etc... about the modules installed type accordingly:
man uv4l
man uv4l-raspicam (the manpage is work in progress)
To get a list of available options:
uv4l --help --driver raspicam --driver-help
To quicly test uv4l, if you did not install the optional uv4l-raspicam-extras package, load it first:
uv4l --driver raspicam --auto-video_nr --width 640 --height 480 --encoding jpeg
To take a JPEG snapshot from the Camera:
dd if=/dev/video0 of=snapshot.jpeg bs=11M count=1
For a list of other use cases click here.
To terminate a running driver, close the applications and kill the corresponding uv4l process:
pkill uv4l
Apart from the driver for the Raspberry Pi Camera Board, the following drivers can be installed:
$ sudo apt-get install uv4l-uvc
$ sudo apt-get install uv4l-xscreen
$ sudo apt-get install uv4l-mjpegstream
To get help:
109
$ man uv4l-uvc
$ man uv4l-xscreen
$ man uv4l-mjpegstream
---
110
Cheap PIR Sensors and the Raspberry Pi – Part 1 (untested)
http://www.raspberrypi-spy.co.uk/2013/01/cheap-pir-sensors-and-the-raspberry-pi-part-1/
A great little sensor you can add to your Raspberry Pi projects is a PIR module. These 5V “Passive Infra
Red” sensors are available for a few pounds from eBay. They can be powered from 5V and output 3V so
can be connected directly to pins on the Pi’s GPIO header without any other components.
The module sets a single output pin high whenever it detects movement within its field of view. It holds
this pin High (3.3V) for a minimum period of time. If continuous movement is detected the output pin will
stay High. When the time has elapsed and no more movement is detected the output pin returns Low
(0V).
I am currently using one in an alarm system and it works great for such a small and cheap device.
PIR Connections
Here is a diagram showing the pin-out on the PIR module and how I connected it to my Raspberry Pi :
PIR Module
The device has two variable resistors that you can adjust to tweak the performance of the module.
Trimming Controls
111
The first one (left-hand side on the photo)
determines the sensitivity of the device. The
default setting is usually 50%.
The second control (right-hand side on the photo
and usually marked “time” on the PCB) allows
you to adjust the amount of time the output
pin stays at 3V (high) when it is triggered by
movement. This can be set from a few seconds to
200 seconds. The default setting is usually a few
seconds.
The units available on eBay vary in specification
but they are all very similar.
Python Example Script
If you connect your module as shown in the
diagram above the following Python script will
allow you to get started. Cut and paste the script
below into a text file and transfer to the Pi or
download the script directly using this link.
#!/usr/bin/python
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#|R|a|s|p|b|e|r|r|y|P|i|-|S|p|y|.|c|o|.|u|k|
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# pir_1.py
# Detect movement using a PIR module
#
# Author : Matt Hawkins
# Date
: 21/01/2013
# Import required Python libraries
import RPi.GPIO as GPIO
import time
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
# Define GPIO to use on Pi
GPIO_PIR = 7
print "PIR Module Test (CTRL-C to exit)"
# Set pin as input
GPIO.setup(GPIO_PIR,GPIO.IN)
# Echo
Current_State = 0
Previous_State = 0
try:
print "Waiting for PIR to settle ..."
# Loop until PIR output is 0
while GPIO.input(GPIO_PIR)==1:
Current_State = 0
print "
Ready"
# Loop until users quits with CTRL-C
while True :
# Read PIR state
Current_State = GPIO.input(GPIO_PIR)
if Current_State==1 and Previous_State==0:
# PIR is triggered
print " Motion detected!"
# Record previous state
Previous_State=1
elif Current_State==0 and Previous_State==1:
# PIR has returned to ready state
print " Ready"
Previous_State=0
# Wait for 10 milliseconds
time.sleep(0.01)
except KeyboardInterrupt:
print " Quit"
112
# Reset GPIO settings
GPIO.cleanup()
This script can also be downloaded onto your Pi directly using this command line :
1
wget http://www.raspberrypi-spy.co.uk/archive/python/pir_1.py
This can then be run using :
1
sudo python pir_1.py
When run the script waits for the output pin to go Low. It then prints a message to the screen every time
the output state changes. This is either when movement is detected (output changes to High) or the
device sees no movement (outout changes to Low).
Try changing the reset time by turning the “time” resistor clockwise by a few degrees. Run the script
again, trigger the device and then wait to see how long it takes to go back to the ready state.
Photos
Here some more detailed photos of the PIR pins and two trimming controls :
113
Robot Arm Stuff.
(see) MagPi Editon 3 - Page 14
http://cymplecy.wordpress.com/2012/08/26/scratch-controlling-the-gpio-on-a-raspberrypi/
https://github.com/peterlavelle/maplinarm
http://notbrainsurgery.livejournal.com/38622.html - Alternative approach by sending bits of data.
http://www.mybigideas.co.uk/RPi/RobotArm/- Robot Arm with PS3 Pad.
http://www.instructables.com/id/Raspberry-Pi-and-Wiimote-controlled-Robot-Arm/#step1 - Robot arm
with Wii-Mote
To use the arm you must install the pyUSB drivers.
sudo apt-get install python libusb-0.1-4
git clone https://github.com/walac/pyusb.git
cd pyusb
sudo
sudo
sudo
sudo
apt-get install libusb-dev
apt-get install python-pip
apt-get install python3-pip #You need this if using Python 3.3
pip install pyusb
sudo python setup.py install
sudo pyton3 setup.py install #Install for python 3 aswell as 2.7.
sudo apt-get install bluez python-cwii
114
Robot Arm Basics
http://www.wikihow.com/Use-a-USB-Robotic-Arm-with-a-Raspberry-Pi-(Maplin)
Save the following
code in arm.py then
run using sudo python
arm.py
#ROBOT ARM CONTROL PROGRAM
#import the USB and Time librarys into Python
import usb.core, usb.util, time
#Allocate the name 'RoboArm' to the USB device
RoboArm = usb.core.find(idVendor=0x1267, idProduct=0x000)
#Check if the arm is detected and warn if not
if RoboArm is None:
raise ValueError("Arm not found")
#Create a variable for duration
Duration=1
#Define a procedure to execute each movement
def MoveArm(Duration, ArmCmd):
#Start the movement
RoboArm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,3)
#Stop the movement after waiting a specified duration
time.sleep(Duration)
ArmCmd=[0,0,0]
RoboArm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,3)
#Do a quick test of all the joints.
MoveArm(1,[0,2,0]) #Rotate base clockwise
MoveArm(1,[64,0,0]) #Shoulder up
MoveArm(1,[128,0,0]) #Shoulder down
MoveArm(1,[16,0,0]) #Elbow up
MoveArm(1,[32,0,0]) #Elbow down
MoveArm(1,[4,0,0]) #Wrist up
MoveArm(1,[8,0,0]) # Wrist down
MoveArm(1,[2,0,0]) #Grip open
MoveArm(1,[1,0,0]) #Grip close
MoveArm(1,[0,0,1]) #Light on
MoveArm(1,[0,0,0]) #Light off
115
Robot Arm with PS3 Pad
#!/usr/bin/env python
import pygame
import usb.core
import time
pygame.init()
# Wait for a joystick
while pygame.joystick.get_count() == 0:
print 'waiting for joystick count = %i' % pygame.joystick.get_count()
time.sleep(10)
pygame.joystick.quit()
pygame.joystick.init()
j = pygame.joystick.Joystick(0)
j.init()
print 'Initialized Joystick : %s' % j.get_name()
armFound = False
while not armFound:
dev = usb.core.find(idVendor=0x1267, idProduct=0x0000)
if dev is None:
print 'Arm not found. Waiting'
time.sleep(10)
else:
armFound = True
#this arm should just have one configuration...
dev.set_configuration()
# How far to move the JoyStick before it has an effect (0.60 = 60%)
threshold = 0.60
# Key mappings
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
# Robot Arm defaults
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
I use to drive a USB
Robot ARM from my
Raspberry Pi using a
PlayStation 3 controller. I
got the ARM from Maplins
in the UK (Code:A37JN)
and its a OWI EDGE 535
Robotic kit.
Most of the tools required
to control the Robot ARM
from a Raspberry Pi come
pre-installed on the latest
images, however you will
need to install PyUSB to
send commands to the
ARM.
sudo apt-get
install python libusb0.1-4
git clone https:/
/github.com/walac/
pyusb.git
cd pyusb
sudo python
setup.py install
With the PyUSB module
installed and a PS3
controller attached its just
a simple case of running
the following script to
control its movements.
The analogue sticks
control the ARM
movement, with the
R1/R2 buttons moving
the wrist and the X and
Circle keys operating the
gripper.
This assumes the PS3
Pad is wired.
# ARM control related stuff
def setcommand(axis_val):
if axis_val > threshold:
return 1
elif axis_val < -threshold:
116
return 2
elif abs(axis_val) < threshold:
return 0
def buildcommand(shoulc,basec,elbowc,wristc,gripc,lightc):
byte1 = shoulc + elbowc + wristc + gripc
comm_bytes = (byte1, basec, lightc)
return comm_bytes
def processArm(event):
global command, lc, shoulder, base, elbow, wristup, wristdown, grip_open,
grip_close, grip_command, wrist_command, shoulder_command, base_command,
elbow_command
if event.type == pygame.JOYBUTTONDOWN:
if event.button == PS3_BUTTON_SELECT:
if lc == 0:
lc = 1
else:
lc = 0
elif event.type == pygame.JOYAXISMOTION:
if event.axis == PS3_AXIS_LEFT_VERTICAL:
shoulder = event.value
elif event.axis == PS3_AXIS_LEFT_HORIZONTAL:
base = event.value
elif event.axis == PS3_AXIS_RIGHT_VERTICAL:
elbow = event.value
elif event.axis == PS3_AXIS_R1:
wristup = event.value
elif event.axis == PS3_AXIS_R2:
wristdown = event.value
elif event.axis == PS3_AXIS_X:
grip_open = event.value
elif event.axis == PS3_AXIS_CIRCLE:
grip_close = event.value
# Are we opening or closing the gripper?
if grip_open> threshold:
grip_command = 1
elif grip_close> threshold:
grip_command = 2
else:
grip_command = 0
# And the same for the wrist, are we moving up or down?
if wristup > threshold:
wrist_command = 1*4
elif wristdown > threshold:
wrist_command = 2*4
else:
wrist_command = 0
shoulder_command = setcommand(shoulder)*64
base_command = setcommand(base)
elbow_command = setcommand(elbow)*16
# Work out what to send out to the robot
newcommand = buildcommand(shoulder_command,base_command,
elbow_command, wrist_command, grip_command,lc)
# If the command has changed, send out the new one
if newcommand != command:
dev.ctrl_transfer(0x40, 6, 0x100, 0, newcommand, 1000)
command = newcommand
try:
# Loop forwever
while True:
# Sleep so we don't eat up all the CPU time
time.sleep(0.1)
# read in events
events = pygame.event.get()
# and process them
for event in events:
117
processArm(event)
except KeyboardInterrupt:
j.quit()
118
Robot Arm With Wii-Mote
sudo
sudo
sudo
sudo
#
#
#
apt-get install libusb-dev
apt-get install python-pip
pip install pyusb
apt-get install bluez python-cwii
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|A|Y|L|O|R| |B|O|A|R|D|M|A|N| | | |R|P|I| |A|R|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
'''First we need to import some files (These files contain all the commands needed for our program)
We have usb.core and usb.util - these are used to control the usb port for our arm
Next we have cwiid which communicates with the wiimote
And we have the time libary which allows us to slow or pause things'''
import usb.core, usb.util, cwiid, time
#Give our robot arm an easy name so that we only need to specify all the junk required for the usb connection
once
print 'Make sure the arm is ready to go.'
print ''
Armc = 1750
Arm = None
while (Arm == None):
#This connects to the usb
Arm = usb.core.find(idVendor=0x1267, idProduct=0x0000)
#This will wait for a second, and then if the program could not connect, it tells us and tries again
Armc = Armc + 1
if (Armc == 2000):
print 'Could not connect to Arm, double check its connections.'
print 'Program will continue when connection is established...'
print ' '
Armc = Armc/2000
continue
#Set up our arm transfer protocol through the usb and define a Value we can change to control the arm
Duration = 1
ArmLight = 0
#Create delay variable that we can use (Seconds)
Delay = .1
Counter = 9999
def ArmMove(Duration, ArmCmd):
#Start Movement
Arm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,1000)
time.sleep(Duration)
#Stop Movement
ArmCmd=[0,0,ArmLight]
Arm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,1000)
#Establish a connection
print 'Connected to arm
print ' '
print 'Press 1 and 2 on
#Connect to mote and if
with the wiimote
successfully.'
the wiimote at the same time.'
it doesn't connect then it tells us and tries again
119
time.sleep(3)
print ''
print 'Establishing Connection... 5'
time.sleep(1)
print 'Establishing Connection... 4'
time.sleep(1)
print 'Establishing Connection... 3'
Wii = None
while (Wii==None):
try:
Wii = cwiid.Wiimote()
except RuntimeError:
print 'Error connecting to the wiimote, press 1 and 2.'
print 'Establishing Connection... 2'
time.sleep(1)
print 'Establishing Connection... 1'
time.sleep(1)
print ''
#Once a connection has been established with the two devices the rest of the program will continue; otherwise, it
will keep on trying to connect to the two devices
#Rumble to indicate connection and turn on the LED
Wii.rumble = 1 #1 = on, 0 = off
print 'Connection Established.'
print 'Press any button to continue...'
print ''
''' Each number turns on different leds on the wiimote
ex) if Wii.led = 1, then LED 1 is on
2 = LED 2
3 = LED 3
4 = LED 4
5 = LED 1, 3
6 = LED 2, 3
7 = LED 1,2,3
8 = LED 4
9 = LED 1, 4
10 = LED 2,4
11 = LED 1,2,4 12 = LED 3,4
13 = LED 1,3,4
14 = LED 2,3,4 15 = LED 1,2,3,4
It counts up in binary to 15'''
time.sleep(1)
Wii.rumble = 0
Wii.led = 15
# Set it so that we can tell when and what buttons are pushed, and make it so that the accelerometer input can be
read
Wii.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC | cwiid.RPT_EXT
Wii.state
while True:
#This deals with the accelerometer
'''create a variable containing the x accelerometer value
(changes if mote is turned or flicked left or right)
flat or upside down = 120, if turned: 90 degrees cc = 95, 90 degrees c = 145'''
Accx = (Wii.state['acc'][cwiid.X])
'''create a variable containing the y accelerometer value
(changes when mote is pointed or flicked up or down)
flat = 120, IR pointing up = 95, IR pointing down = 145'''
Accy = (Wii.state['acc'][cwiid.Y])
'''create a variable containing the z accelerometer value
(Changes with the motes rotation, or when pulled back or flicked up/down)
120
flat = 145, 90 degrees cc or c, or 90 degrees up and down = 120, upside down = 95'''
Accz = (Wii.state['acc'][cwiid.Z])
#This deals with the buttons, we tell every button what we want it to do
buttons = Wii.state['buttons']
#Get battery life (as a percent of 100):
#Just delete the nunber sign inn front
#print Wii.state['battery']*100/cwiid.BATTERY_MAX
# If the home button is pressed then rumble and quit, plus close program
if (buttons & cwiid.BTN_HOME):
print ''
print 'Closing Connection...'
ArmLight = 0
ArmMove(.1,[0,0,0])
Wii.rumble = 1
time.sleep(.5)
Wii.rumble = 0
Wii.led = 0
exit(Wii)
''' Arm Commands Defined by ArmMove are
[0,1,0]
Rotate Base Clockwise
[0,2,0]
Rotate Base C-Clockwise
[64,0,0] Shoulder Up
[128,0,0] Shoulder Down
[16,0,0] Elbow Up
[32,0,0] Elbow Down
[4,0,0]
Wrist Up
[8,0,0]
Wrist Down
[2,0,0]
Grip Open
[1,0,0]
Grip Close
[0,0,1]
Light On
[0,0,0]
Light Off
ex) ArmMove(Duration in seconds,[0,0,0])
This example would stop all movement and turn off the LED'''
#Check to see if other buttons are pressed
if (buttons & cwiid.BTN_A):
print 'A pressed'
time.sleep(Delay)
ArmMove(.1,[1,0,ArmLight])
if (buttons & cwiid.BTN_B):
print 'B pressed'
time.sleep(Delay)
ArmMove(.1,[2,0,ArmLight])
if (buttons & cwiid.BTN_1):
print '1 pressed'
ArmMove(.1,[16,0,ArmLight])
if (buttons & cwiid.BTN_2):
print '2 pressed'
ArmMove(.1,[32,0,ArmLight])
if (buttons & cwiid.BTN_MINUS):
print 'Minus pressed'
ArmMove(.1,[8,0,ArmLight])
if (buttons & cwiid.BTN_PLUS):
print 'Plus pressed'
ArmMove(.1,[4,0,ArmLight])
if (buttons & cwiid.BTN_UP):
121
print 'Up pressed'
ArmMove(.1,[64,0,ArmLight])
if (buttons & cwiid.BTN_DOWN):
print 'Down pressed'
ArmMove(.1,[128,0,ArmLight])
if (buttons & cwiid.BTN_LEFT):
print 'Left pressed'
ArmMove(.1,[0,2,ArmLight])
if (buttons & cwiid.BTN_RIGHT):
print 'Right pressed'
ArmMove(.1,[0,1,ArmLight])
#Here we handle the nunchuk, along with the joystick and the buttons
while(1):
if Wii.state.has_key('nunchuk'):
try:
#Here is the data for the nunchuk stick:
#X axis:LeftMax = 25, Middle = 125, RightMax = 225
NunchukStickX = (Wii.state['nunchuk']['stick'][cwiid.X])
#Y axis:DownMax = 30, Middle = 125, UpMax = 225
NunchukStickY = (Wii.state['nunchuk']['stick'][cwiid.Y])
#The 'NunchukStickX' and the 'NunchukStickY' variables now store the stick values
#Here we take care of all of our data for the accelerometer
#The nunchuk has an accelerometer that records in a similar manner to the wiimote, but the
number range is different
#The X range is: 70 if tilted 90 degrees to the left and 175 if tilted 90 degrees to the right
NAccx = Wii.state['nunchuk']['acc'][cwiid.X]
#The Y range is: 70 if tilted 90 degrees down (the buttons pointing down), and 175 if tilted 90
degrees up (buttons pointing up)
NAccy = Wii.state['nunchuk']['acc'][cwiid.Y]
#I still don't understand the z axis completely (on the wiimote and nunchuk), but as far as I
can tell it's main change comes from directly pulling up the mote without tilting it
NAccz = Wii.state['nunchuk']['acc'][cwiid.Z]
#Make it so that we can control the arm with the joystick
if (NunchukStickX < 60):
ArmMove(.1,[0,2,ArmLight])
print 'Moving Left'
if (NunchukStickX > 190):
ArmMove(.1,[0,1,ArmLight])
print 'Moving Right'
if (NunchukStickY < 60):
ArmMove(.1,[128,0,ArmLight])
print 'Moving Down'
if (NunchukStickY > 190):
ArmMove(.1,[64,0,ArmLight])
print 'Moving Up'
#Make it so that we can control the arm with tilt Functions
#Left to Right
if (Accx < 100 and NAccx < 90 ):
ArmMove(.1,[0,2,ArmLight])
print 'Moving Left'
if (Accx > 135 and NAccx > 150):
ArmMove(.1,[0,1,ArmLight])
print 'Moving Right'
#Up and Down
if (Accy < 100 and NAccy < 90):
122
ArmMove(.1,[64,0,0])
print 'Moving Up'
if (Accy > 135 and NAccy > 150):
ArmMove(.1,[128,0,0])
print 'Moving Down'
#Here we create a variable to store the nunchuck button data
#0 = no buttons pressed
#1 = Z is pressed
#2 = C is pressed
#3 = Both C and Z are pressed
ChukBtn = Wii.state['nunchuk']['buttons']
if (ChukBtn == 1):
print 'Z pressed'
ArmLight = 0
ArmMove(.1,[0,0,ArmLight])
if (ChukBtn == 2):
print 'No nunchuk detected.'
else:
if (ArmLight == 0):
if (Accz > 179 or Accz < 50):print 'C pressed'
ArmLight = 1
ArmMove(.1,[0,0,ArmLight])
#If both are pressed the led blinks
if (ChukBtn == 3):
print 'C and Z pressed'
ArmMove(.1,[0,0,0])
time.sleep(.25)
ArmMove(.1,[0,0,1])
time.sleep(.25)
ArmMove(.1,[0,0,0])
time.sleep(.25)
ArmMove(.1,[0,0,1])
time.sleep(.25)
ArmMove(.1,[0,0,0])
time.sleep(.25)
ArmMove(.1,[0,0,1])
time.sleep(.25)
ArmMove(.1,[0,0,0])
#Any other actions that require the use of the nunchuk in any way must be put here for the error
handling to function properly
break
#This part down below is the part that tells us if no nunchuk is connected to the wiimote
except KeyError:
ArmLight = 1
ArmMove(.1,[0,0,ArmLight])
time.sleep(.5)
elif (ArmLight == 1):
if (Accz > 179 or Accz < 50):
ArmLight = 0
ArmMove(.1,[0,0,ArmLight])
time.sleep(.5)
if (Counter == 10000):
print 'No nunchuk detected.'
Counter = Counter/10000
break
123
Counter = Counter + 1
break
Robot Arm GUI (in Python) - WIP
When running this program you MUST use sudo startx or it will not let you access the USB controller if
running this script via IDLE (or IDLE3)
Hmpf, still working this out.
You need the image of the robot arm, 600x600
GIF (the controls use the co-ordinates for
positioning buttons!)
Lambda is required to send the intial status.
Currently the program will not load until the arm is
connected.
There are differences between Python 2.7 and
Python 3.x
from tkinter import *
from tkinter import ttk
import time
#import usb.core, usb.util,
#Code got from here - http://pythondictionary.codeit.co.uk/tkinter
#& here - http://www.tutorialspoint.com/python/
python_gui_programming.htm
#Set up our arm transfer protocol through the usb and
define a Value we can change to control the arm
Duration = 1
TKInter changes case between them. For 3.3 use
#Create delay variable that we can use (Seconds)
Delay = .1
Counter = 9999
from tkinter import *
from tkinter import ttk
#INSERT CODE TO TEST FOR ARM HERE (untested)
Then for 2.7 use
#This routine by http://www.instructables.com/member/
Boardmaster/
def ArmMove(Duration, ArmCmd):
from Tkinter import *
from Tkinter import Tk
#Arm Commands Defined by ArmMove are
if ArmCmd==[0,1,0]:
status='Rotate Base Clockwise'
elif ArmCmd==[0,2,0]:
status='Rotate Base C-Clockwise'
elif ArmCmd==[64,0,0]:
status='Shoulder Up'
elif ArmCmd==[128,0,0]:
status='Shoulder Down'
elif ArmCmd==[16,0,0]:
status='Elbow Up'
elif ArmCmd==[32,0,0]:
status='Elbow Down'
elif ArmCmd==[4,0,0]:
status='Wrist Up'
elif ArmCmd==[8,0,0]:
status='Wrist Down'
elif ArmCmd==[2,0,0]:
status='Grip Open'
elif ArmCmd==[1,0,0]:
status='Grip Close'
elif ArmCmd==[0,0,1]:
status='Light On'
else:
status='ALL OFF'
print (str(ArmCmd) + ' ' + status)
text.insert("@1,1", str(ArmCmd)+ ' ' + status
+'\n')
#Start Movement
#Arm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,1000)
time.sleep(Duration)
124
#Stop Movement
ArmCmd=[0,0,0]
#Arm.ctrl_transfer(0x40,6,0x100,0,ArmCmd,1000)
#Define an instance of TK for the window.
root = Tk()
#Give the window a title.
root.title("MRO Robot Arm Controller")
#Setup the Canvas, this is based on the Robot Arm
image, 600x600
can1=Canvas(root, width=600, height=600)
can1.pack()
#Places the canvas
#Define where the image is for the robot arm.
filename = PhotoImage(file = "robot.gif")
#Put the image on the Canvase, the first 2 args are coords...
#the anchor says which part of the image these are
relative to, NW (top left!)
image = can1.create_image(0, 0, anchor=NW,
image=filename)
#Define base buttons
but_baseleft = Button(root, text="BASE \n LEFT",
command=lambda: ArmMove(0.1,[0,2,0]))
but_baseleft.pack()
but_baseleft.place(bordermode=OUTSIDE, height=50,
width=50, x=450,y=450)
but_baseright = Button(root, text="BASE \n RIGHT",
command=lambda: ArmMove(0.1,[0,1,0]))
but_baseright.pack()
but_baseright.place(bordermode=OUTSIDE, height=50,
width=50, x=500,y=450)
#Define shoulder buttons
but_shoulderup = Button(root, text="SHOULDER \n UP",
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
\n DOWN", font='Ariel 6', command=lambda:
ArmMove(0.1,[128,0,0]))
but_shoulderdown.pack()
but_shoulderdown.place(bordermode=OUTSIDE, height=50,
width=50, x=150,y=300)
#Define elbow buttons
but_elbowup = Button(root, text="ELBOW \n LEFT",
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 \n RIGHT",
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)
#Define wrist buttons
but_wristup = Button(root, text="WRIST \n UP",
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 \n DOWN",
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)
125
#Define grip
but_gripopen = Button(root, text="GRIP \n OPEN",
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 \n CLOSE",
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)
#This always needs to be at the END!
root.mainloop()
126
7 Segment Display Project (One of my first test projects!)
https://projects.drogon.net/7-segment-led-display-for-the-raspberry-pi/
Using 4543 BCD (Binary Coded Decimal) Chips (x2 for 10s and Units Display) - Feed the same data to
both chips DA,DB,DC,DD, different Latches (LD and LD2 on other chip!).
For this chose common Catchode.
For this I installed FLASK which lets you contol devices etc via the web-browser or even someone far
away doing it :)
sudo pip install flask
127
128
Chips for driving motors
http://www.hobbytronics.co.uk/motor-control/h-bridge-driver-sn754410
http://www.fanjita.org/serendipity/archives/61-Raspberry-Rover-part-2-The-Hardware.html#extended
LCD Setup
Using standard LCD displays to get output from the Pi (Cheap Displays Ordered from Ebay / China)
http://www.raspberrypi-spy.co.uk/2012/07/16x2-lcd-module-control-using-python/
http://www.raspberrypi-spy.co.uk/2012/08/16x2-lcd-module-control-with-backlight-switch/
129
Cheap 3.5 LCD Display.
http://www.raspberrypi-spy.co.uk/2012/11/cheap-miniature-lcd-screen/
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=64&t=17651
Works a treat, used a funky
little PSU I bought from
Wilkinsons (for around £5
I think that switches DC
Voltages upto 12 volts.
Bargain.
Used the standard setup to change the FONT to something more readable.
sudo dpkg-reconfigure console-setup
Making it run off a USB??? - http://www.raspberrypi.org/phpBB3/viewtopic.php?f=64&t=17651
130
Setting up an iBeacon
http://learn.adafruit.com/pibeacon-ibeacon-with-a-raspberry-pi?view=all
http://www.theregister.co.uk/2013/11/29/feature_diy_apple_ibeacons/
“Feature US department store Macy’s recently said it is implementing iPhone-based tracking tech the
better to encourage browsing punters to buy. Of course, Macy has chosen to pitch this as an Apple
technology - figuring, presumably, iPhone owners are more receptive to inducements delivered through
technology and have more cash to splash than Android fans.”
Install The Required Software
First run this:
sudo apt-get install libusb-dev libdbus-1-dev libglib2.0-dev libudev-dev libical-dev
libreadline-dev
Next install BlueZ’s source files and compile it.
The version at the time of writing was 5.11.
sudo wget www.kernel.org/pub/linux/bluetooth/bluez-5.11.tar.xz
sudo unxz bluez-5.11.tar.xz
sudo tar xvf bluez-5.11.tar
cd bluez-5.11
sudo ./configure --disable-systemd
sudo make
sudo make install
This will take a while, but when it’s done, you can reboot and plug in the dongle.
Check for your USB Module
This should give you a list of devices on your system:
sudo hciconfig
If everything is properly configure you will see your Bluetooth 4.0 USB Module like this:
Enable the USB Device
Next you can enable the device with the following commands, turning off device scanning since this can
cause problems when advertising:
131
sudo hciconfig hciO up
sudo hciconfig hci0 leadv
sudo hciconfig hci0 noscan
Then run the hciconfig tool again and you should see that the device is marked as UP andRUNNING:
sudo hciconfig
Enter the iBeacon Advertising Data
The last thing to do is to enter the iBeacon advertising data, which we can do with the following
command (which should all be on one line):
sudo hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 E2 0A 39 F4 73 F5
4B C4 A1 2F 17 D1 AD 07 A9 61 00 00 00 00 C8 00
FF identifies the start of the Manufacturer Specific Data, 4C 00 is Apple's company ID (0x004C), and
then you can see the reset of the iBeacon payload until C8.
Testing it on iOS
To test that this actually works you'll need an iOS 7 based iPad/iPhone/iPod Touch, and the freeBeacon
Toolkit app.
Start the app up, going into 'Listen' mode, and you should see a screen similar to the capture below,
where the range will go in and out depending on your proximity to the node:
132
HARDWARE - Controllers
84
Graphics Testing / Visual Joystick Test
sudo apt-get install jstest-gtk
This will then appear in X under one of the menus. Works quite well for visual testing.
Wiimote Basics
Getting the drivers / setup
Ensure Bluetooth is installed sudo apt-get install bluetooth
Run 'bluetooth status' from
service bluetooth status
Should say 'started'
Install CWiiD & WMInput
sudo apt-get install python-cwiid wminput wmgui
Run the hcitool
sudo hcitool dev
This should show a device (hci summat... if it doesn't try plugging bluetooth into PI not hub! or a reboot!)
Run a scan
sudo hcitool scan
This should list your wiimote as Nintendo RVL
Use this script to test
get the script - wget http://www.raspberrypi-spy.co.uk/archive/python/wii_remote_1.py
Run the script - python wii_remote_1.py
133
134
Running WiiMote as a Mouse.
First you need to edit a file so that it detects the Gyros etc.
sudo nano /etc/cwiid/wminput/ir_ptr
Find Find these lines:
Plugin.ir_ptr.X = ~ABS_X
Plugin.ir_ptr.Y = ~ABS_Y
and replace them with:
Plugin.ir_ptr.X = ABS_X
Plugin.ir_ptr.Y = ABS_Y
(ensure your sensor bar is plugged in!)
Finally run this (the -d means it runs as a daemon, daemons good, demons bad!)
wminput -d -c <config filename from /etc/cwiid/wminput>
or this one for no output.
nohup wminput -d
Wii-Mote Button Mappings
Note the RIGHT button should be 512!!!
A Better Diagram
135
WIIMote Info
https://help.ubuntu.com/community/CWiiD
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=9&t=1233
Using the Wiimote - http://talk.maemo.org/showthread.php?t=60178
http://www.brianhensley.net/2012/08/wii-controller-raspberry-pi-python.html
http://linux.die.net/man/1/wminput
http://abstrakraft.org/cwiid/wiki/ConfigScriptEtc - Scripts to install. (need to know the MAC address of WII
Mote)
http://www.raspberrypi-spy.co.uk/2013/02/nintendo-wii-remote-python-and-the-raspberry-pi/
136
Creating Custom WiiMote Configs
cd /etc/cwiid/wminput/
Edit / Copy / Mess with the scripts (sudo nano default) - default
sudo nano fps_config - allows for nunchuck, just save your config as something different.
Daemons allow you to run stuff on start.
You can edit the Bluetooth Daemon (runs on start)
sudo nano /etc/init.d/bluetooth
(do ctrl+W and search for wminput, add -c <config> for it to run a specific config.
https://github.com/rpl/python-wiimote-hacks
Using Wii-Motes in Python Projects
For a few step by step guides
http://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/robot/getting_started/
- this script is a great place to start.
wget http://www.raspberrypi-spy.co.uk/archive/python/wii_remote_1.py
#!/usr/bin/python
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#|R|a|s|p|b|e|r|r|y|P|i|-|S|p|y|.|c|o|.|u|k|
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# wii_remote_1.py
# Connect a Nintendo Wii Remote via Bluetooth
# and read the button states in Python.
#
# Project URL :
# http://www.raspberrypi-spy.co.uk/?p=1101
#
# Author : Matt Hawkins
# Date
: 30/01/2013
# ----------------------# Import required Python libraries
# ----------------------import cwiid
import time
button_delay = 0.1
print 'Press 1 + 2 on your Wii Remote now ...'
time.sleep(1)
# Connect to the Wii Remote. If it times out
137
# then quit.
try:
wii=cwiid.Wiimote()
except RuntimeError:
print "Error opening wiimote connection"
quit()
print 'Wii Remote connected...\n'
print 'Press some buttons!\n'
print 'Press PLUS and MINUS together to disconnect and quit.\n'
wii.rpt_mode = cwiid.RPT_BTN
while True:
buttons = wii.state['buttons']
# If Plus and Minus buttons pressed
# together then rumble and quit.
if (buttons - cwiid.BTN_PLUS - cwiid.BTN_MINUS == 0):
print '\nClosing connection ...'
wii.rumble = 1
time.sleep(1)
wii.rumble = 0
exit(wii)
# Check if other buttons are pressed by
# doing a bitwise AND of the buttons number
# and the predefined constant for that button.
if (buttons & cwiid.BTN_LEFT):
print 'Left pressed'
time.sleep(button_delay)
if(buttons & cwiid.BTN_RIGHT):
print 'Right pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_UP):
print 'Up pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_DOWN):
print 'Down pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_1):
print 'Button 1 pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_2):
print 'Button 2 pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_A):
138
print 'Button A pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_B):
print 'Button B pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_HOME):
print 'Home Button pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_MINUS):
print 'Minus Button pressed'
time.sleep(button_delay)
if (buttons & cwiid.BTN_PLUS):
print 'Plus Button pressed'
time.sleep(button_delay)
139
XBox 360 Pad
Install the XBox Pad Drivers.
sudo apt-get install xboxdrv
http://pingus.seul.org/~grumbel/xboxdrv/xboxdrv.html
Create a mapping file
(create a directory to put the mappings in)
cd ~
mkdir Xbox
cd Xbox
sudo nano basic_config
An example mapping file can look something like
this...
(Left Stick acts like Keys, WASD)
(Right Stick acts like mouse - x2,y2)
(copy and paste the following!)
[xboxdrv]
silent=true
deadzone=6000
dpad-as-button=true
trigger-as-button=true
[ui-axismap]
#Map the Right stick like a mouse.
x2=REL_X:10
y2=REL_Y:-10
#Map the left stick as keys
x1=KEY_A:KEY_D
y1=KEY_W:KEY_S
#Map the 4 coloured buttons
[ui-buttonmap]
a=KEY_LEFTSHIFT
b=BTN_C
x=BTN_EXTRA
y=KEY_C
#Map the Bumper Buttons
[ui-buttonmap]
lb=BTN_RIGHT
rb=KEY_SPACE
#Map the Triggers.
[ui-buttonmap]
lt=KEY_Z
rt=BTN_LEFT
#Map the D-PAD
[ui-buttonmap]
dl=KEY_4
dr=KEY_2
du=REL_WHEEL:-1:150
dd=REL_WHEEL:1:150
[ui-buttonmap]
back=KEY_TAB
start=KEY_ESC
140
GUIDE=BTN_HOME
Alternative Joystick Setup.
For an alternative (for use with pygame etc) use
ABS Values (not REL)
[ui-axismap]
#Right stick to ABS
x2=ABS_X
y2=ABS_Y
#Left stick to Mouse
x1=REL_X:10
y1=REL_Y:-10
[ui-buttonmap]
a=BTN_A
b=BTN_B
x=BTN_X
y=BTN_Y
Alternative Setup For XBMC.
# XBMC Configuration
# ==================
#
# This configuration file that with XBMC by emulating a wireless
# Xbox360 controller connected to the xpad kernel driver. It uses the
# configuration files that come with XBMC, so it should work out of
# the box without any further configuration of XBMC.
#
#
[xboxdrv]
ui-clear = true
extra-devices=false
extra-events=false
deadzone=6000
device-name = "Xbox 360 Wireless Receiver"
[ui-buttonmap]
#A=BTN_A
A=KEY_ENTER
#B=BTN_B
B=KEY_BACKSPACE
X=KEY_X
Y=KEY_ESC
#Steuerkreuz Links macht A, Steuerkreuz Rechts macht B
#DU=BTN_0
DU=KEY_UP
141
#DD=BTN_1
DD=KEY_DOWN
#DL=BTN_LEFT
DL=KEY_LEFT
#DR=BTN_RIGHT
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
[ui-axismap]
#x2=REL_RX:10
#y2=REL_RY:-10
x1=REL_X:10
y1=REL_Y:10
# The resp filter moves the neutral position to zero to work around a
# bug in XBMC, that causes bogus events when neutral position is
# elsewhere. It loses a bit of precision in the trigger as result, but
# that isn't noticable.
LT^resp:127:255=ABS_Z
RT^resp:127:255=ABS_RZ
# EOF #
Call the mapping using
sudo xboxdrv --config basic_config
Run it in the background using the above with an ‘&’ at the end.
Alternative calling
1) Start xboxdrv via - for example - (im my case for 2 controllers):
sudo xboxdrv --wid 0 --silent --deadzone 4500 --ui-buttonmap guide=KEY_ESC --led 8
--priority realtime --four-way-restrictor --ui-axismap x1^resp:-32000:4000:0:4000:32000,y1^resp:-32000:-4000:0:4000:32000 &
sudo xboxdrv --wid 1 --silent --deadzone 4500 --ui-buttonmap guide=KEY_ESC --led 9
--priority realtime --four-way-restrictor --ui-axismap x1^resp:-32000:4000:0:4000:32000,y1^resp:-32000:-4000:0:4000:32000 &
142
"--led ...", "--four-way-restrictor", "--ui-axismap..." should not be needed, but I played a LOT with nearly
all settings, because of another problem. I found out, that "--deadzone" is in fact needed for some games
when playing with the analog stick.
Kill all running versions using the killall command.
sudo killall xboxdrv
Running at Startup
To run the xbox driver at startup follow the above procedure, however add the command to the /etc/
rc.local e.g.
sudo nano /etc/rc.local
and add before the exit 0
sudo /home/pi/xbox/load.sh
goto the /home/pi/xbox directory and create a load.sh script.
sudo nano /home/pi/xbox/load.sh
Add the following lines.
#!/bin/bash
sudo rmmod xpad
sudo xboxdrv --config /home/pi/xbox/pico_config --silent
Save and Exit.
use chmod to make it executable
sudo chmod +x /home/pi/xbox/load.sh
https://github.com/petrockblog/RetroPie-Setup/wiki/Setting-up-the-XBox360-controller
Here is an example of what to insert in /etc/rc.local for 4 wireless pads (put this just before exit 0):
xboxdrv --trigger-as-button --wid 0 --led 2 --deadzone 4000 --silent &
sleep 1
xboxdrv --trigger-as-button --wid 1 --led 3 --deadzone 4000 --silent &
sleep 1
xboxdrv --trigger-as-button --wid 2 --led 4 --deadzone 4000 --silent &
sleep 1
xboxdrv --trigger-as-button --wid 3 --led 5 --deadzone 4000 --silent &
(replace the --wid by --id if you use wired controllers) You must swich-on your pads before booting the
raspberry.
Notice the sleep 1 between each instance: this prevents the RPi from setting random controllers with
random led status; adjust timing if necessary.
143
144
Using a PS3 controller
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.
sudo apt-get update
sudo apt-get install qtsixa
http://booting-rpi.blogspot.co.uk/2012/08/dualshock-3-and-raspberry-pi.html
http://www.raspians.com/Knowledgebase/ps3-dualshock-controller-install-on-the-raspberry-pi/
https://help.ubuntu.com/community/Sixaxis
Dualshock 3 and Raspberry PI
Getting Sony Dualshock 3 gamepad to work in Raspberry Pi on Raspbian (Debian Wheezy).
First of all, I'll need a bluetooth dongle, since Raspbery Pi doesn't have built-in one, listing of compatible
dongle you can find here.
So, install dependencies first
sudo apt-get install bluez-utils bluez-compat bluez-hcidump checkinstall libusb-dev
libbluetooth-dev joystick
It takes a while.
After all type "hciconfig" in console, you should see something like this.
pi@raspberrypi ~ $ hciconfig
hci0: Type: BR/EDR Bus: USB
BD Address: 00:1F:81:00:06:20 ACL MTU: 1021:4 SCO MTU: 180:1
UP RUNNING PSCAN
RX bytes:1260 acl:0 sco:0 events:46 errors:0
TX bytes:452 acl:0 sco:0 commands:45 errors:0
if not, your dongle seems not to be recognized by system.
So now, we need to pairing the dongle with the gamepad using this tool.
download and compile it.
sudo apt-get install pyqt4-dev-tools
sudo wget http://www.pabr.org/sixlinux/sixpair.c
gcc -o sixpair sixpair.c -lusb
145
After this you should have a executable file "sixpair".
Now connect your Dualshock via a USB cable to Raspberry Pi and launch this file with sudo.
sudo ./sixpair
Current Bluetooth master: DE:AD:BE:EF:00:00
Setting master bd_addr to: 00:1F:81:00:06:20
If you see this, it was successful.
Install a Sixaxis Joystick Manager. Download a last archive and compile only important for us part.
sudo wget http://sourceforge.net/projects/qtsixa/files/QtSixA%201.5.1/QtSixA-1.5.1-src.tar.gz
sudo tar xfvz QtSixA-1.5.1-src.tar.gz
cd QtSixA-1.5.1/sixad
make
sudo mkdir -p /var/lib/sixad/profiles
sudo make install
the last command make automatically a package for you, so you can later simple uninstall it, if you won't
it or use a different system, type "sudo make install" instead of "sudo checkinstall"
Now test it, for this launch temporary a sixad daemon.
sudo sixad --start
Then press a "PS" button on Dualshock gamepad, if you feel a vibration, it works, congratulations!
After all you can make "sixad" daemon starting at boot time.
sudo update-rc.d sixad defaults
reboot
If you have any trouble with recognition, you can debug your Dualshock controller with "jstest".
sudo jstest /dev/input/js0
PS3 Move???
http://www.pabr.org/linmctool/linmctool.en.html
PS3 Joystick Buttons and Axes
146
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.py also exposes the joystick's three-axis accelerometer and the single-axis gyroscope:
Axis
Description
16
Right-Left (positive is left)
17
Forward-Backward (positive is forward)
18
Up-Down (positive is up)
19
Yaw axis (positive is clockwise)
QJoyPad - Turning Joystick Commands into Keypresses.
- #I thinkt he liqt4-dev is VERY important here!
Download the QJoyPad files
sudo apt-get install libxtst-dev libqt4-dev build-essential
wget http://downloads.sourceforge.net/qjoypad/qjoypad-4.1.0.tar.gz
tar xvf qjoypad-4.1.0.tar.gz
cd qjoypad-4.1.0.tar.gz/src
../configure
make
sudo make install
147
Just run
qjoypad
(should show up in the system tray with a little gamepad icon.)
Manual Here - http://qjoypad.sourceforge.net/doc/doc_index.html
148
HARDWARE - USB Devices
98
WIFI ADAPTER???
TP Link wn725n (V2)
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=26&t=29752
http://blog.elevendroids.com/2012/12/precompiled-tp-link-wl-725n-driver-for-3-2-27-kernel/
1. copy 8188eu.ko to
/lib/modules/3.6.11+/kernel/driver/net/wireless
2. sudo depmod -a
3. modprobe 8188eu
4. ifconfig
Roll your own driver from this source.
https://github.com/lwfinger/rtl8188eu
Clone the Github
git clone http://github.com/lwfinger/rtl8188eu (Note I took the ‘s’ off the http)
RASPBMC Version here - https://dl.dropboxusercontent.com/u/99979776/8188eu.ko
http://smhaziq.blogspot.co.uk/2013/06/compiling-tp-link-wn725n-v2-driver-in.html
Edimax Dongle
http://www.savagehomeautomation.com/projects/raspberry-pi-installing-the-edimax-ew-7811un-usb-wifiadapte.html
Quick Webcam Monitor Guide via Motion
sudo apt-get install motion
sudo nano /etc/motion/motion.conf
Change Daemon off TO Daemon on
Change webcam_localhost = on TO webcam_localhost = off
Then ctrl+x , Y and then enter to save
Then do : sudo nano /etc/default/motion
Change start_daemon_motion=no TO start_darmon_motion=yes
Then ctrl+x, Y and then enter to save.
Then type: sudo service motion start
Then type ifconfig and pick out the number that will look like 192.168.x.xxx. This is your local IP address
of the PI.
Go to a browser and type it in i.e. 192.168.1.101 then put :8081. so it will look like
149
192.168.1.101:8081. Then you will see what your webcam sees.
This doesn’t seem to work at school (proxy browser issue!) - however you can use VLC player and stry
opening up the stream http://x.x.x.x:yyyy - This worked for me!
PS3 Camera Test under XDE.
You can use Guvcview, (this will only work when using the Pi, not via SSH!)
sudo apt-get install guvcview
Once installed start up X (if you haven’t already) you should now find a link under menu (sound and
video), run the app, should come up with a preview window and a settings window. I found this more
responsive than MOTION (see below) and a great way to test the eyetoy. (only seemed to work
320x240 but for £2 who cares!)
PS3 Eyetoy Camera Streaming - Using Motion
N.B. This ONLY worked for me with the camera plugged into the PI, not the HUB!
You may also have to do Hexxeh’s rpi-update (to get the latest firmware!)
Just managed to get my PS3 Eye camera working with the Pi, so thought I'd share how it's done in Debian. The
following steps will get the camera and Pi working together as a simple motion detection device with a web stream
that you can view on your local network:
1. Install the 'motion' package (http://www.lavrsen.dk/foswiki/bin/view/Motion/WebHome):
sudo apt-get install motion
2. Install the ffmpeg package:
sudo apt-get install ffmpeg
3. Edit the /etc/motion/motion.conf file and change the following setting from 'on' to 'off'. This is optional, but will
allow the camera to be viewed using another PC on your local network:
webcam_localhost off
4. If you wish to have basic control over the camera from a web browser (see step 11) then you can change the
following setting in the same file to 'off':
control_localhost off
5. Since the PS3 Eye camera is capable of capturing at a resolution of 640x480, we can make the following further
changes to the /etc/motion.conf file:
ffmpeg_video_codec msmpeg4
width 640
height 480
150
(or 320x240 if using a PS2 Eyetoy!)
# Text is placed in lower left corner
text_left SECURITY CAMERA %t - Office
Install wput so can FTP files.
# Command to be executed when a picture (.ppm|.jpg) is saved (default: none)# The filename
of the picture is appended as an argument for the command.on_picture_save wput ftp://
USERNAME:PASSWORD@REMOTE SERVER %f
6. Plug your PS3 Eye camera into a USB port on the Pi.
7. Find out the IP Address of your Pi and make a note of it for step 10:
ifconfig
This will give the following output:
eth0
Link encap:Ethernet HWaddr xx:xx:xx:xx:xx:xx
inet addr:192.168.32.47 Bcast:192.168.32.255 Mask:255.255.255.0
inet6 addr: fe80::ba27:ebff:fe40:357a/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:31800 errors:0 dropped:0 overruns:0 frame:0
TX packets:27108 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:20174919 (19.2 MiB) TX bytes:29838750 (28.4 MiB)
The address in the above example is 192.168.32.47.
8. Start up the motion application. Note that it has no GUI and can be run from the command line when you first
start up the Pi. It doesn't need to run within startx:
sudo motion -n
9. This will run the software in command-line mode, displaying startup information and errors directly to the
console. It also allows it to be stopped using Ctrl-C. If you want to run the software in the background as
a 'daemon', simply type 'motion' without the -n switch.
10. If everything has worked okay, you should be able to go to another computer on your network and browse to
your Pi's address to see the camera output:
http://192.168.32.47:8081
Using your Pi's address of course!
11. You can also browse to the feed on the Pi itself, although this will only work in Chrome and not Midori.
12. If you browse to the 'control port' address below, you also get rudimentary control over the motion software:
http://192.168.32.47:8080
13. Since this is a motion detection package, it automatically detects movement on the camera and creates '.jpg'
image and '.swf' video snapshots each time it sees movement on the camera. These are stored in the following
directory:
/tmp/motion
151
14. Note that these files will build up quite quickly if the camera is pointed at something that moves a lot, so make
sure you have plenty of space on your sd card. Also, since the files are stored in /tmp, they will be deleted each
time you reboot your Pi.
Further Reading here - http://chris.gg/2012/07/using-a-ps3-eyetoy-with-the-raspberry-pi/
(running as a daemon!)
A great way to view your images / swf videos is to use WinSCP and dig them out of the /root/tmp/
motion folder (unless you changed it!)
Face Recognition on the Pi.
Tutorial and guide found here
It’s a bit disjointed in places, some of the code is a bit unclear (in the wrong place) or not quite there, this
has a difficulty of HARD! But I have learn lots along the way! :)
GUVCVIEW
First get the webcam working with guvcview (see above
sudo apt-get install update && apt-get install update -y
sudo apt-get install guvcview
CMAKE
Next install CMAKE (this allows you to compile c code on the pi!)
sudo apt-get update
sudo apt-get install cmake
OPENCV
Install the code to run OpenCV once compiled from Python
sudo apt-get update
sudo apt-get install libopencv-dev
sudo apt-get install python-opencv
Testing this installed is a little more complicated! First go here to find the code for OpenCV
Make a new folder call it OpenCV
mkdir OpenCV
sudo nano display image.cpp
paste the following code in (don’t use the link, some of the code is missing CV parts!)
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main( int argc, char** argv )
152
{
if( argc != 2)
{
cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
return -1;
}
Mat image;
image = imread(argv[1], CV_LOAD_IMAGE_COLOR);
// Read the file
if(! image.data )
// Check for invalid input
{
cout << "Could not open or find the image" << std::endl ;
return -1;
}
namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image );
// Show our image inside it.
waitKey(0);
window
return 0;
}
// Wait for a keystroke in the
Make another file for make instructions.
sudo nano CMakeLists.txt
paste the following code into it.
cmake_minimum_required(VERSION 2.8)
project( displayimage )
find_package( OpenCV REQUIRED )
add_executable( displayimage display_image.cpp )
target_link_libraries( displayimage ${OpenCV_LIBS} )
Save it (this is the file that give the compiler the settings to use, you’ll be chaning this several times)
Find a reasonable sized image on the net (a jpg image around 300x300), I used
wget <url>
to grab the file, then rename it using
mv <filename.jpg> sample.jpg
to put it all together finally, compile the c, make the instruction file (executable) and run the code.
cmake .
make
./displayimage sample.jpg
If all has worked your picture *should* appear on the screen!
Install the face recognition API
Download the libfacerec file, unzip, compile and make.
153
wget https://github.com/bytefish/libfacerec/zipball/v0.04
unzip v0.04
rm v0.04
cd libfacerec
cmake .
make
This sounds bonkers but to test if it’s all installed ok we go back to your display image example. Edit the
makefile to include the libfacerec libraries. (Look something like this!)
cmake_minimum_required(VERSION 2.8)
project( reco )
find_package( OpenCV REQUIRED )
add_executable( displayimage display_image.cpp )
target_link_libraries( displayimage /home/pi/libfacerec/bytefish-libfacerec-e1b143d/
libopencv_facerec.a ${OpenCV_LIBS} )
Compile and make again to test it works.
cmake .
make
./displayimage sample.jpg
Hopefully this will work, if it does things are going well.
Gathering Photos
You have to train the Pi to ‘KNOW’ who it’s looking at. To do this it needs a set of
portrait photos (30 suggested). They should be headshots, face on. However you can just
save a large selection of photos and then get the Pi to sort, prep and preen them. Dump the
initial photos in the OpenCV folder. (ensure they’re all called a1.jpg, a2.jpg etc.) - Time
for another C Program, ‘Prepare’
Edit the CMakeLists.txt file again with
cmake_minimum_required(VERSION 2.8)
project( prepare )
find_package( OpenCV REQUIRED )
add_executable( prepare preparePhoto.cpp )
target_link_libraries( prepare ${OpenCV_LIBS} )
use wget to gather the program.
wget http://raufast.org/download/preparePhoto.cpp
cmake .
make
./prepare 0.3 100 hs 800 1
This will probably crash out a few times, just delete the offending file and re-run. It saved all of my
files as hsX.jpg. You’ll have to do this for each FACE you want to recognise (upto 4 apparently!)
Move all of these files into a Faces Folder then a subfolder for each person.
-OpenCv
-OpenCv/Faces/S1
154
This is difficult to get right, but you need to generate a CSV file that will be used later
by the reco (recognition software). I tried doing this manually but couldn’t get it work.
There’s a script you can run. (available from here)
N.B. - (You can do this just using WinSCP, highlight all the files, use copy to clipboard, use nano 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/env python
import sys
import os.path
# This is a tiny script to help you creating a CSV file from a face
# database with a similar hierarchie:
#
# philipp@mango:~/facerec/data/at$ tree
# .
# |-- README
# |-- s1
# |
|-- 1.pgm
# |
|-- ...
# |
|-- 10.pgm
# |-- s2
# |
|-- 1.pgm
# |
|-- ...
# |
|-- 10.pgm
# ...
# |-- s40
# |
|-- 1.pgm
# |
|-- ...
# |
|-- 10.pgm
#
if __name__ == "__main__":
if len(sys.argv) != 2:
print "usage: create_csv <base_path>"
sys.exit(1)
BASE_PATH=sys.argv[1]
SEPARATOR=";"
label = 0
for dirname, dirnames, filenames in os.walk(BASE_PATH):
for subdirname in dirnames:
subject_path = os.path.join(dirname, subdirname)
for filename in os.listdir(subject_path):
abs_path = "%s/%s" % (subject_path, filename)
print "%s%s%d" % (abs_path, SEPARATOR, label)
label = label + 1
I dumped this in the Faces folder, then ran using
python create_csv.py /home/pi/OpenCv/Faces > faces.csv
155
I later moved this csv back out into the OpenCv Folder (easier)
Install the Reco Program
Edit our old friend the CMakeLists.txt.
cmake_minimum_required(VERSION 2.8)
project( reco)
find_package( OpenCV REQUIRED )
add_executable( reco faceReco.cpp )
link_directories( /home/pi/libfacerec/bytefish-libfacerec-e1b143d)
target_link_libraries( reco /home/pi/libfacerec/bytefish-libfacerec-e1b143d/
libopencv_facerec.a ${OpenCV_LIBS} )
wget http://raufast.org/download/faceReco.cpp
cmake .
make.
FINALLY...
Run the damn thing from X (on the PI)
./reco faces.csv 1 5500
I will do some further testing on this and get some photos of myself and perhaps another
individual and see what I can get working. An interesting idea / concept though! It was
able to recognise at least one picture of Angelina Jolie I used! Further testing with ipad
to follow!
Removing the IR Filter on The Eyetoy
http://createdigitalmotion.com/2009/08/trick-out-your-ps3-eye-webcam-best-cam-for-vision-augmentedreality/
This video demonstrates how to disassemble, remove IR Filter and re-assemble!)
Using Multiple Cameras with Motion
To do this you need to add a thread per camera.
sudo nano /etc/motion/motion.conf
then at the bottom add...
thread /etc/motion/thread1.conf
thread /etc/motion/thread2.conf
etc...
You need a config (conf) for each camera you intend to use.
create the thread1.conf file using
sudo nano /etc/motion/thread1.conf
156
It only really needs the following code.
videodevice /dev/video0
text_left USBWebcam-1
target_dir /home/ndmaque/motion/images/webcam2
webcam_port 8081
Similarly create thread2.conf
sudo nano /etc/motion/thread2.conf
videodevice /dev/video1
text_left USBWebcam-2
target_dir /home/ndmaque/motion/images/webcam2
webcam_port 8082
Notice how they have different ports so you can access them seperately, (note the separte devices!)
http://www.lavrsen.dk/foswiki/bin/view/Motion/MotionGuideOneLargeDocument
http://through-the-interface.typepad.com/through_the_interface/2012/09/creating-a-motion-detectingsecurity-cam-with-a-raspberry-pi-part-2.html
Retaliation (USB Rocket MOD!)
Rocket Launcher - http://itr8r.tumblr.com/post/31840231144/raspberry-pi-retaliation
Retaliation - https://github.com/codedance/Retaliation#readme
Retaliation in Scratch http://itr8r.tumblr.com/post/40413865818/scratch-retaliation
N.B. You can plug the rocket launcher into the Pi, but it will probably error, or try a HUB, but it will need
some power going to it. 1 amp? Fire FAILS on my setup (I suspect due to it being knackered or lack of
power!) Will test at school when get chance!
The python-usb yum module is not new enough to work with the retaliation code. Instead download the
source for 1.0 from pyusb.
Untar into a directory, then install pyusb with:
sudo apt-get install python libusb-0.1-4
git clone https://github.com/walac/pyusb.git
cd pyusb
sudo python setup.py install
157
Step 2 - Download retaliation:
sudo wget https://raw.github.com/codedance/Retaliation/master/retaliation.py
sudo chmod +x retaliation.py
Step 3 - Connect and test
Connect the missile launcher (I used a powered USB hub) and test with a command such as
sudo ./retaliation.py zero
sudo ./retaliation.py left 1000
Step 4 - Modify the script as needed for your office & enjoy
Retaliation Modification to Script. (TO REDO to use KEYBOARD!)
158
TVHead Test for XBMC
I got a August DVB-T205 TV Capture USB Stick / Dongle. Heard they are compatible with RPi etc,
and fancied giving LiveTV / PVR / Streaming a go.
I did some general reading around these links.
https://github.com/ambrosa/DVB-Realtek-RTL2832U-2.2.2-10tuner-mod_kernel-3.0.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/using-pvr-with-raspbmc
Getting the device recognised in Linux.
First ensure some dependants are installed (in case of compiling etc)
sudo apt-get install make gcc pkg-config libavahi-client-dev libssl-dev buildessential
Get the August DVB-T205 - Driver
https://mega.co.nz/#!nZNkRJzS!
Mx3BSGwU6BQLFUVkuY4ce0h7IDtKSELDc5USfKsyg3k
I was unable to WGET this file as it’s a MEGA load (one you have to click through on and supply a
catchpa.
I then WinSCP’d Driver to Pi.
Untar it.
sudo tar -xvf <filename>
Copy to correct folder (you can use mv </path/filename> </newpath/filename>), but I think I did in in
WinSCP (moved the .ko file)
/lib/modules/3.6.11/kernel/drivers/media/dvb/dvb-usb/
Refresh the drivers in Linux to pick up this change using
sudo depmod -a (to update all the drivers etc)
reboot.
NOTE:
This Dongle ONLY seemed to work if plugged into the PI!!!
TVHead backend - http://wiki.xbmc.org/index.php?title=PVR/Backend/Tvheadend
Access TVHead using - http://<Pi IP Address>:9981
159
So far managed to get TV channels tuned, EPG working (via web browser) and then record a
program in ts(standard format) or MKV that seems better!
Some detail here about watching LiveTV that does not seem to work.
http://forum.xbmc.org/showthread.php?tid=148646&page=34
Stuff still to do, get wireless working with Lloyds USB Dongle?
Add a HDD and try recording to it, set this up as a Samba Share!!!
160
Hardware Add-on Boards
151
Berry Clip
http://www.raspberrypi-spy.co.uk/berryclip-6-led-add-on-board/
User Manual PDF
Once created run the following to install the simple software / drivers / examples.
mkdir berryclip
cd berryclip
wget https://bitbucket.org/MattHawkinsUK/rpispy-berryclip/get/master.tar.gz
tar -xvf master.tar.gz --strip 1
The navigate to berryclip and run any one of the examples provided. For me the Buzzer did not work. :(
but everything else seemed straightforward and pretty easy to use.
berryclip_01.py – Test LEDs only
berryclip_02.py – Test Buzzer only
berryclip_03.py – Test Switch only
berryclip_04.py – Test LEDs and Switch
berryclip_05.py – Test LEDs, Buzzer and Switch
berryclip_06.py – LED sequence
berryclip_07.py – Dice Simulator
berryclip_08.py – Reaction time game
berryclip_09.py – Random LEDs
berryclip_10.py – Multiple LED sequences in a loop
berryclip_11.py – Traffic light simulator
berryclip_12.py – Morse code generator
Input / Output Pins on the BerryClip
LED 1 Pin 07 GPIO4
LED 2 Pin 11 GPIO17
LED 3 Pin 15 GPIO22
LED 4 Pin 19 GPIO10
LED 5 Pin 21 GPIO9
LED 6 Pin 23 GPIO11
Buzzer Pin 24 GPIO8
161
Switch Pin 26 GPIO7
162
LedBORG - http://www.piborg.org/ledborg
Rev 2, 2013-09-10 or 3.6.11+ build #538
mkdir ~/ledborg-setup
cd ~/ledborg-setup
wget -O setup.zip http://www.piborg.org/downloads/ledborg/
raspbian-2013-09-10-rev2.zip
unzip setup.zip
chmod +x install.sh
./install.sh
Usage
Colour options
The colours on an LedBorg are set as levels of red, green and blue; referred to as RGB
The available levels are:
●
●
●
0 -> Means channel is off
1 -> Means channel is at 50%
2 -> Means channel is at 100%
For example:
RGB of 200 means that red is on full, green is off and blue is off, producing RED
RGB of 210 means that red is on full, green is on half and blue is off, producing ORANGE
RGB of 202 means that red is on full, green is off and blue is on full, producing MAGENTA
RGB of 021 means that red is off, green is on full and blue is on half, producing SPRING GREEN
RGB of 222 means that red is on full, green is on full and blue is on full, producing WHITE
RGB of 000 means that red is off, green is off and blue is off, since all are off this turns LedBorg off (pseudo black)
All colours against numbers:
100
200
211
110
220
221
000
111
222
010
020
121
011
022
122
120
021
210
001
002
112
101
202
212
012
102
201
For tables with names and HTML codes see here
Controlling LedBorg
To set the colour from the GUI:
Find the GUI icon on the desktop where it will be called LedBorg with a PiBorg logo
Alternatively it can be found by browsing to /home/pi where it will be called ledborg_gui
Run the GUI by double-clicking on it
If a dialog box appears asking you what to do select Execute
163
Click on a box to change to the colour it shows
You can click on Demo Mode to run example sequences, including turning LedBorg into a CPU usage meter!
To set the colour from a Python script:
LedBorg = open('/dev/ledborg', 'w')
LedBorg.write('RGB')
del LedBorg
replacing RGB with the desired levels (see above)
To set the colour from a terminal type:
echo "RGB" > /dev/ledborg
replacing RGB with the desired levels (see above)
To set the colour from a terminal with the basic driver type:
~/ledborg-basic RGB
replacing RGB with the desired levels (see above), note that 50% options are not available to the basic driver and
100% will be used instead (only 8 colours including off)
To disable LedBorg from a terminal type:
sudo /etc/init.d/ledborg.sh stop
Note that this will free the GPIO pins for use, but will not affect if the LedBorg driver is started at boot time
To enable LedBorg from a terminal type:
sudo /etc/init.d/ledborg.sh start
Note that this will start using the GPIO pins, but will not affect if the LedBorg driver is started at boot time
Managing boot options
To set the boot-up colour from a terminal type:
echo "RGB" > /home/pi/ledborg_bootcolour
replacing RGB with the desired levels (see above)
To stop LedBorg from auto-loading from a terminal type:
sudo update-rc.d ledborg.sh remove
Note that this will stop LedBorg using the GPIO pins during boot, however the enable LedBorg instructions above
will be need to be used before trying to set a colour
To enable LedBorg auto-loading from a terminal type:
sudo update-rc.d ledborg.sh defaults 100
Note that this will start using the GPIO pins during boot, loading the colour specified by /home/pi/
ledborg_bootcolour
164
PILite LED Matrix http://cpc.farnell.com/ciseco/b040/pi-lite-led-matrix-raspberry-pi/dp/SC13018?
in_merch=New%20Products&MER=e-bb45-00001002
http://wiki.raspberrytorte.com/index.php?title=Pi_Lite - Best Setup Guide (simple)
http://openmicros.org/index.php/articles/94-ciseco-product-documentation/raspberry-pi/303-pi-litesetting-up-for-python-examples - Again Simple instructions
http://openmicros.org/index.php/articles/94-ciseco-product-documentation/raspberry-pi/280-b040-pi-litebeginners-guide
http://www.raspberrypi-spy.co.uk/tools/pi-lite-14x9-led-matrix-sprite-editor/
Access to the serial port
By default the Raspberry Pi’s serial port is configured to be used for console input/output. Whilst this is useful if you want to
login using the serial port, it means you can't use the Serial Port in your programs. Ciseco hardware, such as Slice of Pi, Slice
of Radio and Pi-Lite are connected to this serial port, so we need to set the Raspberry Pi up such that it gives up its exclusive
access to the serial port.
Disable Serial Port Login
To enable the serial port for your own use you need to disable login on the port. There are two files that need to be edited
The first and main one is /etc/inittab
To access this, open LXTerminal from your pi desktop, log into your pi as before and once Pi@respberrypi ~ $ shows, type:
sudo nano /etc/inittab
You will see a line similar to;
T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
Disable it by adding a # character to the beginning. Save the file.
#T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
Disable Bootup Info
165
When the Raspberry Pi boots up, all the bootup information is sent to the serial port. Disabling this bootup information is optional
and you may want to leave this enabled as it is sometimes useful to see what is happening at bootup. If you have a device
connected (i.e. Arduino) at bootup, it will receive this information over the serial port, so it is up to you to decide whether this is a
problem or not.
You can disable it by editing the file /boot/cmdline.txt
To find this, go back to the terminal screen and enter;
sudo nano /boot/cmdline.txt
The contents of the file looks like this;
dwc_otg.lpm_enable=0 console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4
elevator=deadline rootwait
You need to remove all references to ttyAMA0 (which is the name of the serial port we need access to). After your edits, the file
should now look like this;
dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait
Reboot
In order to enable the changes you have made, you will need to reboot the Raspberry Pi
sudo shutdown -r now
Programming from the Raspberry Pi
.
Hello World Python
Example
http://www.raspberrypispy.co.uk/2013/09/howto-setup-the-pi-lite-ledmatrix-board/
#!/usr/bin/env python
import sys
import serial
import time
# Define message complete with
# carriage return at the end
message1 = "Hello World!\r"
message2 = "Pi-Lite messages are easy!\r"
# Configure Pi serial port
s = serial.Serial()
s.baudrate = 9600
s.timeout = 0
s.port = "/dev/ttyAMA0"
try:
# Open serial port
s.open()
except serial.SerialException, e:
# There was an error
sys.stderr.write("could not open port %r: %s\n" % (port, e))
sys.exit(1)
print "Serial port ready"
# Clear display
s.write("$$$ALL,OFF\r")
# Send message 1 to the Pi-Lite
print message1
s.write(message1)
# Short delay to allow the
# 12 character message to finish
time.sleep(6)
166
# Send message 2 to the Pi-Lite
print message2
s.write(message2)
# Short delay to allow the
# 26 character message to finish
time.sleep(12)
print "Good bye"
167
SOFTWARE 109
GitHubs - Why They Rock!
GitHubs are repositories of files / software that are created / used when serveral people are working on /
updating a single software project. Other times this can just be a collection of file, e.g. Python scripts of
a particular type / collection. Some times you might want to get / collect / grab the GIT so that you can
compile your own version, or use the collection.
Firstly install the drivers and software to deal with GitHubs
sudo apt-get install git-core
It can often be handy to CLONE an entire GitHub!!!
How to clone your repo to your local machine ?
(in git terminology it’s called “checkout“)
First you need to find your repo address. It can be find on your GitHub repo page:
Copy the address in the box ([email protected]……/….git)
Open the terminal and go to the folder where you want to have your git to be located.
Type command:
git clone ADDRESS YOU COPIED
to update navigate to the right folder and use.
git pull
When you see a new script posted on the blog, to get it on your raspberry pi all you need to do is run the
following command to get the latest updates:
1. Run “git fetch origin” to download the latest updates
2. Run “git merge origin/master” to update the files in your current directory with them.
168
git clone git://github.com/??????????
Compiling Your Own Version of Software (Roll your own!)
Grab
Firstly Grab the software package you want (often Tar.gz, a Tar file (tape archive) that has been
compressed using Gzip)
use the command wget <filepath> to grab the Tar.gz
wget <full filepath inc http://>
extract the tar.gz to a path using
tar -xvf <filename>
delete the original file
rm <filename.tar.gz>
enter the extracted folder
cd <filename>
Configure
Now to Configure your package use
sudo ./configure
Make
Now MAKE the package (this often takes ages!)
sudo make
Make Install
Now do a MAKE INSTALL, this installs the software for your usages?
sudo make install.
169
SOFTWARE - Interfacing
111
Pi-Wall (WORKING!)
http://www.piwall.co.uk/information/10-create-your-own-gpl-movie-piwall
This codes should allow you to play back a video on a video wall of seveal screens!
(start with x4!)
The setup must consist of a Master that effectively broadcasts to the slave ‘tiles’
41 is top left
42 top right
43 bottom left
44 bottom right
I assume the first 4 refers to the fact it’s a x4 screens. The each one is addressed individually.
Setting up the units.
install libav-tools on each pi.
sudo apt-get install libav-tools
Copy pwlibs1_1.1armhf.deb and pwomxplayer_20130815_armhf.deb to the home directory.
extract dpkg the both.
sudo dpkg -i /home/pi/pwlibs1_1.1_armhf.deb
sudo dpkg -i /home/pi/pwomxplayer_20130815_armhf.deb
Network configuration
Each Pi needs to have a different IP address (obviously!) and you almost certainly want these to be
statically assigned. For this Guide we'll assume a private address range of 192.168.0.* if you need to
use another set of addresses, then adjust accordingly.
In a production environment, you may want to connect the master Pi to an existing network - this is best
achieved by adding a USB ethernet or WiFi adapter as a second interface to the master. Configuring this
second network interface is beyond the scope of this document.
In order for the master to communicate efficiently with the tiles, it uses multicast addressing (where
each packet sent by the master is received by all the tiles). The rules and guidelines for using multicast
170
addresses are complex; if the network is completely private then it doesn't really matter, but in this Guide
we'll use one of the "administratively scoped" addresses, 239.0.1.23. If you plan to use a real, shared
network, then speak to your network administrator to agree an address.
If you are using a Linux PC as your master and don’t want to permanently alter your network
configuration then execute the following commands after you have connected to the private PiWall
network.
“sudo ifconfig eth0 192.168.0.??? netmask 255.255.255.0 up”
“sudo route add -net 224.0.0.0 netmask 240.0.0.0 eth0”
Note that this enables the full multicast address range, even though we'll only be using a single address
within that range.
To make this routing permanent on a Raspberry Pi master or tile, edit the network interface stanza in "/
etc/network/interfaces", e.g.
iface eth0 inet static
address 192.168.0.???
netmask 255.255.255.0
up route add -net 224.0.0.0 netmask 240.0.0.0 eth0
We usually use an address of 100 for the master and number the tiles from 1, upwards.
Testing the software
First test a tile to ensure that it is working correctly. Start by connecting a keyboard to the tile and
attaching a USB pen drive that contains a movie that the standard omxplayer can display. Find the
path of the USB pen drive, from the command line type "df" this will list all the file systems on your Pi.
In the right hand column, look for the entry that has a path that starts with "/media/", on my system it
is "/media/18DA-7CE4". Prepend this path to the "movie.avi" argument in the following commands.
Confirm that the movie can be played by the standard omxplayer provided with the Raspbian image by
typing "omxplayer movie.avi" at the command prompt. Next verify that pwomxplayer can play the movie
by typing "pwomxplayer movie.avi". Finally check that pwomxplayer can show a section of the video
by typing "pwomxplayer --tile-code=42 movie.avi" which should display just the top right corner of the
original movie, but magnified to fill the whole screen.
Now you're ready to test the master in conjunction with one or more tiles. On each Raspberry Pi tile
type "pwomxplayer --tile-code=$n udp://239.0.1.23:1234?buffer=1200000B" (where $n=41 is the top left,
42 is the top right, 43 is the bottom left and 44 is the bottom right for a 4 screen PiWall). On the master
type "avconv -re -i movie.avi -vcodec copy -f avi -an udp://239.0.1.23:1234"
(possible with output sound?
avconv -re -i movie.avi -vcodec copy -f avi -an udp://239.0.1.23:1234 –enable-outdev=ALSA
171
The "--tile-code" configuration doesn't provide bezel compensation, for that you will need to provide a
detailed PiWall configuration file. That will be the subject of a further guide to be published later this
week.
Looping an Video on the screens.
On the Raspberry Pi master just create a simple bash script (you could save it as "forever") ...
while true
do
avconv -re -i movie.avi -vcodec copy -an -f avi udp://239.0.1.23:1234
done
Don't forget to either make the script executable or run it by prepending the name of the bash script with sh, eg "sh
forever".
Multicasting Input from the Pi Camera (untested!)
In theory it should be possible to PIPE the output of the Pi Camera to display on your video wall using
something like this.
raspivid -o - -t 10000 -vf | avconv -re -r - -vcodec copy -f avi -an udp://
239.0.1.23:1234
The -t 10000 might not be needed (until tested!)
The -vf is the vertical flip of the camera output.
172
Fritzing
http://fritzing.org/forum/thread/1338/
PI-Car
The Pi-Car project like many others now seem to be doing controls a remote controlled car using the
remote hacked to work with the GPIO pins on the RPi. There’s even a python script that can be run so
that you can control the car through Scratch.
http://pi-cars.com/
http://pi-cars.com/under-the-bonnet/
http://pi-cars.com/2012/12/23/pi-cars-and-scratch-driving-lesson-1/
- this page guides you on how to create the Python file needed to hook into
Scratch.
173
Using Twitter
http://blog.kugelfish.com/2012/08/kugelbot-or-what-to-do-with-raspberry-pi.html
https://pypi.python.org/pypi/twitter/
The projects listed here all require you to have a twitter account. I setup a seperate account so I
could do Pi Testing.
@AMC_PI
letmein (with a few numbers) - Add this to keepass and remove.
Once you have signed up you need to log into https://dev.twitter.com, this will allow you access to
creating apps around / using twitter. You’ll need to create a new APP.
You will need to then carry out the following steps in order to get access keys and consumer keys which
will allow us to authenticate the twitter account and application without having to keep entering in login
data. This uses the OAuth protocol which you can find out more about using google!
1. Select create a new application
2. Enter name, description, website
3. Select Yes I agree to the terms and conditions
4. Enter captcha information and click submit
You will see that by default the access level is set to read only. We will need to change this to read/write
to enable us to push tweets out to the world. To change this settings carry out the following steps.
1. Select settings along top menu tabs
2. Under application type select Read and Write
3. Ensure that “Allow this application to be used to Sign in with Twitter” is checked
4. Click the update this twitter applications settings button at the bottom of the page
If you now return to the Details tab you will see a number of special keys which include, consumer key/
secret and access token/secret. Leave the webpage open as we will need all of this information in a
minute to start tweeting.
Once you have done so there are 4 keys bits of info you need for most of these projects.
Consumer Key
Consumer Secret
Access Token
Access Token Secret
These are just random strings of letters / numbers, but you will need them to do any twitter work.
Also once you have created your APP (on the twitter site) you’ll have to change the settings of
the app to either ‘read only’ or ‘read / write’. If you change the settings of the app the access
token and access token secret will change. I found this out! You can use the same app setup in
most of your Pi Projects.
174
Creating An Array of Followers (Partly Tested)
http://raspi.tv/2013/how-to-create-a-twitter-app-on-the-raspberry-pi-with-python-tweepy-part-1
This script will
just look at your
account, work out
all your followers
and select one at
random!!!
#!/usr/bin/env python2.7
# twitterwin.py by Alex Eames http://raspi.tv/?p=5281
import tweepy
import random
# Consumer keys and access tokens, used for OAuth
consumer_key = 'copy your consumer key here'
consumer_secret = 'copy your consumer secret here'
access_token = 'copy your access token here'
access_token_secret = 'copy your access token secret here'
# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
# Creation of the actual interface, using authentication
api = tweepy.API(auth)
follow2 = api.followers_ids() # gives a list of followers ids
print "you have %d followers" % len(follow2)
show_list = str(raw_input("Do you want to list the followers array?"))
if show_list == ('y' or 'yes' or 'Y' or 'Yes' or 'YES'):
print follow2
def pick_winner():
random_number = random.randint(0, len(follow2)-1)
winner = api.get_user(follow2[random_number])
print winner.screen_name, random_number
while True:
pick = raw_input("Press Enter to pick a winner, Q to quit.")
if pick == ('q' or 'Q' or 'quit' or 'QUIT' or 'Quit'):
break
pick_winner()
175
Creating a Python Script that can Tweet (Tested)
Create a simple python script called
SillyTweeter.py.
Use sudo chmod +x to make it
executable.
Run using
python SillyTweeter.py ‘This text will
be output to twitter’
#!/usr/bin/env python
import sys
from twython import Twython
CONSUMER_KEY = 'tRrx71zfMENmCV1t......'
CONSUMER_SECRET = 'eMoBaVi8OkoC3j6aDszc4VjXzeuddxV577......'
ACCESS_KEY = '2161868077-KlG5aiRfLuWrweKMpPPO7RFxapWzdHeEV......'
ACCESS_SECRET = '4HinfnCRL74IRG09c3JCWcy2gcl5QwiBJmbNqbD......'
api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
api.update_status(status=sys.argv[1])
N.B. the …... are to keep my tokens safe!
Copy and paste your own from Twitter!
Creating a Python Script that can Tweet Images (Tested)
Call the program like you did the
last example,
python TweetPhoto.py ‘/home/
pi/twitter/test.jpg’ ‘Any Text you
want here’
only instead of a message
add the path to file you with to
output!
#!/usr/bin/env python
import sys
from twython import Twython
import os
CONSUMER_KEY = 'tRrx71zfMENmCV1t…...'
CONSUMER_SECRET = 'eMoBaVi8OkoC3j6aDszc4VjXzeuddxV577…...'
ACCESS_KEY = '2161868077-KlG5aiRfLuWrweKMpPPO7RFxapWzdHeEV…...'
ACCESS_SECRET = '4HinfnCRL74IRG09c3JCWcy2gcl5QwiBJmbNqbD…...'
photo = open(sys.argv[1],'rb')
api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
#api.update_status(status=sys.argv[1])
api.update_status_with_media(media=photo, status=sys.argv[2])
176
Create a Python Script that can Tweet Images Via Raspicam, watermark them and Tweet
Them
sudo apt-get install python-pip
…and then enter:
sudo pip install https://
github.com/ashtons/picam/
zipball/master#egg=picam
import picam
i = picam.takePhoto()
i.save(‘/home/pi/test.jpg’)
You can use this command, but I
could not work out how to flip the
image, so instead I canlled the bash
commands within the script. This
allowed the use of imagemagick too
to watermark it!
More on Time in Python
http://www.cyberciti.biz/faq/howto-get-currentdate-time-in-python/
#!/usr/bin/env python
import sys
import time
import picam
from twython import Twython
import os
CONSUMER_KEY = 'tRrx71zfMENmCV1tkvVT4Q'
CONSUMER_SECRET = 'eMoBaVi8OkoC3j6aDszc4VjXzeuddxV5776BApo4'
ACCESS_KEY = '2161868077-KlG5aiRfLuWrweKMpPPO7RFxapWzdHeEV7Sqx75'
ACCESS_SECRET = '4HinfnCRL74IRG09c3JCWcy2gcl5QwiBJmbNqbD7wXoRx'
date_bit=time.strftime("%Y_%m_%d")
photopath = '/home/pi/twitter/'+ date_bit + '_photo.jpg'
print ('Going to save file as: ' + photopath)
os.system('raspistill -o temp.jpg -vf')
print ('About to convert photo!')
os.system('composite CTI_Pi_Big.png temp.jpg -gravity south '+
photopath)
print ('Just added a watermark')
uploadphoto = open(photopath,'rb')
api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
##api.update_status(status=sys.argv[1])
api.update_status_with_media(media=uploadphoto, status='PiCam Test
Final')
Creating a Python Script to Output System Info
http://c-mobberley.com/wordpress/index.php/2013/04/26/raspberry-pi-connect-to-twitter-account-using-tweepy-installation-and-tweetcpu-temperature-example/
It is possible to adapt this script to
output just about anything via the
api! Could be interesting.
#!/usr/bin/env python
import os
import sys
import tweepy
CONSUMER_KEY = '*****YOUR DATA******'
CONSUMER_SECRET = '*****YOUR DATA******'
ACCESS_KEY = '*****YOUR DATA******'
ACCESS_SECRET = '*****YOUR DATA******'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
177
cmd = '/opt/vc/bin/vcgencmd measure_temp'
line = os.popen(cmd).readline().strip()
temp = line.split('=')[1].split("'")[0]
api.update_status('My Current Processor Temperature: '+ temp + ' C')
Tweeting on a Set Interval
(Using the above example)
To edit the root cron file you must run the following command.
sudo crontab -e
It is very important to ensure the sudo command is used!
Once you are in the file you can then add the following line, just change the directory to point to where
your file is saved.
*/60 * * * * python /home/pi/Twitter/TweetTemp.py
Read Out Tweets (Untested)
http://www.stuffaboutcode.com/2012/10/raspberry-pi-python-talking-twitter.html
This process uses Google’s API to read out Tweets
out loud!
Install python-oauth
I used leah's python oauth module to authenticate with twitter.
Install distribute
If you have never installed python modules before you are
going to need to install the python setup tools, module,
distribute, see blog post, python - installing modules, for info on
how to do this.
Install git-core
In order to get the code from github you need to install git-core
tools.
#!/usr/bin/env python
# An experimental talking twitter client for the
Raspberry Pi
# written in Python, by Martin O'Hanlon
# www.stuffaboutcode.com
from oauth.oauth import OAuthRequest,
OAuthSignatureMethod_HMAC_SHA1
from hashlib import md5
import json, time, random, math, urllib, urllib2,
pycurl, subprocess, sys
# twitter oauth keys, get your from dev.twitter.com
CONSUMER_KEY = 'consumer key'
CONSUMER_SECRET = 'consumer secret'
ACCESS_TOKEN = 'access token'
ACCESS_TOKEN_SECRET = 'access token secret'
sudo apt-get install git-core
Get the code from git
git clone https://github.com/leah/python-oauth.git
Install the module
cd python-oauth
sudo python setup.py install
Install pycurl
pycurl is used to connect to the twitter streams.
sudo apt-get install python-pycurl
Install mplayer
mplayer is used to output the audio stream.
sudo apt-get install mplayer
# function to download a file from a url, used for
testing
def downloadFile(url, fileName):
fp = open(fileName, "wb")
curl = pycurl.Curl()
curl.setopt(pycurl.URL, url)
curl.setopt(pycurl.WRITEDATA, fp)
curl.perform()
curl.close()
fp.close()
# returns the appropriate google speech url for a
particular phrase
def getGoogleSpeechURL(phrase):
googleTranslateURL = "http://translate.google.com/
translate_tts?tl=en&"
parameters = {'q': phrase}
data = urllib.urlencode(parameters)
googleTranslateURL = "%s%s" %
(googleTranslateURL,data)
return googleTranslateURL
178
Create talking twitter client program
nano ttc.py
# function to download an mp3 file for a particular
phrase, used for testing
def downloadSpeechFromText(phrase, fileName):
googleSpeechURL = getGoogleSpeechURL(phrase)
print googleSpeechURL
downloadFile(googleSpeechURL, fileName)
# output phrase to audio using mplayer
def speakSpeechFromText(phrase):
googleSpeechURL = getGoogleSpeechURL(phrase)
subprocess.call(["mplayer",googleSpeechURL],
shell=False, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# class for managing tokens
class Token(object):
def __init__(self,key,secret):
self.key = key
self.secret = secret
def _generate_nonce(self):
random_number = ''.join(str(random.randint(0, 9))
for i in range(40))
m = md5(str(time.time()) + str(random_number))
return m.hexdigest()
# talking twitter client
class TalkingTwitterStreamClient:
def __init__(self, streamURL):
self.streamURL = streamURL
self.buffer = ""
self.conn = pycurl.Curl()
self.conn.setopt(pycurl.URL, self.streamURL)
self.conn.setopt(pycurl.WRITEFUNCTION,
self.on_receive)
self.conn.perform()
def on_receive(self, data):
sys.stdout.write(".")
self.buffer += data
if data.endswith("\n") and self.buffer.strip():
content = json.loads(self.buffer)
self.buffer = ""
#debug - output json from buffer
#print content
if "friends" in content:
self.friends = content["friends"]
if "text" in content:
print u"{0[user][name]}:
{0[text]}".format(content).encode('utf-8')
speakSpeechFromText(u"A tweet from
{0[user][name]}".format(content))
#downloadSpeechFromText(u"A tweet from {0[user]
[name]}".format(content), "./tweet.mp3")
speakSpeechFromText(u"{0[text]}".format(content))
#downloadSpeechFromText(u"{0[text]}".format(content
), "./tweet.mp3")
# get the url needed to open the twitter user
stream, including signature after authentication
def getTwitterUserStreamURL():
STREAM_URL = "https://userstream.twitter.com/2/
user.json"
access_token =
Token(ACCESS_TOKEN,ACCESS_TOKEN_SECRET)
consumer = Token(CONSUMER_KEY,CONSUMER_SECRET)
179
parameters = {
'oauth_consumer_key': CONSUMER_KEY,
'oauth_token': access_token.key,
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': str(int(time.time())),
'oauth_nonce': access_token._generate_nonce(),
'oauth_version': '1.0',
}
oauth_request =
OAuthRequest.from_token_and_callback(access_token,
http_url=STREAM_URL,
parameters=parameters)
signature_method = OAuthSignatureMethod_HMAC_SHA1()
signature =
signature_method.build_signature(oauth_request,
consumer, access_token)
parameters['oauth_signature'] = signature
data = urllib.urlencode(parameters)
return "%s?%s" % (STREAM_URL,data)
# Run Talking Twitter Client
client =
TalkingTwitterStreamClient(getTwitterUserStreamURL(
))
#some useful debug commands, comment out running
the client and uncomment the command
#get twitter stream url, including oauth signature
#print getTwitterUserStreamURL()
#download a speech file from google
#downloadSpeechFromText("hello, how are you
today", "./downloadedFile.mp3")
#output phrase to audio
#speakSpeechFromText("hello, how are you today")
#start talking twitter client
Tweeting Webcam Pics (Part Tested)
http://www.makeuseof.com/tag/how-to-build-a-raspberry-pi-twitter-bot/
Now let’s make something really useful; we’re going tweet webcam pics. Thankfully, Twython supports
the API function update_status_with_media, which makes things rather simple.
Plug a USB webcam into your device and check if
it’s been recognised with the command:
sudo ls /dev/video*
if you see video0, you’re in luck. I used a
Playstation 3 PSEye cam and it worked just fine
without any additional legwork.
We’re also going to use the pygame libraries to
take a picture
#!/usr/bin/env python
import sys
from twython import Twython
import os
import pygame
import pygame.camera
from pygame.locals import *
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
image = cam.get_image()
pygame.image.save(image,'webcam.jpg')
CONSUMER_KEY = 'jmyBuGoaMKS05x85qFCNRw'
180
Initialise the camera, then call using cam (setup to
use /dev/video0, set res to 640x480)
In short, you’ve initialised the webcam at a
specific resolution (you may need to adjust this
is it’s a really old cam), snapped a picture, and
saved it as a jpg. We’re just going to overwrite the
same webcam.jpg each time the app is run.
Finally, adjust the update_status line to read:
CONSUMER_SECRET
= 'U2Ay9nv0CxdopruNk4DR9aRDyhry98ML7mYMCStdaI'
ACCESS_KEY = '354540970nMZVfXJqTbEP8ddj3jwRNs8UMXlZapZpbxiaLg0v'
ACCESS_SECRET
= 'L9MnMvXLROx76CT9NzjR7PFrtMcIb1U9venQwK1ygY'
photo = open('webcam.jpg','rb')
api =
Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_
SECRET)
api.update_status_with_media(media=photo, status='My
RPi be tweeting images now => ')
photo = open('webcam.jpg','rb')
api.update_status_with_media(media=ph
oto, status='My RPi be tweeting images
now => ')
Similar to the SillyTweeter example, this jus uses
the api to post a picture. Complete code for this
example is here.
- Reading Tweets from a #Tag
http://fuenteabierta.teubi.co/2013/01/controlling-raspberry-pi-via-twitter.html
-Creating a TweetBot
http://www.makeuseof.com/tag/how-to-build-a-raspberry-pi-twitter-bot/
181
Clever Graphics Programming / Shaders (a chance to fix Dremples)
-Setup OpenFramework - http://www.openframeworks.cc/setup/raspberrypi/Raspberry-Pi-GettingStarted.html
Download openFrameworks
You now can download the Linux armv6 version of openFrameworks and uncompress it into a folder. Using
a Shell, The following commands will download openFrameworks and uncompress it into the folder/home/pi/
openFrameworks
1. cd
2. curl -O http://www.openframeworks.cc/versions/v0.8.0/of_v0.8.0_linuxarmv6l_release.tar.gz
3. mkdir openFrameworks
4. tar vxfz of_v0.8.0_linuxarmv6l_release.tar.gz -C openFrameworks --strip-components 1
Compile openFrameworks:
This step will take approximately 1 hour when compiling on the Raspberry Pi, Make sure you didn't skip the
Memory Split step in the above section Configure the Raspberry Pi or it will eventually fail.
Assuming openFrameworks is located at /home/pi/openFrameworks run the following commands to install the
necessary packages and compile openFrameworks.
1. cd /home/pi/openFrameworks/scripts/linux/debian_armv6
2. sudo ./install_dependencies.sh (this will take a while!)
You are now ready to compile openFrameworks!
Before making on a recent build of Raspian use his command before making
1.
sed -i 's/VC_IMAGE_TRANSFORM_T/DISPMANX_TRANSFORM_T/g' /home/pi/openFrameworks/libs/openFrameworks/
app/ofAppEGLWindow.cpp
2. make Release -C /home/pi/openFrameworks/libs/openFrameworksCompiled/project
(but not as long as this!)
Having fun with hte OpenFrameworks.
http://www.creativeapplications.net/tutorials/how-to-use-openframeworks-on-the-raspberrypi-tutorial/
Setup some folder and download some 100+ MB of demo files.
cd /home/pi/openFrameworks/apps/
wget https://github.com/openFrameworks-arm/RaspberryPiGuideCAN/archive/master.zip
unzip master.zip
mv RaspberryPiGuideCAN-master CANApps
Try the Simple Hello World Demo
cd /home/pi/openFrameworks/apps/CANApps/HelloWorld
make
make run
182
Try a smiple shader.
cd /home/pi/openFrameworks/apps/CANApps/ShaderSimple
make
make run
183
SOFTWARE - GAMES
123
A good list of Games that run on the Pi
http://www.raspberryconnect.com/raspbian-packages-list/item/65-raspbian-games
SDL DispManx
This will give you best emulation and graphics blitting around, it’s not a standard version of SDL, but is
enhanced, works with Q3, DGen and SNES (not sure about emulation station though!)
Grab copy of the GitHub git clone git://github.com/vanfanel/SDL12-kms-dispmanx.git
cd SDL<tab>
./autogen.sh
run the MAC_ConfigureDISPMANX.sh script
sudo ./MAC_ConfigureDISPMANX.sh
Edit the Makefile
sudo nano Makefile
and add to CFLAGS)
-I/opt/vc/include/interface/vmcs_host/linux
Finally Make and Install.
sudo make
sudo make install
(Just re-install default libsdl1.2 and everything should be back to normal)
sudo apt-get install --reinstall libsdl1.2debian
184
Q3 Arena on RASP PI (Build)
Compile away (this will take over an hour!)
http://www.raspbian.org/RaspbianQuake3
1. Make sure you're up-to-date:
sudo apt-get update
2.
sudo apt-get dist-upgrade
Reboot.
3. Install required packages:
sudo apt-get install git gcc build-essential libsdl1.2-dev
4. Download the Quake 3 source code:
mkdir ~/src
5.
cd ~/src
git clone https://github.com/raspberrypi/quake3.git
cd quake3
6. Edit build.sh in quake3 directory:
change line 8 to this: ARM_LIBS=/opt/vc/lib
7.
change line 16 to this: INCLUDES="-I/opt/vc/include -I/opt/vc/include/interface/
vcos/pthreads"
comment out line 19:
#CROSS_COMPILE=bcm27088. 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/
release-linux-arm/baseq3:
pak0.pk3, pak1.pk3, pak2.pk3, pak3.pk3, pak4.pk3, pak5.pk3, pak6.pk3, pak7.pk3,
pak8.pk3
i.
ii.
Update your permissions for directFB access:
sudo usermod -a -G video [your_username]
1.
Log out, log back in. This will allow you to run game as non-root. Works with other
directFB/SDL based stuff, too.
11. If you do not intend to keep Quake 3 source code, you may reorganize files as suggested by
this thread on RasPi Forum.
Copy the contents of
/home/src/quake3/build/release-linux-arm/
to
/home/pi/quake3
12. Run ./ioquake3.arm. Shoot things.
Assuming you're still root, start the game with `./ioquake3.arm`. Start a game, run around see how it feels.
Hopefully it all works, and it created the correct directories for you. Navigate to `/root/.q3a/baseq3` and run
Start the game again, and the autoexec.cfg should execute automatically. If you'd like to try the other configs, drop
down the console with the tilde key `~ and type `exec low.cfg` or any of the others.
185
186
Quake 3 Quick Install - School Build
(estimated install time around 5 minutes!)
ensure have apt-get update && apt-get upgrade and upgraded firmware???
cd ~
wget http://www.raspians.com/uploads/quake3.zip
unzip quake3.zip
rm quake3.zip
cd quake3
#This will not work at school as DROPBOX is blocked!!! GRRR.... AMAZING USB AGAIN!
wget http://dl.dropbox.com/u/1816557/Q3%20Demo%20Paks.zip
unzip Q3\ Demo\ Paks.zip
rm Q3\ Demo\ Paks.zip
cd ~
sudo chmod +x /home/pi/quake3/ioquake3.arm
School Build Error solutions
if quake3 bombs out with an error message like 'SDL_Init()' 'Unable to open mouse'. This will effect other
DirectFB applications/games that need a mouse.
Work around either to run with no mouse.
CODE: SELECT ALL
export SDL_NOMOUSE=1
OR fix the permissions so non-root uses can access /dev/input/mice and /dev/input/mouse0 as follows.
Create new file in "/etc/udev/rules.d/99-input.rules"
CODE: SELECT ALL
# file /etc/udev/rules.d/99-input.rules
KERNEL=="mice", NAME="input/%k", MODE="664", GROUP="input"
KERNEL=="mouse*", NAME="input/%k", MODE="664", GROUP="input"
Add a new group and add your user(s) to it (my login is just 'pi')
CODE: SELECT ALL
groupadd input
usermod -a -G input pi
Restart the sound
- Update: If you are getting static try bringing down the console (tilde by default) and
entering "snd_restart" (no quotes) and press enter. It will re-init the sound subsystem and can clear it up in
my build.
187
Sound through headphones
sudo amixer cset numid=3 1
Show FPS in Game
#To show FPS use ~ on the menu and type
cg_drawFPS "1"
Quake 3 Config File Guide
http://www.gamesurge.com/pc/hardware/tweaks/q3atweak.shtml
Full version of Quake 3.
Yes, if you copy pak0.pk3 from your cd to the base3q directory on the Pi, you will unlock the full game providing
you enter the CD key. Multiplayer works a treat! (around 480 MB). Ensure when you copy that you rename /
overwrite the existing pak0.pak3 file, you might need to rename the old one (for backup) and make the other one
lower caps!
Openaren on the Pi (Not via Pi Store)
cd ~
sudo apt-get install openarena
sudo apt-get install libcurl3-gnutls
Q3 - Models, Levels, Maps and Extras
http://ioquake3.org/extras/models/ - Models
http://lvlworld.com/ - Levels
http://www.quakeunity.com - Mod Packs / Skins / Textures etc.
http://www.moddb.com/games/quake-iii-arena - Quake 3 Info.
188
Q3 Console Manual
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)
189
/cg_drawTimer (default: 0)
Will display elapsed game time in the upper right of the screen. (0=off, 1=on)
/cg_gibs (default: 1)
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!
190
Quake 2 on the Pi.
Need a fresh install of Wheezy not Squeeze
//Get the latest build - http://deponie.yamagi.org/quake2/debs/source/ (the tar.gz)
Extract it.
Go get the Quake2 demo (Unzip the EXE, rescue the following files and put onto USB)
ftp://ftp.idsoftware.com/idstuff/quake2/q2-314-demo-x86.exe
- Unzip this file (again, it's a self-extracting zip file).
- Create a new "quake2/" directory with a "baseq2/" sub-directory and put the "pak0.pak" and
the "players/" sub directory, you can find them within the unzipped files (in Install/Data/baseq2/), in
your "baseq2/" directory. No
patching is needed for the demo, in fact it would break it.
Install the following using apt-get install ...
● libsdl1.2-dev
● libvorbis-dev
● libogg-dev
● zlib1g-dev
● libjpeg8-dev
MAKE - Goto the GITHUB, find the updated version, save the RAW over the top - https://github.com/
reefab/yquake2
yq2.cfg - Goto https://github.com/reefab/yquake2 then stuff, again save the RAW in the base2q folder
ready for later.
191
Installing Quake 2 on Pi
Quake 2 - https://github.com/reefab/yquake2/blob/
a07e3a605a9f1765b5950da5271df33653245c6b/README.md
Must run Quake 2 as Root.
cd /home/pi/quake2
./quake2
Quake 2 FIX???
sudo ln -fs /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
sudo ln -fs /opt/vc/lib/libGLESv2.so /usr/lib/libGLESv2.so
sudo ln -fs /opt/vc/lib/libGLESv2.so /usr/lib/libGLESv2.so.2
sudo ln -fs /opt/vc/lib/libGLESv2_static.a /usr/lib/libGLESv2_static.a
sudo ln -fs /opt/vc/lib/libbcm_host.so /usr/lib/libbcm_host.so
sudo ln -fs /opt/vc/lib/libvchiq_arm.a /usr/lib/libvchiq_arm.a
sudo ln -fs /opt/vc/lib/libvchiq_arm.so /usr/lib/libvchiq_arm.so
sudo ln -fs /opt/vc/lib/libvcos.a /usr/lib/libvcos.a
sudo ln -fs /opt/vc/lib/libvcos.so /usr/lib/libvcos.so
OFTEN USE - apt-get update && apt-get dist-upgrade
apt-get install ntpdate
ntpdate uk.pool.ntp.org
arm128_start.elf : 128M ARM, 128M GPU split
arm192_start.elf : 192M ARM, 64M GPU split
arm224_start.elf : 224M ARM, 32M GPU split
192
Installing DOOM 1 / 2
First off, we need to prepare a folder for the source code. I have a folder called Sources in my home
directory where I direct all my source code and compiling related needs. So, let's start by creating one:
cd ~
mkdir Sources
cd Sources
Next, we will download the .tar.gz archive from SourceForge either with Midori or NetSurf or download it
on your computer and use SSH to transfer it to the Sources folder:
sudo wget http://downloads.sourceforge.net/project/chocolate-doom/chocolate-doom/1.7.0/
chocolate-doom-1.7.0.tar.gz
Then unpack it, delete the archive and navigate into the new folder:
tar -xvf chocolate-doom-1.7.0.tar.gz
rm chocolate-doom-1.7.0.tar.gz
cd chocolate-doom-1.7.0
Before we start configuring and compiling, we need to download a pretty huge list of packages, they are
mainly SDL related so they should be useful to you on your next compiling adventures.
sudo apt-get update
sudo apt-get install gcc build-essential libsdl1.2-dev libsdl1.2debian libsdl-image1.2
libsdl-image1.2-dev libsdl-mixer1.2 libsdl-mixer1.2-dev libsdl-net1.2 libsdl-net1.2-dev
timidity
When everything is installed, we can finally run the configuration script
./configure
(NOTE: If this gives you an error, it is most likely due to a part of your compiling masquerade is missing.
Try googling the error and you will most likely find what you need to apt-get in order to fix it.)
Finally, we can start compiling. This will take some time but not nearly as long as Q3A.
make
After compiling finishes, we will install our new binaries with the followning command:
sudo make install
NOTE: You need to run this using sudo or as root, because the installing script copies binaries, icons
and .desktop files to the /usr/share folder. On the bright side, this means that everything gets neatly
embedded in your LXDE menu. Due to the way chocolate-doom is launched this is a bit unneeded, but
we will talk about that later (at least we have the icon).
To configure Chocolate Doom, you need to run the following command from the terminal:
chocolate-setup
This will bring you up a nice DOS-looking window where you can configure our new software. Under
display configuration, you can either choose the full screen, but if you have a Full HD LCD like me, I
reccomend hitting A, disabling "Fix aspect ratio" and then selecting 1280x800, since it tends to be quite
laggy on full 1920x1080. Hit the escape key to return to the original menu. Since there is no joystick
to be configured, we will head right to thekeyboard configuration. If you want controls similar to more
modern FPS games, set Move Forward to W, Move Backward to S, Strafe Left to A, Strafe Right to D
and you can set Turn Left to Q and Turn Right to E or whatever you like and leave Speed On on Shift
and Strafe On on Alt. Press escape to return and you can skip the Mouse configuration, since everything
there is set by default to the "average" levels. You can fiddle around there yourself later. Go to Sound
configuration and make sure Sound Effects is set to Digital and that Music playback is set to Native
MIDI. Once you checked that, return to the main menu and select Save parameters and launch DOOM.
Now, since there are no WAD files yet, the game will not lauch but the settings will be saved.
193
Now, we need to get the WAD files. A little google search will tell you how to *cough* *cough* extract
these files from your original Doom CD. Alternatively, you can use Doom 2, Ultimate Doom, TNT:
Eviluion or Plutonia. Log into your Raspberry Pi through SSH as root (for example using WinSCP)
and make create a folder called doom in /usr/share and put your doom.wad, doom2.wad, tnt.wad or
plutonia.wad. I have tried Strife and Hexen as well, but for some strange reason they don't work for me.
Then you can finally start the game using the terminal with the following command:
chocolate-doom -iwad /usr/share/(name of your file).wad
Congratulations! You have now got Doom running on your Raspberry Pi.
OPTIONAL: Create a WAD-specific launcher
(so you don't have to use the terminal all the time)
Open up LeafPad and type the following text in:
[Desktop Entry]
Name=Doom 1
Exec=chocolate-doom -iwad /usr/share/doom/doom.wad
Icon=chocolate-doom
Type=Application
Comment=Conservative Doom source port. Loaded with a Doom1 WAD.
Categories=Game;ActionGame;
And save it on your desktop as doom1.desktop. The exact name doesn't really matter, since the name
specified inside the file is the one getting displayed. Bang, you got your easy desktop launcher for Doom.
Can you even ask for more? Well... Of course you can. Let me introduce you to the:
OPTIONAL 2: Create a laucher for multiple kinds of Doom
So, let's say you happen to own both Doom 1, Doom 2, and on top of it you also own TNT and Plutonia.
And you don't want to have four different icons. Then let us create a launcher with all these options!
Using a little inspiration from the ever-popular Python Games, we will make ourselves a nice little menu
using Zenity. Open up LeafPad, or, if you have it, Geany and paste the following script there:
#!/bin/sh
RET=0
GAME=$(zenity --list --width=350 --height=250 --radiolist --title="Choose your game" -column "Select" --column="Game" TRUE "Doom 1/Ultimate Doom" FALSE "Doom 2" FALSE "TNT:
Evilution" FALSE "The Plutonia Experiment" )
RET=$?
echo $GAME
if [ "$GAME" = "Doom 1/Ultimate Doom" ]; then
chocolate-doom -iwad /usr/share/doom/doom.wad
elif [ "$GAME" = "Doom 2" ]; then
chocolate-doom -iwad /usr/share/doom/doom2.wad
elif [ "$GAME" = "TNT: Evilution" ]; then
chocolate-doom -iwad /usr/share/doom/tnt.wad
elif [ "$GAME" = "The Plutonia Experiment" ]; then
chocolate-doom -iwad /usr/share/doom/plutonia.wad
else
echo "Cancelled..."
fi
And save it somewhere nice, like your home folder, under the name chocolate-doom-launcher (without
the extension). Open up terminal, navigate to the file you just saved and issue these two commands:
chmod +x chocolate-doom-launcher
sudo cp chocolate-doom-launcher /usr/bin
From now on, you have a new terminal command that brings up a nice little launcher for all your Doom
related business. Now let's turn it into a pretty little icon, shall we? For the last time, open LeafPad or
Geany and create a new file and paste this into it:
194
[Desktop Entry]
Name=Chocolate Doom Launcher
Exec=chocolate-doom-launcher
Icon=chocolate-doom
Type=Application
Comment=One launcher for all Doom realted games.
Categories=Game
And save it on your desktop as chocolate-doom-launcher.desktop. If you want this launcher to appear in
your menu as well, open up terminal for the last time and type in these two commands:
cd ~/Desktop
sudo cp chocolate-doom-launcher.desktop /usr/share/applications
And that's it. You now have a fully working, configured installation of Chocolate Doom 1.7.0 with
working MIDI sound thru Timidity, with a launcher for different games both on your desktop and in your
applications menu. Time to give yourself a pat on the back, and go play some Doom!
Enjoy!
Installing Aliens TC and Aliens Doom 3.0 (AVP) in Chocolate Doom.
Download the appropriate files Aliens TC
http://www.doomworld.com/idgames/index.php?id=5739
Download the appropriate files for Aliens Doom 3
http://www.doomworld.com/idgames/index.php?id=5254
Extract in the WADs folder.
Run Alienst TC using
chocolate-doom -iwad <path>/DOOM.WAD -deh <path>/atcud19.deh -merge <path>/alitcsf.wad -file <path>/alitcsnd.wad
<path>/alitcwad.wad
Run Alens Doom 3 using
chocolate-doom -iwad <path>/DOOM.WAD -deh <path>/ad3.deh -merge <path>/ad3spfl.wad <path>/ad3gfx.wad <path>/
ad3snd.wad <path>/ad3mus.wad <path>/ad3lev.wad
Don’t forget these can be added to the custom doom launcher. (chocolate-doom-launcher) see above,
set the permissions again, and copy to the usr/share/applications
Instructions for LAN play
To play Chocolate Doom on a local area network is straightforward. Start a server in the same way as for Internet
play:
chocolate-doom -server -deathmatch
Other players can then automatically join the server with the -autojoin command line option:
chocolate-doom -autojoin
Installing Minecraft on the Pi.
Grab the Targa Ball.
wget https://s3.amazonaws.com/assets.minecraft.net/pi/minecraft-pi-0.1.1.tar.gz
195
To decompress it: tar -zxvf minecraft-pi-0.1.1.tar.gz
To run it: cd mcpi
Followed by minecraft-pi
Custom Textures Packs
These do work. Try DokuCraft, Legopak or Sphax
(to install these backup the
~/mcpi/data/images folder, then overwrite it with the texture pack. This will overwrite, but should work.
Best done in ‘X’ as you can really see what you’re doing!
Python Scripts for Minecraft.
Easiest way is to clone the scripts GitHub (see GitHub’s worth cloning!)
mkdir /home/pi/mcpi/PythonScripts
sudo git clone https://github.com/brooksc/mcpipy.git
cd mcpipy
sudo mv *.py /home/pi/mcpi/PythonScripts
These can then be run from a seperate command prompt! (just run then as plain python scripts, e.g.
sudo python ~/mcpi/PythonScripts/maze.py
For the clocks etc you have to keep the script running for it to update!
Rendering 3D Models in the Minecraft World
Fromhttp://www.stuffaboutcode.com/
Download and run
You can download the code direct from git-hub, so run minecraft, open/create a world and follow the
instructions:
sudo apt-get install git-core
cd ~
git clone https://github.com/martinohanlon/minecraft-renderObj.git
cd minecraft-renderObj
python minecraft-renderObj.py
By default the renderObj (v1) script will render the manhatten skyline.
v2 will render the Raspberry Pi, V2 works better. To change what is rendered you’ll have to get your
hands dirty!
Lots of models available from here
http://people.sc.fsu.edu/~jburkardt/data/obj/obj.html
196
Making the OBJ Files.
In sketchup get your model sorted (or import one!)
Ensure you have the right plugin installed in the plugins folder
Instructions from here.
1. Get the free version of Google Sketchup and install this plugin (Put it in the plugin folder on your Sketchup
installation folder).
(https://sites.google.com/site/messiaen64/level-importer/ObjExporter.rb?attredirects=0)
2. Make your SketchUp model.
3. Click on the plugins tab and select OBJ Exporter.
4. Click browse to select where your model is going to.
5. Click on Export .Obj File.
6. This can take a while, so be patient.
Copy the obj files across to the Pi using WinSCP or similar.
Running your New 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")
Viewing 3D Meshes on a Pi.
Trying out various options such as PyObjViewer - Doesn’t work well.
wget http://jestermon.weebly.com/uploads/1/6/2/1/1621282/pyobjviewer.zip
Meshlab?
197
List of Minecraft Blocks
http://raspberry-python.blogspot.co.uk/2013/02/minecraft-pi-edition-available.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)
198
Minecraft Twitter (untested)
http://www.stuffaboutcode.com/2013/08/raspberry-pi-minecraft-twitter.html?m=1
Install
Create a twitter app
You need to create a twitter app using your twitter id, you can do this by visiting dev.twitter.com, signing
on, and clicking create app; if you are having problems see a previous blog post of mine, automatically
posting updates to twitter, which has some in-depth instructions.
Install python oauth & pycurl
We need a couple of python modules to get the twitter feed working. If you have never installed python
modules before you are going to need to install the python setup tools module, distribute, see blog post,
python - installing modules, for info on how to do this.
sudo apt-get install git-core
git clone https://github.com/leah/python-oauth.git
cd python-oauth
sudo python setup.py install
sudo apt-get install python-pycurl
Download code
cd ~
git clone https://github.com/martinohanlon/minecraft-twitter.git
cd minecraft-twitter
Update twitter keys
You will need to get the twitter keys you were given when you created your twitter app and put them into
minecraft-twitter.py. Open minecraft-twitter.py and scroll down till you find:
# twitter oauth keys, get yours from dev.twitter.com
CONSUMER_KEY = '#############'
CONSUMER_SECRET = '###############'
ACCESS_TOKEN = '###############
ACCESS_TOKEN_SECRET = '###############'
And replace the hashes with your access keys.
Run
Start up minecraft
python minecraft-twitter.py
Code
Its a bit hacky (as you might expect from a hack weekend), but I've include it for reference below. If you
want to get it running though I would suggest you download it from github using the instructions above.
199
#www.stuffaboutcode.com
#Raspberry Pi, Minecraft Twitter
#import the minecraft.py module from the minecraft directory
import minecraft.minecraft as minecraft
#import minecraft block module
import minecraft.block as block
#import time, so delays can be used
import time
#import oauth for twitter security
from oauth.oauth import OAuthRequest, OAuthSignatureMethod_HMAC_SHA1
from hashlib import md5
#required by twitter stream class
import json, random, math, urllib, urllib2, pycurl
#Letters used in the program, hashes are turned into blocks
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" +
"###" + "\n" +
"# #" + "\n" +
200
"# #" + "\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",
"s":
"###" + "\n" +
201
"#" + "\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":
"###" + "\n" +
" #" + "\n" +
202
"###" + "\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" +
"
" + "\n" +
" # " + "\n",
203
",":
"
" + "\n" +
"
" + "\n" +
"
" + "\n" +
" #" + "\n" +
" # " + "\n",
"/":
" #" + "\n" +
" #" + "\n" +
" # " + "\n" +
"# " + "\n" +
"# " + "\n",
":":
"
" + "\n" +
" # " + "\n" +
"
" + "\n" +
" # " + "\n" +
"
" + "\n",
"@":
"###" + "\n" +
"# #" + "\n" +
"## " + "\n" +
"# " + "\n" +
"###" + "\n",
"'":
" # " + "\n" +
" # " + "\n" +
"
" + "\n" +
"
" + "\n" +
"
" + "\n",
"#":
" # " + "\n" +
"###" + "\n" +
" # " + "\n" +
"###" + "\n" +
" # " + "\n"
}
# twitter oauth keys, get yours from dev.twitter.com
CONSUMER_KEY = '#############'
CONSUMER_SECRET = '###############'
ACCESS_TOKEN = '###############
ACCESS_TOKEN_SECRET = '###############'
# constants to position the text lines in minecraft
LETTERBLOCKID = block.COBBLESTONE.id
LETTERBLOCKDATA = 0
#These are the lines where the tweets will be written
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)]]
}
LINEHEIGHT = 5
LETTERWIDTH = 3
204
#Class for creating text in minecraft
class MinecraftText:
def __init__(self, mc):
self.mc = mc
self.currentLine = 0
self.currentTopLeft = LINETOPLEFTS[self.currentLine]
#writes a line to minecraft at the next position
def writeNextLine(self, line):
#Output message
self.clearLine(self.currentLine)
self.writeLineToMC(line, self.currentLine)
self.currentLine+=1
#if I have reached the top line, reset it
if self.currentLine == 4: self.currentLine = 0
#writes a line of text into minecraft
def writeLineToMC(self, line, lineNumber):
#get the textlines
textlines = TEXTLINES[lineNumber]
#current testline
currentTextLine = 0
#set the cursor position
currentCursor = minecraft.Vec3(textlines[currentTextLine][0].x,
textlines[currentTextLine][0].y,
textlines[currentTextLine][0].z)
#setup x and z directions
xDirection, zDirection = 1, 0
nextTextLine = False
#make line lower case
line = line.lower()
#write the line to minecraft
for character in line:
#create the character in minecraft
self.writeLetterToMC(character, currentCursor, xDirection, zDirection)
#move the 'cursor' on
# check if the current cursor pos is outside the textLine,
# if so move to the next text line
if currentTextLine == 0:
currentCursor.x = currentCursor.x + LETTERWIDTH + 1
if currentCursor.x > textlines[currentTextLine][1].x: nextTextLine = True
if currentTextLine == 1:
currentCursor.z = currentCursor.z + LETTERWIDTH + 14
if currentCursor.z > textlines[currentTextLine][1].z:
nextTextLine = True
if currentTextLine == 2:
currentCursor.x = currentCursor.x - LETTERWIDTH + 14
if currentCursor.x < textlines[currentTextLine][1].x: nextTextLine = True
if currentTextLine == 3:
currentCursor.z = currentCursor.z - LETTERWIDTH + 14
#if currentCursor.z < textlines[currentTextLine][1].z: nextTextLine = True
if nextTextLine == True:
nextTextLine = False
#next testline
currentTextLine+=1
#set the cursor position
currentCursor = minecraft.Vec3(textlines[currentTextLine][0].x,
textlines[currentTextLine][0].y,
textlines[currentTextLine][0].z)
#setup x and z diections
if currentTextLine == 1: xDirection, zDirection = 0, 1
if currentTextLine == 2: xDirection, zDirection = -1, 0
205
if currentTextLine == 3: xDirection, zDirection = 0, -1
#create a letter in minecraft
def writeLetterToMC(self, character, cursorTopLeft, xDirection, zDirection):
# the current position is where we have reached in creating the letter
currentPos = minecraft.Vec3(cursorTopLeft.x, cursorTopLeft.y, cursorTopLeft.z)
# is the character in my letter list?
if (character in letters.keys()):
# get the hashes for the character
letterString = letters[character]
#loop through all the hashes, creating block
for digit in letterString:
if digit == "#":
#print "create block x = " + str(currentPos.x) + " y = " + str(currentPos.y)
self.mc.setBlock(currentPos.x, currentPos.y, currentPos.z, LETTERBLOCKID, LETTERBLOCKDATA)
currentPos.x = currentPos.x + xDirection
currentPos.z = currentPos.z + zDirection
if digit == " ":
self.mc.setBlock(currentPos.x, currentPos.y, currentPos.z, block.AIR.id)
currentPos.x = currentPos.x + xDirection
currentPos.z = currentPos.z + zDirection
if digit == "\n":
currentPos.y = currentPos.y - 1
currentPos.x = cursorTopLeft.x
currentPos.z = cursorTopLeft.z
#clears a line of text in minecraft
def clearLine(self, lineNumber):
for textline in TEXTLINES[lineNumber]:
self.mc.setBlocks(textline[0].x,
textline[0].y,
textline[0].z,
textline[1].x,
textline[1].y - LINEHEIGHT,
textline[1].z,
block.AIR.id)
# class for managing oauth tokens
class Token(object):
def __init__(self,key,secret):
self.key = key
self.secret = secret
def _generate_nonce(self):
random_number = ''.join(str(random.randint(0, 9)) for i in range(40))
m = md5(str(time.time()) + str(random_number))
return m.hexdigest()
# twitter client
class MinecraftTwitterStreamClient:
def __init__(self, streamURL):
#Connect to minecraft by creating the minecraft object
# - minecraft needs to be running and in a game
self.mc = minecraft.Minecraft.create()
#Post a message to the minecraft chat window
self.mc.postToChat("Minecraft twitter stream active")
#create my minecraft text screen object
self.mcText = MinecraftText(self.mc)
#setup connection to twitter stream
self.streamURL = streamURL
self.buffer = ""
self.conn = pycurl.Curl()
206
self.conn.setopt(pycurl.URL, self.streamURL)
self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
self.conn.perform()
#this method is called each time some data arrives on the stream
def on_receive(self, data):
# debug - to see when this is called sys.stdout.write(".")
self.buffer += data
if data.endswith("\n") and self.buffer.strip():
content = json.loads(self.buffer)
self.buffer = ""
#debug - output json from buffer print content
#friends data - store for later
if "friends" in content:
self.friends = content["friends"]
#text (tweet) arrives
if "text" in content:
print u"{0[user][name]}: {0[text]}".format(content).encode('utf-8')
tweet = u"{0[user][name]}: {0[text]}".format(content).encode('utf-8')
self.mcText.writeNextLine(tweet)
# get the url needed to open the twitter user stream, including signature after authentication
def getTwitterUserStreamURL():
STREAM_URL = "https://userstream.twitter.com/2/user.json"
access_token = Token(ACCESS_TOKEN,ACCESS_TOKEN_SECRET)
consumer = Token(CONSUMER_KEY,CONSUMER_SECRET)
parameters = {
'oauth_consumer_key': CONSUMER_KEY,
'oauth_token': access_token.key,
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': str(int(time.time())),
'oauth_nonce': access_token._generate_nonce(),
'oauth_version': '1.0',
}
oauth_request = OAuthRequest.from_token_and_callback(access_token,
http_url=STREAM_URL,
parameters=parameters)
signature_method = OAuthSignatureMethod_HMAC_SHA1()
signature = signature_method.build_signature(oauth_request, consumer, access_token)
parameters['oauth_signature'] = signature
data = urllib.urlencode(parameters)
return "%s?%s" % (STREAM_URL,data)
if __name__ == "__main__":
#Create minecraft twitter
mcTwitter = MinecraftTwitterStreamClient(getTwitterUserStreamURL())
Installing Descent on the Pi (untested)
http://blog.sheasilverman.com/2012/08/descent-tutorial/
207
1. Install the required dependancies
1. sudo apt-get install libsdl1.2debian libsdl-mixer1.2 libsdl-mixer1.2dev libsdl-image1.2 libsdl-image1.2-dev libsdl-ttf2.0-0 libsdlttf2.0-dev libsdl-net1.2 libsdl-net1.2-dev gcc-4.7 scons libphysfsdev
cd ~/
mkdir descent
cd descent
Download the needed source code:
1. wget http://sourceforge.net/projects/dxx-rebirth/files/dxx-rebirth/
0.57.3/d1x-rebirth_v0.57.3-src.tar.gz
2. wget http://sourceforge.net/projects/dxx-rebirth/files/dxx-rebirth/
0.57.3/d2x-rebirth_v0.57.3-src.tar.gz
6. Download the needed patches:
1. wget http://www-user.tu-chemnitz.de/~heinm/tmp/d1x-rebirthrpi.diff.gz
2. wget http://www-user.tu-chemnitz.de/~heinm/tmp/d2x-rebirthrpi.diff.gz
7. Unzip the source files and the patches:
1. tar xvfz d2x-rebirth_v0.57.3-src.tar.gz
2. tar xvfz d1x-rebirth_v0.57.3-src.tar.gz
3. gunzip d1x-rebirth-rpi.diff.gz
4. gunzip d2x-rebirth-rpi.diff.gz
8. You now have to patch the source code with the diff files.
1. cd into the source code directories.
1. Descent 1
1. cd ~/descent/d1x-rebirth_v0.57.3-src/
2. patch -p1 < ../d1x-rebirth-rpi.diff
Descent
2
2.
1. cd ~/descent/d2x-rebirth_v0.57.3-src/
2. patch -p1 < ../d2x-rebirth-rpi.diff
9. We are now ready to compile!
10. On the command line enter these two commands:
1. export CC=gcc-4.7
2. export CXX=g++-4.7
11. Descent 1
1. cd ~/descent/d1x-rebirth_v0.57.3-src/
2. scons raspberrypi=1
1. Wait around 30 – 40 minutes.
2. If there are no errors you should now have a d1x-rebirth
executable file in your directory!
12. Descent 2
1. cd ~/descent/d2x-rebirth_v0.57.3-src/
2. scons raspberrypi=1
1. Wait around 30 – 40 minutes.
2. If there are no errors you should now have a d2x-rebirth
executable file in your directory!
13. You now need the data files that holds the actual game levels, sounds, artwork,
etc. These are in .hog, .pig, and .ham (descent 2 only) files. You can get the
game content from dxx-rebirth, the creators of this port. They also have links
to the shareware files:
1. http://www.dxx-rebirth.com/game-content/
2. http://www.dxx-rebirth.com/download/dxx/content/descent-pcshareware.zip
3. http://www.dxx-rebirth.com/download/dxx/content/descent2-pc-demo.zip
14. Unzip those files by running unzip filename
15. copy descent.hog and descent.pig to ~/descent/d1x-rebirth_v0.57.3-src/
16. copy D2DEMO.HAM, D2DEMO.HOG and D2DEMO.PIG to ~/descent/d2x-rebirth_v0.57.3-src/
17. You are now ready to play!
1. Descent 1
1. cd ~/descent/d1x-rebirth_v0.57.3-src/
2.
3.
4.
5.
208
2. ./d1x-rebirth -hogdir . (yes, thats a period at the end
that must be there)
2. Descent 2
1. cd ~/descent/d2x-rebirth_v0.57.3-src/
2. ./d2x-rebirth -hogdir .
18. ENJOY!!
I realize these are a lot of instructions, but I wanted to make them as verbose as possible.
Below are the precompiled binaries with shareware data files already copied over.
Descent 1 Binaries | Descent 2 Binaries
209
SOFTWARE - Games Emulation 148
http://storyhub.actionaid.org/forum/viewtopic.php?
f=78&t=54357&sid=0d6a44bb92801dc8aa760b11b68f60e1 - Raspberry Pi Main Emulation Thread.
A Note about ROMS
Here’s a quick note about ROMs. ROMs are virtual disk images (Generally of old console / computer
games). Now many old companies might argue that ROMs aren’t legal. Espeically if you don’t own
the original of the game! Yet for some it makes perfects sense, having a copy of a game they bought
years ago to play on new hardware. When Sonic 2 was first released it cost £45 (that’s around £65
with inflation)!!! which is bonkers expensive. However greedy companies love churning out games
collections for modern consoles and charging hansomely for them, probably many of the emulators on
the consoles will be using other peoples work and benefitting from it. (N.B. You’ll notice you can’t get
a decent emulator on an iPhone/iPad/iPod due to the closed architecture and nature of the app store,
unless you jailbreak, sad really!)
So is it legal to download Gensis (Megadrive), SNES or NES roms from sites like Coolroms,
emuparadise or Romination? No, but it’s a somewhat grey area!
I’d also like to take another view on this, bear with me if you will. Who’s archiving and backing up our
illustrious games herritage? These games defined generations and are etched into our history. But
games are being lost... why? Because no-one cares? Or no one is able to archive entire collections?
Copyright restrictions? Take a look on any major torrent tracking site for ‘Console XYZ collection’ and
you’ll find EVERY game ever released on that console (multiple versions from multiple countries),
immortalised for posterity! These games have been painstakingly collected, categorized and bundled for
your convenience, designed to be easily shared! Why, lest we forget.
Should I encourage you to go and find these games? Dunno. I will perhaps demonstrate Sonic 2
running from an original cartridge on a Megadrive 2, I’ll then show the same game running on Pi
through emulation! There are a ton of lessons to be learnt here, Filesizes, Compression, Emulation,
Virtualisation etc. I will also mention some noteworthy characters and some of my other faves. Will I
encourage kids to go and find out more about these games? Of course! Perhaps it will get a few more
parents involved with a conversation over the dinner table. Current copyright laws are archaic and
desperately need updating! Many of these games will have slipped out of copyright, others will have not.
There was a time when Sonic and Mario would not be seen dead with each other. Imagine Sony and
Microsoft releasing a game together, crazy. But times change.
Handle, with care, use at your own risk. If you like it, buy it (that is if you can even source an original
copy!) RANT OVER.
<< Click on images for Links.>>
210
Ultra Slim - Cheat (Precompiled with XBMC!)
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=78&t=59590
Misc info:
Samba is installed and user pi's home directory is shared. Makes copying rom's or other large files a breeze.
Lirc (remote support) is installed and enabled. Just copy your lircd.conf to /etc/lirc.
SSH = pi/raspberry
You can put your own scripts in ~/Roms/apps/ and it will show in EmulationStation.
Key location/files:
● Roms location = ~/Roms/
●
Retroarch main config = ~/Emulators/Retroarch/retroarch.cfg
●
Retroarch core configs = ~/Emulators/Retroarch/configs/[emu]/retroarch.cfg
●
emulationstation config = ~/.emulationstation/es_systems.cfg
●
emulationstation mappings = ~/.emulationstation/es_input.cfg
How to update XBMC or switch to Gotham:
I might release updates to xbmc every now and again. I build the updates myself on my pc and upload to dropbox.
Frodo is installed by default. Gotham is alpha and under heavy developement. You have been warned. But has
several speed patches for a better xbmc experience on raspberry pi. The source I am currently using is here for
frodo and here for Gotham. Do not try to run the command via sudo it will not work. The script will backup your
current xbmc in opt just incase something goes wrong. There is no error checking, it's just a simple script. So
proceed at your own risk.
1: Download: Frodo (last updated 01/15/14) or Gotham (last updated 12/03)
2: Copy that file to your home directory (/home/pi)
3: Run the commands below.
CODE: SELECT ALL
sudo su
updatexbmc
sudo apt-get install libxslt1.1
211
RetroArch (Own Build!)
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=78&t=56070
Initial Setup
sudo apt-get install libasound2-dev git-core
mkdir ~/retro
git clone git://github.com/libretro/RetroArch.git
cd RetroArch
./configure --disable-x11 --disable-oss --disable-pulse --disable-sdl --enable-floathard
make
mv retroarch ~/retro
Install the Individual Game System Engines
Now, let's go for some emulation libraries. What about a fullspeed MegaDrive + MegaCD emulator running
fullscreen at a constant and solid 60FPS with NO TEARING and smooooooth scroll as in real hardware? (My Pi is
running at 950 MHz)
PicoDrive (Working)
1) We clone the repo:
git clone https://github.com/libretro/picodrive.git
cd Picodrive
2)We make some adjustments to the sources:
git submodule init && git submodule update
3)We configure the sources.
./configure
4)We build them:
make -f Makefile.libretro platform=armv6e
We will get a file called picodrive_libretro.so. That's our sega emulation library
We move it to the same directory where RetroArch is:
mv picodrive_libretro.so ~/retro
TESTING
cd ~/retro
./retroarch -L picodrive_libretro.so sega/Sonic.md
RetroPie - Emcompassing Most Emulators.
212
This will take a while to build if you compile your own! (you could just use latest Binaries, not tested!)
(THIS REQUIRES AROUND 700 MB!)
git clone --depth=0 git://github.com/petrockblog/RetroPie-Setup.git
#git clone https://github.com/petrockblog/RetroPie-Setup
cd RetroPie-Setup
run
sudo apt-get install dialog -y
chmod +x retropie_setup.sh
sudo ./retropie_setup.sh
If just wanting to install PicoDrive (superior to DGen) then from the setup just do… (didn’t
work for me!)
Run RetroPie setup:
cd RetroPie-Setup
sudo ./retropie_setup.sh
Option 4 “Update RetroPie setup script”
restart RetroPie setup
Option 2 “Source based installation”
Then deselect all apart from :
10 Generate Folder Structure
11 Install RetroArch
34(36) install Genesis core Picodrive
59 Install Emulation Station
61 Install ES-Config
57(62) generate config file for emulation station
63 Configure Sound Settings
Press ok and when done reboot.
Also if you want to add .bin support:
sudo nano /home/pi/.emulationstation/es_systems.cfg
Navigate to the Megadrive/Genesis section and add .bin & .BIN after .smd .SMD and .bin files will now be picked up.
Choose ‘Source Based Installation’, this will take longer, but will give better results!
To setup the system (which emulators etc) edit the following file.
sudo nano ~/.emulationstation/es_systems.cfg
Then check out the config files for controls / details etc.
sudo nano ~/RetroPie/config/all/retroarch.cfg
set audio_out_rate = 44100
213
Enusure that if trying to run a playstation emulator you need to edit the es_systems.cfg to read BIN file
(both .bin and .BIN as img seems not to work!)
RetroArch-Phoenix or retroarch-joyconfig ???
input_player1_a = 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/retropie-downloads/
retroarch -L /home/root/RetroPie/emulatorcores/Genesis-Plus-GX/libretro.so /home/root/
RetroPie/roms/megadrive/SONIC_CMP.smd
RetroPie - XBox Pad
(Guide from here)
Following this, edit /etc/rc.local, adding (before anything else)
xboxdrv --trigger-as-button --id 0 --led 2 --deadzone 4000 --silent & sleep 1
This ensures that the driver launches when the computer boots. Note the use of “–wid” in the instruction,
which is for wireless controllers. Change it to –id for wired controllers.
Following this, enter
cd ~/RetroPie/emulators/RetroArch/tools
While in this directory, input the following command:
./retroarch-joyconfig -o p1.cfg -p 1 -j 0
You should increase digits by factor of 1 for each additional controller. If entered correctly, the resulting
files should be added to retroarch.cfg:
sudo cat p*.cfg >> ~/RetroPie/configs/all/retroarch.cfg
You can then save and reboot to use your Xbox 360 controller.
214
RetroPie - Exit Games Using Your Controllers
The default method for exiting a game in EmulationStation is by restarting your Raspberry Pi –
something that can corrupt the SD card as this is only possible in this scenario by removing the power
cable.
To overcome this, a workaround exists maps an exit option to your game controller.
You’ll need to edit the retroarch.cfg file to do this, adding the following code:
input_enable_hotkey_btn = "X"
input_exit_emulator_btn = "Y"
You will need to check the retroarch.cfg file to identify the buttons you want to use here. Obviously you
don’t want to exit games using the usual controller buttons – instead, you should be looking for the ones
that relate to the buttons in the centre of the controller, perhaps labelled “menu” or “start”.
RetroPie - Installing ROMs
Hopefully you have setup the folders to install the ROMs using SAMBA SHARES from the setup script.
If not you can still use MobaXTerm (then on the left navigate to /home/pi/RetroPie/roms/
and you will find a folder for each emulator. Put the correct roms in the correct folders!
215
MAME
NES
http://www.youtube.com/
watchv=7_lbCaBUwhc&feature=bf_next&list=PLN4WWy3UrTHT02MuTtn9Q_WZxsXhk2ne7
Snes Emulator - SNES9x
https://github.com/ToadKing/RetroArch-Rpi
Snes9x
There are 2 choice V1.39 (with oss sound) - here
or 1.53 (SNES SDL - with lots of frameskip!) - here
Version 1.39
Some requirements.
sudo apt-get install libsdl-ttf2.0-dev libboost1.50-all-dev
cd ~
mkdir SNES
cd SNES
git clone https://github.com/chep/snes9x-rpi
cd snes9x-rpi
make
sudo make install
ConfJoy tool is replaced by confTool which configures keyboard too. Start it in its
directory, it will create input.config in snes directory (..). Its first argument is the number
of players who will use the keyboard. Use 0 (zero) if you have no keyboard.
ScummVM
http://www.raspberrypi.org/phpBB3//viewtopic.php?f=35&t=10692
PicoDrive
216
DGen (Tested)
(time to install - around 1 hr for SDL and another for DGen.)
Need to install SDL Latest version ???
You will also need SDL (SDL version 1.2.15 as of this post) fromhttp://www.libsdl.org/download-1.2.php.
DGen Manual.
http://www.rjanick.com/2012/10/29/dgen-on-the-raspberry-pi/
http://dgen.sourceforge.net/
DGen Build Instructions
Install this so you can run ROMS from Zips sudo apt-get install libarchive-dev
cd ~
wget http://www.libsdl.org/release/SDL-1.2.15.tar.gz
tar -xvf SDL-1.2.15.tar.gz
cd SDL-1.2.15
./configure
sudo make
sudo make install
cd ~
wget http://sourceforge.net/projects/dgen/files/dgen/1.32/dgen-sdl-1.32.tar.gz
tar -xvf dgen<tab
rm dgen-sdl-1.32.tar.gz
cd dgen<tab>
sudo ./configure
sudo make
sudo make install
If not work try using
make install clean
Set your memory split to 128 on 512 pi, 0 on a 256
Finall run DGen using this for fullscreen.
dgen -g 0 <filename> -f
Or this when running on smaller screens!
dgen -g 0 <filename> -G 320x240
To run PAL games use the ‘-p’ option (Xenon2 requires this!)
Also try -g 0/1 to turn on/off OpenGL.
217
Tweaking DGen
FILES
$HOME/.dgen/dgenrc
Contains user settings for the emulator.
$HOME/.dgen/dgenrc.auto Generated file containing saved user settings.
$HOME/.dgen/saves/*
Save states generated by the emulator.
$HOME/.dgen/ram/*
Battery-backup RAM images, generated by the
emulator for ROMs with save RAM.
$HOME/.dgen/screenshots/*
Screenshots are generated there.
$HOME/.dgen/roms/*
ROMs default search path.
$HOME/.dgen/demos/*
Demos default search path.
Edit settings
sudo nano /home/pi/.dgen/dgenrc.auto
The newest git version of dgen (and I think the newest release 1.32 version) includes ASM optimized emulators for
the m68k and z80... make sure you enable them =). You must edit the dgenrc.5 file and set the following
emu_z80_startup = drz80
emu_m68k_startup = cyclone
The defaults are cz80 and musa, and they are not optimized for the arm platform.
Sonic Level Select
http://info.sonicretro.org/Sonic_hacks
DGen CONTROLS
GAME PAD:
Directional Control - Cursor Keys
Button “A” - A
Button “B” - S
Button “C” - D
Reset TAB
Start - Enter
Exit - Esc
F2 - SAVE in SLOT
F3 - LOAD SLOT
F5 - Toggles “TV Modes”: blur, scanline, interlace, swab, off
F6 - Toggles “Scale” Modes: hqx, scale2x, default (NONE)
For a FULL description of the Controls and Options see Here - http://dgen.sourceforge.net/
Using ta conrol pad (if it appears as /dev/js0)
sudo nano /home/pi/.dgen/dgenrc
Add the following lines for standard joystick.
joy_pad1_up [joystick0-axis1-min]
joy_pad1_down [joystick0-axis1-max]
joy_pad1_left [joystick0-axis0-min]
joy_pad1_right [joystick0-axis0-max]
218
joy_pad1_a [joystick0-button0]
joy_pad1_b [joystick0-button3]
joy_pad1_c [joystick0-button1]
joy_pad1_x [joystick0-button6]
joy_pad1_y [joystick0-button4]
bool_joystick [true]
Create a script for the XBox Pad
(Save in the XBox Folder, assuming you’ve installed and read the Xboxdrv section of
this manual!)
#save as dgen_config
[xboxdrv]
silent=true
deadzone=6000
dpad-as-button=true
trigger-as-button=true
[ui-axismap]
#Map the Right stick as Nothing.
#Map the left stick as keys
x1=KEY_LEFT:KEY_RIGHT
y1=KEY_UP:KEY_DOWN
#Map the 4 coloured buttons
[ui-buttonmap]
a=KEY_S
b=KEY_A
x=KEY_Q
y=KEY_D
#Map the Bumper Buttons
[ui-buttonmap]
lb=KEY_F2
rb=KEY_F3
#Map the Triggers.
[ui-buttonmap]
lt=KEY_W
#rt=KEY_F2
#Map the D-PAD
[ui-buttonmap]
dl=KEY_LEFT
dr=KEY_RIGHT
du=KEY_UP
dd=KEY_DOWN
[ui-buttonmap]
back=KEY_ESC
start=KEY_ENTER
GUIDE=KEY_TAB #REST GENESIS
To call the config use (with the & to run in the bg!)
sudo xboxdrv --config /home/pi/Xbox/dgen_config&
219
220
Mupen64 - RPi
TO BUILD/RUN
Hardware - Mupen64plus-Rpi will build on a 512 or 256MEG Raspberry Pi, if you have a 256MEG variety make
sure you have the RAM split attributing a MAXIMUM of 64MEG to the GPU (use the config (sudo raspi-config))
Operating System - Raspbian Wheezy
Over Clock - Due to the processing power required it is advised to run Mupen64plus-Rpi with the fastest Over
Clock that is stable on your System (use the config (sudo raspi-config))
Dependencies Required - SDL1.2-dev
Additional Files Required - Game ROMS
RAM Split - At least 64MEG to the GPU
Build Time - Approximately 45 minutes to 1 Hour depending on overclock
Install the required dependancies
sudo apt-get install libsdl1.2-dev
Download the source code from Github (on the right you will see a Cloud symbol with Download ZIP, that's the link
for the master folder) and extract (uncompress).
Download Link - https://github.com/ricrpi/mupen64plus-rpi
CD into the folder and run the build script
./m64p_build.sh
Once completed add some ROMs and extract them to an appropriate folder (I called mine n64roms),
then CD into the test folder mupen64plus-rpi-master/test (where the executable and plugins are located ) and run
the program along with the name and location of the ROM
e.g. ./mupen64plus /home/pi/n64roms/mario.n64 (you can change the file name for easy typing)
CONFIGURATION FILE SETTINGS
The cfg file is located at /home/pi
.confg (Hidden Folder)
mupen64plus/mupen64plus.cfg
Basic changes are identified below, If you are familiar with emulator cfg files feel free to experiment with other
settings and report your findings (this will assist with emulator development).
[Video-General]
# Width of output window or fullscreen width
ScreenWidth = (Default: 640)
# Height of output window or fullscreen height
ScreenHeight = (Default: 480)
Change values to alter output resolution, 320x240 is the original hardware res (in most cases), and up to 1024x768
has a minimal impact on performance (1-2% when running from Console)
[Video-Rice]
# Control when the screen will be updated (0=ROM default, 1=VI origin update, 2=VI origin change, 3=CI change,
4=first CI change, 5=first primitive draw, 6=before screen clear, 7=after screen drawn)
ScreenUpdateSetting = (Default: 6)
Change value to alter screen update, can influence correct game performance (a setting of 4 will allow Star Fox 64
to render correctly and PilotWings 64 to display for example)
# Force to use texture filtering or not (0=auto: n64 choose, 1=force no filtering, 2=force filtering)
ForceTextureFilter = (Default: 1)
Change value to enable filtering, smooth’s textures with minimal impact on performance
# Force to use normal alpha blender
NormalAlphaBlender = (Default: False)
221
Change to True fixes some games so environments display correctly
e.g.
Turok Dinosaur Hunter
# If this option is enabled, the plugin will skip every other frame
SkipFrame = (Default:True)
Change to False fixes some games in conjunction with ScreenUpdateSetting, however, due to every frame being
displayed slows emulation
e.g.
Goldeneye 64
The Legend of Zelda: Majora’s Mask
Set ScreenUpdateSetting=1, SkipFrame = False
Enjoy!
222
SOFTWARE Projects
154
SiriProxy - As User
From Here
Before we start, I’d recommend getting tmux, but feel free to skip. You’ll need this (or something similar),
if you plan to start the SiriProxy server in the foreground (so you can see the output) and disconnect the
terminal session (without backgrounding the server). This will let you disconnect, reconnect without the
server stopping. This install process contains one very long step and I’d recommend running this with
tmux in case you get disconnected. It also lets you run several terminal session with a single telnet/ssh
login.
sudo apt-get install tmux
I’m also going to create a user called “pi”
sudo adduser pi
SiriProxy Install
1. Install everything needed for Ruby, RVM, git, etc.
sudo apt-get install dnsmasq ruby build-essential openssl libreadline6 libreadline6-dev
curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3
libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion
Select ‘y’ to continue.
2. Edit DNS
(You can skip this if your router or other DNS can handle it. See “DNS” below)
sudo nano /etc/dnsmasq.conf
Find the line starting with: #address=/double-click.net/127.0.0.1 (use Ctrl-W to search)
Add a new line redirecting the Apple’s Siri server to your local IP (from ifconfig)
address=/guzzoni.apple.com/192.168.168.63
Save and exit (Ctrl-O, Enter, Ctrl-X)
223
restart dnsmasq
sudo /etc/init.d/dnsmasq restart
Test DNS is resolving correctly
ping guzzoni.apple.com
Type Ctrl-C as soon as you see an ip address (almost immediately)
This should return Apple’s IP address (I got 17.174.8.16). Apple blocks ICMP, so the pings will timeout
just make sure it resolves into a 17.x.y.z address.
3. Install RVM
bash < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer)
Don’t worry about the warning in red, the next two commands take care of it
Load RVM as a function and update profile
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"
echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM
function' >> ~/.bash_profile
(I’d recommend using tmux for this bit)
rvm install 1.9.3
You might have to run
rvm autolibs enable
Which tells the ruby install to grab the bits it needs!
Don’t worry about this message:
No binary rubies available for: debian/wheezy_sid/armv6l/ruby-1.9.3-p374.
answer “Y” to all prompts (takes over an hour to run on the Raspberry)
If you get the following error, it’s likely that you ran out of disk space (run “df –k” to check).
Error running 'make', please read /home/pi/.rvm/log/ruby-1.9.3-p374/make.log
There has been an error while running make. Halting the installation.
Set Ruby 1.9.3 as default
rvm use 1.9.3 --default
4. Install the SiriProxy
git clone git://github.com/plamoni/SiriProxy.git
cd SiriProxy
Select 'y' to warning to continue.
mkdir ~/.siriproxy
cp ~/SiriProxy/config.example.yml ~/.siriproxy/config.yml
rake install
Takes a while too. (if this doesn’t take a while, follow the error output and run
gem install /home/pi/SiriProxy/pkg/siriproxy-0.5.3.gem
5. Generate Certificates
224
siriproxy gencerts
6. Install the Certificate on your iPhone
You can use any mechanism to get it to the iphone. As I’m using TerraTerm, I just used SSH SCP (File
menu -> SSH SCP…)
Another great alternative (if you’ll be doing a lot of editing on your local machine) is WinSCP:
E-mail the certificate yourself, click it and install on phone (ignore warning about it being untrusted)
7. Bundle
Set a few things in the environment first and create a symbolic link so that rvmsudo works.
echo 'export rvmsudo_secure_path=1 ' >> ~/.bash_profile
source ~/.bash_profile
sudo ln -s ~/.siriproxy /root/.siriproxy
rvmsudo siriproxy bundle
8. Start the server
rvmsudo siriproxy server
A message should appear saying something like:
225
Starting SiriProxy on 0.0.0.0:443..
SiriProxy up and running.
9. Set DNS server on phone
The last step is to point your iPhone at your DNS server. This will be the PI’s IP unless you are using an
external DNS server.
1. Got to Settings -> Wi-Fi
2. Click the blue arrow next to your connection
3. Enter the Linux VM's IP
226
10. Test
Note: with the current versions you will highly likely receive an InvalidByteSequence error. Don’t
panic.See InvalidByteSequence below. Other errors, and solutions, can be found in Part 1
Try it anyway
Press and hold the home button.
Say the exact phrase “Test Siri Proxy”. It should respond with exactly “Siri Proxy is up and running” and
you should see something like this:
Create server for iPhone connection
start conn #, @zip_stream=#, @consumed_ace=false, @name="iPhone",
@ssled=false>
[Info - Plugin Manager] Plugins laoded: [#>]
[Info - iPhone] Received Object: LoadAssistant
[Info - iPhone] Received Object: SetRestrictions
[Info - iPhone] Received Object: SetRestrictions
[Info - iPhone] Received Object: ClearContext
[Info - iPhone] Received Object: SetSessionObjects
[Info - Guzzoni] Received Object: AssistantLoaded
[Info - iPhone] Received Object: StartSpeechRequest
[Info - iPhone] Received Object: SetRequestOrigin
[Info - User Location] lat: XX.07408038900973, long: -YY.70323611215576
[Info - iPhone] Received Object: SpeechPacket
[Info - Guzzoni] Received Object: SetConnectionHeader
227
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
[Info
-
iPhone] Received Object: SpeechPacket
iPhone] Received Object: SpeechPacket
iPhone] Received Object: SpeechPacket
iPhone] Received Object: SpeechPacket
iPhone] Received Object: SpeechPacket
iPhone] Received Object: SpeechPacket
iPhone] Received Object: SpeechPacket
iPhone] Received Object: SpeechPacket
iPhone] Received Object: SpeechPacket
iPhone] Received Object: SpeechPacket
iPhone] Received Object: FinishSpeech
Guzzoni] Received Object: SpeechRecognized
Plugin Manager] Processing 'Test Siri proxy '
Plugin Manager] Processing plugin #
Plugin Manager] Matches (?i-mx:test siri proxy)
Plugin Manager] Applicable states:
Plugin Manager] Current state:
Plugin Manager] Matches, executing block
Plugin Manager] Say: Siri Proxy is up and running!
Plugin Manager] Sending Request Completed
Siri Proxy Plugins
Generally visit the GitHub,
Goto the ~/SiriProxy/Plugins Folder
Do a git clone <git>
see what’s in the config-info.yml (copy the install bit) - ignore this and just make the path equal so it can
find the config-info.yml
and paste in the general file below.
sudo nano ~/.siriproxy/config.yml
run rvmsudo sirproxy bundle
run rmvsudo bundles install
Finally rvmsudo siriproxy server (and it should ALL be working!)
Magic8Ball - https://github.com/Ponyboy47/siriproxy-magic8ball
Siri-IMDB - https://github.com/mattparmett/SiriProxy-SiriIMDB
Sir-FoulLanguage - https://github.com/coden00b/SiriProxy-FoulLanguage
Adding your own Siri Commands
Edit this file.
sudo nano ~/SiriProxy/plugins/siriproxy-example/lib/siriproxy-example.rb
find the ‘listen_for’, add your own commands. They must be aligned and the colours MUST match up!
listen_for /what time is it/i do
say "It's Hammer Time." #Say something to the user!
request_completed #always complete your request!
end
228
You can add commands to be run using the ‘puts %x { }’command.
listen_for /Quake/i do
say "about to run Quake3" #Say something
puts %x{sudo /home/pi/Quake3/ioquake3.arm}
request_completed #Always complete your requests!
end
After you have made changes you should do
rvmsudo siriproxy update
rvmsudo bundle install
rvmsudo siriproxy bundle
Then test with
rvmsudo siriproxy server
229
SiriProxy - As Root
Different Approach, not as ROOT
http://www.hometoys.com/emagazine/2013/02/siri-home-automation-integration-from-start-to-finishbrpart-1--the-basics-using-a-linux-vm/2087
Best guide yet.
http://steve0hh.wordpress.com/2013/02/11/raspberry-pi-siri-proxy/
https://gist.github.com/elvisimprsntr/4409751
http://simonthepiman.com/how_to_setup_windows_file_server.php - setting up SAMBA.
Clone the GitHub and instructions.
https://github.com/plamoni/SiriProxy
http://www.idownloadblog.com/2011/12/09/how-to-install-siri-proxy-tutorial-video/
1. UPDATE YOUR PI.
Type this into Pi’s terminal:
apt-get update
apt-get dist-upgrade
apt-get autoremove
2. SET THE ROOT PASSWORD FROM THE USER ACCOUNT
This might not sound important, but this will save a lot of hassel! You’ll need root access to start SiriProxy, but you
don’t need to sudo while installing RVM, which will result in your user not being able to start SiriProxy server. Or
root not having RVM, SiriProxy installed for them.
Type
sudo passwd
Set the desired password.
Log out and log back in using root.
Remove the original account (Optional) :
deluser
3. INSTALLING THE BASICS
apt-get install samba samba-common-bin ssh vim rcs unzip -y
4. EDIT THE NETWORK SETTINGS TO USE A STATIC IP ADDRESS
We do this so as your Pi doesn’t change it’s IP address, hence we’ll have lesser hassel when setting up the iPhone
for SiriProxy.
To edit, type :
vim /etc/network/interfaces
Then once in the configuration file, comment the following out by adding a # to the front:
From
iface eth0 inet dhcp
to
230
iface eth0 inet static
Then add the following snippet below the line of code you have just commented out.
Note: Replace the words in caplocks with your own address.
auto eth0
iface eth0 inet static
address YOUR-DESIRED-IP-ADDRESS
netmask 255.255.255.0
broadcast 192.168.1.255
network 192.168.1.0
gateway 192.168.1.254
Example of mine as my Pi’s IP address was 192.168.1.6:
auto eth0
iface eth0 inet static
4. REBOOT YOUR PI
Reboot to have the changes take effect.
To reboot, type:
reboot
5. BREAK THE CIRCULAR APPLE’S SIRI SERVER DNS RE-DIRECT
Edit your DNS settings :
nano /etc/resolv.conf
Comment out NAMESERVER entires from your ISP or router internal IP address, which is usually just the first line
in the file, then add this into the file :
# Google public DNS servers
nameserver 8.8.8.8
nameserver 8.8.4.4
# Level3 public DNS servers - less hops and shorter ping times
nameserver 209.244.0.3
nameserver 209.244.0.4
6. SETUP YOUR DNS SERVER
I am opting to use Pi as the DNS server as I do not want to mess with my router’s setting.
To install DNSMASQ, type :
sudo apt-get install dnsmasq
Change the config file.
sudo nano /etc/dnsmasq.conf
At around line 63, find the following
#address=double-click.net/127.0.0.1
Under it add this
# iOS production Siri server
address=/guzzoni.apple.com/<your static ip>
# iOS beta Siri server
address=/kryten.apple.com/<your static ip>
Hit save, then restart dnsmasq by typing:
231
sudo /etc/init.d/dnsmasq restart
7. INSTALL THE PREREQUISITE THAT NEEDED TO BE INSTALLED :
sudo apt-get install ruby build-essential openssl libreadline6 libreadline6-dev curl gitcore zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt-dev
autoconf libc6-dev ncurses-dev automake libtool bison subversion pkg-config -y
8. INSTALL RVM
bash < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer)
9. SET RVM PATH
[[ -s "/etc/profile.d/rvm.sh" ]] && . "/etc/profile.d/rvm.sh"
10. SET THE RVM PATH TO BE SET UP EVERY TIME I LOG IN
echo '[[ -s "/etc/profile.d/rvm.sh" ]] && . "/etc/profile.d/rvm.sh" # Load RVM function' >>
~/.bash_profile
11. INSTALL RUBY 1.9.3
(This will take quite a long time.. So go grab a coffee and come back.)
rvm install 1.9.3
12. CLONE THE SIRIPROXY REPO
cd ~
sudo git clone git://github.com/plamoni/SiriProxy.git
13. ENTER THE SIRIPROXY DIRECTORY
cd SiriProxy
14. MAKE THE .SIRIPROXY DIRECTORY IN MY HOME DIRECTORY
mkdir ~/.siriproxy
15. COPY THE EXAMPLE CONFIG TO .SIRIPROXY DIRECTORY TO USE
cp ./config.example.yml ~/.siriproxy/config.yml
16. INSTALL SIRIPROXY
Can take a minute or two
rake install
N.B. If not running as root you will probably have to set permissions using
sudo chown -R whoami~/.rvm
and
sudo chown -R whoami~/.SiriProxy
It them fails on the build and tells you tur run
gem install /home/pi/SiriProxy/pkg/siriproxy-0.5.2.gem
DO NOT RUN THIS AS SUDO, it will fail, try it normally!
17. GENERATE THE CERTIFICATES FOR YOUR IPHONE TO USE
siriproxy gencerts
18. EMAIL & INSTALL IT TO YOUR IPHONE!
As SSH port 22 is opened by default on the Raspbian “wheezy” image, we could use WinSCP (on our main
computer) to get the certificate (ca.pem) from our Pi. To do that, we’ve to type (on our main computer) :
232
Naviagate to /home/pi/.siriproxy and copy the ca.pem.
Attach this file to an email account you have access to on your iPhone.
On the iPhone simply, open your email, tap the file and follow the prompts to install the certificate.
19. CONFIGURE YOUR IPHONE
As we’ll need to configure the DNS settings on the iPhone!.
Head to Settings app on your iPhone, select Wifi.
Then select the blue arrow of the hotspot you are connected to for more settings.
Change the DNS IP address to your Pi’s IP address, in my case, I’ve set it to192.168.1.6, which is my IP address.
233
20. BUNDLE SIRIPROXY
This installs the plugins and what not
siriproxy bundle
bundle install
21. START THE SERVER!!
To start SiriProxy, type :
siriproxy server
In the terminal it should show something like :
22. TEST IF IT’S WORKING!
On your iPhone launch Siri and say : test siri proxy
If it replys with Siri Proxy is up and running!, then you know you got it. And on the terminal, you will see
something like the image below.
234
235
Ultrasonic Distance Monitor
http://www.raspberrypi-spy.co.uk/2013/01/ultrasonic-distance-measurement-using-python-part-2/
236
Taking Screenshots on the Raspberry Pi
Posted by zag on Feb 27 2013 04:26 PM
It looks like the default debian image isn't setup to take screenshots at the moment.
Most people will need to make a screenshot at some point, so here is a quick guide to setting it up.
Step 1
Load up start >> accessories >> LXTerminal
sudo apt-get install scrot
When the install is finished, type 'scrot' at the terminal to start it.
Step 2
Press "Prt Scr" on the keyboard
Now go to file browser and you will see the screenshot in your user area.
Something like this:
[attachment=222:screenshot.jpg]
237
Simple Samba Share
http://elinux.org/R-Pi_NAS
(Tried this so kids could grab stuff from my demo pi?)
cd~
#Install the 2 samba packages (30 ish MB)
sudo apt-get update
sudo apt-get install samba
Edit the samba config for your share!
sudo nano /etc/samba/smb.conf
#Add the following at the end
[MROShare]
comment =MRO Share
path = /home/pi/
read only = Yes
writeable = Yes
create mask = 0777
directory mask = 0777
guest only = Yes
guest ok = Yes
#Save the file (ctrl + o, Enter, ctrl+x)
#Restart the Samba service. Test.
sudo service samba restart
use smbget or similar to test (try out on windows PC!)
SMBGET (tested and working!)
you need to have samba installed to use this to grab a file.
sudo smbget smb://<ipaddress>/<folder>/<file>
or to grab an entire folder (use -R recursive)
sudo smbget -R smb://<ipaddress>/<folder e.g. MROShare>/<file>
SAMBA Server on the Pi.
1. Ensure SSH setup on the Pi.
Login using the default user pi and the default password raspberry.
2. Now lets make sure all the system updates from Debian have been applied
pi@raspberrypi~$ sudo apt-get update
238
NOTE:- The disk drives that I will be attaching will be formatted in windows format - either
FAT32 or NTFS
3. Attach the disk drive or drives to the Raspberry Pi then type
pi@raspberrypi~$ sudo fdisk -l
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: 3965 MB, 3965190144 bytes
Device Boot Start End Blocks Id System
/dev/mmcblk0p1 17 1216 76800 c W95 FAT32 (LBA)
/dev/mmcblk0p2 1233 26672 1628160 83 Linux
/dev/mmcblk0p3 26689 29744 195584 82 Linux swap / Solaris
Disk /dev/sda: 1000.2 GB, 1000204886016 bytes
Device Boot Start End Blocks Id System
/dev/sda1 1 121601 976760001 7 HPFS/NTFS
Disk /dev/sdb: 4005 MB, 4005560320 bytes
Device Boot Start End Blocks Id System
/dev/sdb1 1 486 3903763+ b W95 FAT32
----------------------------------------------------From the above listing you can see a disk /dev/mmcblk0 (the SD Card) which contains 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~$ sudo mkdir /mnt/disk1
pi@raspberrypi~$ sudo mkdir /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
----------------------------------------------------239
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
filesystem.
pi@raspberrypi~$ sudo nano /etc/fstab
This will show the following
----------------------------------------------------proc /proc proc defaults 0 0
/dev/mmcblk0p1 /boot vfat defaults 0 0
#/dev/mmcblk0p3 none swap sw 0 0
----------------------------------------------------We need to add the bottom 2 lines for the 2 disk drives, please note that the entry vfat 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 /proc proc defaults 0 0
/dev/mmcblk0p1 /boot vfat defaults 0 0
#/dev/mmcblk0p3 none swap sw 0 0
/dev/sda1 /mnt/disk1 ntfs-3g defaults 0 0
/dev/sdb1 /mnt/disk2 vfat defaults 0 0
----------------------------------------------------To make the files visible to the filesystem type
pi@raspberrypi~$ sudo mount -a
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~$ sudo apt-get install samba
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~$ sudo apt-get install samba-common-bin
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~$ sudo nano /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 = Home Directories
; browseable = no
;[printers]
; comment = All Printers
240
; browseable = no
; path = /var/spool/samba
; printable = yes
; guest ok = no
; read only = yes
; create mask = 0700
;[print$]
; comment = Printer Drivers
; path = /var/lib/samba/printers
; browseable = yes
; read only = yes
; guest ok = no
;[cdrom]
; comment = Samba server's CD-ROM
; read only = yes
; locking = no
; path = /cdrom
; guest ok = yes
; preexec = /bin/mount /cdrom
; postexec = /bin/umount /cdrom
------------------------------------------------------
Then finally at the end add your windows share name - i will use a share name 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 = USB Share
path = /mnt/disk1
writeable = Yes
only guest = Yes
create mask = 0777
directory mask = 0777
browseable = Yes
public = yes
------------------------------------------------------
8. At last we can restart samba and test the configuration so to restart samba.
pi@raspberrypi~$ sudo service samba restart
and to check the shares and configuration run
pi@raspberrypi~$ sudo testparm -s
this should show something similar to that below
-----------------------------------------------------Load smb config files from /etc/samba/smb.conf
rlimit_max: rlimit_max (1024) below minimum Windows limit (16384)
Processing section "[usb]"
Loaded services file OK.
Server role: ROLE_STANDALONE
[global]
server string = %h server
obey pam restrictions = Yes
pam password change = Yes
passwd program = /usr/bin/passwd %u
passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n
*password\supdated\ssuccessfully* .
unix password sync = Yes
syslog = 0
log file = /var/log/samba/log.%m
max log size = 1000
241
dns proxy = No
wins support = Yes
panic action = /usr/share/samba/panic-action %d
[usb]
comment = USB Share
path = /mnt/disk1
read only = No
create mask = 0777
directory mask = 0777
guest only = Yes
guest ok = 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~$ sudo smbpasswd -a pi
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.
242
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~$ sudo apt-get install autofs
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~$ sudo vi /etc/auto.master
At the end of the file is the following
-----------------------------------------------------+auto.master
------------------------------------------------------
You need to add the following below the +auto.master entry
-----------------------------------------------------+auto.master
/media/ /etc/auto.ext-usb --timeout=10,defaults,user,exec,uid=1000
------------------------------------------------------
Now you can reboot and the server will keep on working and sharing your windows files on
boot
Creating a Web GUI on the Pi using Apache Sever
http://www.instructables.com/id/Simple-and-intuitive-web-interface-for-your-Raspbe/step3/Installing-aweb-server-then-transferring-your-web/
Controlling the LEDs remotely with SSH is pretty cool but the interface (console) isn't
very user friendly and typing the commands every time is long and annoying. That's why
we need a graphical interface for our project.
Programming an app for each OS (IOS, Android, Windows phone, Mac, Linux,
Windows,...) would be too long and would require to know a lot of different languages for
243
nearly nothing. It would also require to do an application running on the Raspberry Pi.
Making it this way would be overkill and time wasting.
That's why a website is the best solution, it's compatible with all devices and
you "only" need to know four languages: HTML (for the page's skeleton), CSS (page's
style), PHP (interactions with the server) and JavaScript (interactions with the user).
We indeed need to install a web server on the Raspberry Pi. In our case, we don't
need a MySQL database, only a HTTP server and its PHP extension.
After updating your Raspberry Pi with the "sudo apt-get update" command,
type "sudo apt-get install apache2 php5 libapache2-mod-php5" to install Apache
HTTP server and PHP5 extension. You can now test if your server is working by typing
the IP of your Raspberry Pi in your browser. You should now see a "It works!" page
with two other lines. If you don't, then check your board's IP, try re-installing Apache or
rebooting your Raspberry Pi. This page is showing that your Apache server is working
properly but not its PHP extension. To check it, navigate to your "/var/www/" directory by
using the "cd /var/www/" command. If you use the "ls" command, you should have only
one file named "index.html". This file corresponds to the "It works!" page. You can now
delete it ("sudo rm index.html") and create another one called "index.php" (use "sudo
nano index.php"). Then type the following text:
<?php
phpinfo();
?>
After saving it using ^o (Ctrl + o), exit nano editor with ^x (Ctrl + x). Now if you refresh
your browser, you should see a long page with lots of information about your server and
PHP. If you don't, check the index.php file, try re-installing PHP or try to understand the
error displayed instead of the page (Google it if necessary).
If both pages were correctly displayed, then you now have a fully functional Apache/
PHP server but using nano every time is annoying and not very comfortable. We indeed
need to transfer files from your computer to your Raspberry Pi. You may want to install a
FTP server but it isn't necessary, you can already transfer files using the SFTP protocol.
All you need is an SFTP client on your computer. I'm personally using WinSCP for
Windows but there are Cyberduck for mac and Filezilla for Linux. If you try transferring
files before reading what's next, you'll probably have issues such as "access refused"
or "cannot write here". It's due to the fact that the user pi isn't owning the www directory.
Indeed, if you try the "ls -l /var/www" command, you'll see that only root (the super user)
is owning the www directory. You can (like I did) use the "sudo chown -R pi /var/www"
command to change it or create a group named www-data in which you place the pi user
then use the "sudo chown -R www-data /var/www" command. The -R flag is standing
for recursive, it means that the user/group isn't owning only the directory itself but also
everything inside (index.php as example).
244
You now have your server ready to work and to receive web pages. Have fun with it if
know HTML, CSS and PHP
uptohere
245
SOFTWARE - XBMC
174
XBMC is the best media software I have ever used. I’ve been a fan and been a ‘user’ since the days of
the old XBMC4Xbox! It was the major factor as to WHY I jailbroke my iPad!
However as this guide is for the raspberry pi let’s deal with that!
I’ve tried both
Xbian and
RaspBMC.
XBian seems stable but is only updated half as often. Both seem to work well. RaspBMC has the
advantage of being one of the standard installs for NOOBS. N.B. I had trouble with the RaspBMC using
NOOBS, if you’re using the ‘Auto Update’ feature it can baulk your install (this is allegedly fixed with the
newest update!). Better to do a custom build if it is one you are using all the time! (I have 2 floating
around the house, this may become 3, with one hooked up to the Stereo!)
You’ll need to install the following bits of software if you’re trying to do anything clever.
sudo apt-get install git-clone unzip
Booting to Black Screen
The raspberry pi seems to have some issues with some TVs, where it will seemingly boot to black
screen. I think this is something to do with the HDMI stopping supplying power or something and the Pi
defaulting to the Composite Video Out. To stop this edit the Config.txt on the root of the card ensuring it
has the following (the last 3 lines are the most important!)
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
246
Windows 7 and Adding Sources
I have had issues with a Windows 7PC *(or several of them on the same network not showing upin
XBMC, to fix this ensure they have STATIC IP addresses. When adding sources don’t bother searching
just use
smb://<fixed ip>/<share>, so my TV folder would be smb://192.168.1.1/Tv
Also ensure when adding shares to Windows tha tyou use ADVANCED SHARING, EVERYONE should
have permissions.
●
●
●
●
●
●
Right Click on Folder
Properties
Sharing
Advanced Sharing
Permissions
Check that ‘Everyone’ is etc with at least ‘read’ allow ticked.
247
How to add Sources/Repos/Addons
The best way to get additional plugins, addons and Repos (repositories that will auto update your
software when new versions become available!) etc is to add the sources etc.
In XBMC goto ‘Programs->File Manager’, then ‘Add source’.
2 Excellent sources to add are
XBMC: http://xbmc.flirc.tv
Install the repository so when updates are available it will update automatically.
Then install the Addon.
Fusion: http://fusion.xbmchub.com
(install Addons Via Zip File, choose the hubwizard-beta)
From the Repo
By adding them as sources it will make it easier to install the additional addons. (instead of browsing for
local Zip Files, you can then browse for Zip files from the online sources.
Goto ‘Videos->Addons’ choose the ‘XBMC HubWizard’, wait for the launcher to run then choose
the ‘Android’ install. This will install a ton of addons, but it will also mess up some of your defaults so
be prepared to set things up again! (It will also change the boot logo and your wallpaper, so have those
ready too!)
Get the FLIRC Plugin from the GitHub - https://github.com/flirc/flirc-xbmc-plugin
248
Custom XML for better remote usage (at least on our big telly!!!)
sudo nano /$HOME/.xbmc/userdata/keymaps/remote.xml
<keymap>
<FullscreenVideo>
<remote>
<select>OSD</select>
<subtitle>ShowSubtitles</subtitle>
<red>ShowSubtitles</red>
</remote>
</FullscreenVideo>
<Visualisation>
<remote>
<select>OSD</select>
<right>SkipNext</right>
<left>SkipPrevious</left>
<back>Back</back>
</remote>
</Visualisation>
<global>
<remote>
<menu>ContextMenu</menu>
</remote>
</global>
</keymap>
Fixing TV Scraper Error
Sometime if you’re using sources and scanning XBMC will come up with ‘unable to be connect to
source, continue scanning error… this can get boring. I think it’s something to do with theTVDB and the
scraper. This seemed to fix it for me.
You may have to create / edit the following file.
/$HOME/.pi/.xbmc/addons/metadata.tvdb.com/tvdb.xml
Hi ive edit the .xml myself and also got episode information working in fact tested 100% working on
my frodo
sorry if it takes up too much space but i dunno how else to post it for others but use this exactly as
is (save as tvdb.xml and replace in folder)
<?xml version="1.0" encoding="UTF-8"?>
<!-- should be self-explanatory -->
<scraper framework="1.1" date="2009-01-27">
<NfoUrl dest="3">
<RegExp input="$$1" output="&lt;url cache=&quot;\1-$INFO[language].xml&quot;&gt;http://thetvdb.com/api/
1D62F2F90030C444/series/\1/all/$INFO[language].zip&lt;/url&gt;&lt;id&gt;\1&lt;/id&gt;" dest="3">
<expression>http://thetvdb.com/(?:index\.php)?\?tab=series&amp;id=([0-9]+)</expression>
</RegExp>
<RegExp input="$$1" output="&lt;details&gt;&lt;url cache=&quot;tt\1.xml&quot;
function=&quot;GetTVDBId&quot;&gt;http://thetvdb.com/api/GetSeriesByRemoteID.php?
imdbid=tt\1&amp;amp;language=$INFO[language]&lt;/url&gt;&lt;/details&gt;" dest="3+">
249
<expression>imdb....?/title/tt([0-9]*)</expression>
</RegExp>
<RegExp input="$$1" output="&lt;details&gt;&lt;url cache=&quot;tt\1.xml&quot;
function=&quot;GetTVDBId&quot;&gt;http://thetvdb.com/api/GetSeriesByRemoteID.php?
imdbid=tt\1&amp;amp;language=$INFO[language]&lt;/url&gt;&lt;/details&gt;" dest="3+">
<expression>imdb....?/Title\?([0-9]*)</expression>
</RegExp>
</NfoUrl>
<GetTVDBId dest="3">
<RegExp input="$$1" output="&lt;details&gt;&lt;url cache=&quot;\1-$INFO[language].xml&quot;&gt;http://thetvdb.com/
api/1D62F2F90030C444/series/\1/all/$INFO[language].zip&lt;/url&gt;&lt;id&gt;\1&lt;/id&gt;&lt;/details&gt;" dest="3">
<expression>&lt;seriesid&gt;([0-9]*)&lt;/seriesid&gt;</expression>
</RegExp>
</GetTVDBId>
<EpisodeGuideUrl dest="3">
<RegExp input="$$1" output="\1" dest="3">
<expression>(.*?http://thetvdb.com.*)</expression>
</RegExp>
<RegExp input="$$1" output="\1" dest="3">
<expression>(.*?http://thetvdb.com.*)</expression>
</RegExp>
</EpisodeGuideUrl>
<!-- input: $1=query string -->
<!-- returns: the url we should use to do the search -->
<CreateSearchUrl dest="3">
<RegExp input="$$1" output="&lt;url cache=&quot;cache-\1$$4.xml&quot;&gt;http://thetvdb.com/api/GetSeries.php?
seriesname=\1$$4&amp;amp;language=$INFO[language]&lt;/url&gt;" dest="3">
<RegExp input="$$2" output="%20(\1)" dest="4">
<expression clear="yes">(.+)</expression>
</RegExp>
<expression/>
</RegExp>
</CreateSearchUrl>
<!-- input: $1=html $2=search query -->
<!-- returns: results in xml format <results><movie><title>*</title><url>*</url>*#urls<extra>*</extra></movie>*</
results> -->
<GetSearchResults dest="1">
<RegExp input="$$4" output="&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;
standalone=&quot;yes&quot;?&gt;&lt;results&gt;\1&lt;/results&gt;" dest="1">
<RegExp input="$$1" output="&lt;entity&gt;&lt;title&gt;\3&lt;/title&gt;&lt;language&gt;\2&lt;/language&gt;&lt;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></details> -->
<GetDetails dest="7">
<RegExp input="$$4" output="&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;
standalone=&quot;yes&quot;?&gt;&lt;details&gt;\1&lt;/details&gt;" dest="7">
<RegExp input="$$1" output="\1" dest="5">
<expression noclean="1">&lt;Series&gt;.*?&lt;id&gt;$$2&lt;/id&gt;(.*)</expression>
</RegExp>
<RegExp input="$$5" output="&lt;plot&gt;\1&lt;/plot&gt;" dest="4">
<expression noclean="1">&lt;Overview&gt;([^&lt;]*)&lt;/Overview&gt;</expression>
</RegExp>
<RegExp input="$$2" output="&lt;id&gt;\1&lt;/id&gt;" dest="4+">
<expression/>
</RegExp>
<RegExp input="$$1" output="&lt;mpaa&gt;\1&lt;/mpaa&gt;" dest="4+">
<expression>&lt;ContentRating&gt;([^&lt;]*)&lt;/ContentRating&gt;</expression>
</RegExp>
<RegExp input="$$5" output="&lt;premiered&gt;\1&lt;/premiered&gt;" dest="4+">
<expression>&lt;FirstAired&gt;([^&lt;]*)&lt;/FirstAired&gt;</expression>
</RegExp>
250
<RegExp input="$$5" output="&lt;rating&gt;\1&lt;/rating&gt;" dest="4+">
<expression>&lt;Rating&gt;([^&lt;]*)&lt;/Rating&gt;</expression>
</RegExp>
<RegExp input="$$5" output="&lt;studio&gt;\1&lt;/studio&gt;" dest="4+">
<expression>&lt;Network&gt;([^&lt;]*)&lt;/Network&gt;</expression>
</RegExp>
<RegExp input="$$5" output="&lt;title&gt;\1&lt;/title&gt;" dest="4+">
<expression>&lt;SeriesName&gt;([^&lt;]*)&lt;/SeriesName&gt;</expression>
</RegExp>
<RegExp input="$$5" output="\1" dest="10">
<expression noclean="1">&lt;Genre&gt;([^&lt;]*)&lt;/Genre&gt;</expression>
</RegExp>
<RegExp input="$$10" output="&lt;genre&gt;\1&lt;/genre&gt;" dest="4+">
<expression repeat="yes">([^\|]*)\|</expression>
</RegExp>
<RegExp input="$$10" output="&lt;genre&gt;\1&lt;/genre&gt;" dest="4+">
<expression repeat="yes">([^,]*),</expression>
</RegExp>
<RegExp input="$$10" output="&lt;genre&gt;\1&lt;/genre&gt;" dest="4+">
<expression>([^\|,]+)$</expression>
</RegExp>
<!-- actors with thumbs -->
<RegExp input="$$5" output="&lt;actor&gt;&lt;name&gt;\2&lt;/name&gt;&lt;role&gt;\3&lt;/role&gt;&lt;thumb&gt;http://
thetvdb.com/banners/\1&lt;/thumb&gt;&lt;/actor&gt;" dest="4+">
<expression repeat="yes" noclean="1,2,3">&lt;Actor&gt;.*?&lt;Image&gt;([^&lt;]+)&lt;/Image&gt;.*?&lt;Name&gt;([^&lt;]
*)&lt;/Name&gt;.*?&lt;Role&gt;([^&lt;]*)</expression>
</RegExp>
<!-- actors without thumbs -->
<RegExp input="$$5" output="&lt;actor&gt;&lt;name&gt;\2&lt;/name&gt;&lt;role&gt;\3&lt;/role&gt;&lt;/actor&gt;"
dest="4+">
<expression repeat="yes" noclean="1,2,3">&lt;Actor&gt;.*?&lt;Image&gt;([^&lt;]*)&lt;/Image&gt;.*?&lt;Name&gt;([^&lt;]
*)&lt;/Name&gt;.*?&lt;Role&gt;([^&lt;]*)</expression>
</RegExp>
<RegExp input="$$5" output="&lt;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&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;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;</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])[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;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;[^&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])[az])*&lt;/Language&gt;[^&lt;]*[^S]*Season&gt;([0-9]+)&lt;/Season&gt;</expression>
</RegExp>
<RegExp input="$$5" output="&lt;thumb aspect=&quot;banner&quot; type=&quot;season&quot;
season=&quot;\2&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+">
251
<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;/Language&gt;[^&lt;]*[^S]*Season&gt;([0-9]+)&lt;/Season&gt;</expression>
</RegExp>
<RegExp input="$$5" output="&lt;thumb aspect=&quot;banner&quot; type=&quot;season&quot;
season=&quot;\3&quot;&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+">
<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])*&lt;/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[language].zip&lt;/url&gt;&lt;/episodeguide&gt;" dest="4+">
<expression/>
</RegExp>
<expression noclean="1"/>
</RegExp>
</GetDetails>
<!-- input: $1=html !-->
<!-- input: $2=series url !-->
<!-- returns: results in xml format <episodeguide><episode><title>*</title><url>*</url><season>*</
season><epnum>*</epnum><thumb>*</thumb><id>*</id><aired>*</aired></episode>*</episodeguide> !-->
<GetEpisodeList dest="3">
<RegExp input="$$4" output="&lt;episodeguide&gt;\1&lt;/episodeguide&gt;" dest="3">
<RegExp input="$$2" output="\2-\3" dest="10">
<expression>http://thetvdb.com/api/(.+)/series/([0-9]*)/all/(.+).zip</expression>
</RegExp>
<RegExp conditional="!dvdorder">
<!-- Regular episodes (Absolute order) -->
<RegExp conditional="absolutenumber" input="$$1" output="&lt;episode&gt;&lt;id&gt;\1&lt;/id&gt;&lt;title&gt;\2&lt;/
title&gt;&lt;aired&gt;\3&lt;/aired&gt;&lt;epnum&gt;\4&lt;/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&lt;/epnum&gt;&lt;season&gt;0&lt;/season&gt;&lt;url
cache=&quot;$$10.xml&quot;&gt;$$2&lt;/url&gt;&lt;/episode&gt;" dest="4+">
<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>
252
</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_season&gt;([^&lt;]*).*?&lt;EpisodeName&gt;([^&lt;]*).*?&lt;FirstAired&gt;([^&lt;]*)&lt;/FirstAired&gt;.*?
&lt;/Episode&gt;</expression>
</RegExp>
<expression noclean="1"/>
</RegExp>
</GetEpisodeList>
<!-- input: $1=html -->
<!-- returns: results in xml format <details><writer>*</writer><director>*</director><cast>*</cast><rating>*</
rating><rank>*</rank><plot>*</plot> -->
<GetEpisodeDetails dest="3">
<RegExp input="$$4" output="&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;
standalone=&quot;yes&quot;?&gt;&lt;details&gt;\1&lt;/details&gt;" dest="3">
<RegExp input="$$1" output="\1" dest="8">
<expression noclean="1">&lt;Episode&gt;.*?&lt;id&gt;$$2&lt;/id&gt;(.*?)&lt;/Episode&gt;</expression>
</RegExp>
<RegExp input="$$1" output="&lt;uniqueid&gt;$$2&lt;/uniqueid&gt;" dest="4">
<expression/>
</RegExp>
<RegExp input="$$8" output="&lt;plot&gt;\1&lt;/plot&gt;" dest="4+">
<expression>&lt;Overview&gt;([^&lt;]*)&lt;/Overview&gt;</expression>
</RegExp>
<RegExp input="$$8" output="\1" dest="6">
<expression noclean="1">&lt;Writer&gt;([^&lt;]*)&lt;/Writer&gt;</expression>
</RegExp>
<RegExp input="$$6" output="&lt;credits&gt;\1&lt;/credits&gt;" dest="4+">
<expression repeat="yes">([^\|]*)\|</expression>
</RegExp>
<RegExp input="$$6" output="&lt;credits&gt;\1&lt;/credits&gt;" dest="4+">
<expression repeat="yes">([^,]*),</expression>
</RegExp>
<RegExp input="$$6" output="&lt;credits&gt;\1&lt;/credits&gt;" dest="4+">
<expression>([^\|,]+)$</expression>
</RegExp>
<RegExp input="$$8" output="\1" dest="6">
<expression noclean="1">&lt;Director&gt;([^&lt;]*)&lt;/Director&gt;</expression>
</RegExp>
<RegExp input="$$6" output="&lt;director&gt;\1&lt;/director&gt;" dest="4+">
<expression repeat="yes">([^\|]*)\|</expression>
</RegExp>
<RegExp input="$$6" output="&lt;director&gt;\1&lt;/director&gt;" dest="4+">
<expression repeat="yes">([^,]*),</expression>
</RegExp>
<RegExp input="$$6" output="&lt;director&gt;\1&lt;/director&gt;" dest="4+">
<expression>([^\|,]+)$</expression>
</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 -->
253
<RegExp conditional="absolutenumber" input="$$8" output="&lt;season&gt;0&lt;/season&gt;&lt;episode&gt;\1&lt;/
episode&gt;" dest="4+">
<expression>&lt;EpisodeNumber&gt;([0-9]*)&lt;/EpisodeNumber&gt;.*?&lt;SeasonNumber&gt;0&lt;/SeasonNumber&gt;</
expression>
</RegExp>
<!-- Normal Season/Episodes -->
<RegExp conditional="!absolutenumber" input="$$9" output="&lt;season&gt;\1&lt;/season&gt;" dest="4+">
<RegExp conditional="!dvdorder" input="$$8" output="\1" dest="9">
<expression clear="yes">&lt;SeasonNumber&gt;([^&lt;]*)&lt;/SeasonNumber&gt;</expression>
</RegExp>
<RegExp conditional="dvdorder" input="$$8" output="\1" dest="9">
<expression>&lt;Combined_season&gt;([^&lt;]*)&lt;/Combined_season&gt;</expression>
</RegExp>
<expression/>
</RegExp>
<RegExp conditional="!absolutenumber" input="$$9" output="&lt;episode&gt;\1&lt;/episode&gt;" dest="4+">
<RegExp conditional="!dvdorder" input="$$8" output="\1" dest="9">
<expression clear="yes">&lt;EpisodeNumber&gt;([^&lt;]*)&lt;/EpisodeNumber&gt;</expression>
</RegExp>
<RegExp conditional="dvdorder" input="$$8" output="\1" dest="9">
<expression>&lt;Combined_episodenumber&gt;([^&lt;]*)&lt;/Combined_episodenumber&gt;</expression>
</RegExp>
<expression/>
</RegExp>
<RegExp input="$$8" output="&lt;thumb&gt;http://thetvdb.com/banners/\1&lt;/thumb&gt;" dest="4+">
<expression>&lt;filename&gt;([^&lt;]+)&lt;/filename&gt;</expression>
</RegExp>
<RegExp input="$$8" output="&lt;aired&gt;\1&lt;/aired&gt;" dest="4+">
<expression>&lt;FirstAired&gt;([^&lt;]+)&lt;/FirstAired&gt;</expression>
</RegExp>
<RegExp input="$$8" output="&lt;displayseason&gt;\1&lt;/displayseason&gt;" dest="4+">
<expression>&lt;airsbefore_season&gt;([^&lt;]+)&lt;/airsbefore_season&gt;</expression>
</RegExp>
<RegExp input="$$8" output="&lt;displayepisode&gt;\1&lt;/displayepisode&gt;" dest="4+">
<expression>&lt;airsbefore_episode&gt;([^&lt;]+)&lt;/airsbefore_episode&gt;</expression>
</RegExp>
<RegExp input="$$8" output="&lt;displayafterseason&gt;\1&lt;/displayafterseason&gt;" dest="4+">
<expression>&lt;airsafter_season&gt;([^&lt;]+)&lt;/airsafter_season&gt;</expression>
</RegExp>
<RegExp input="$$8" output="&lt;rating&gt;\1&lt;/rating&gt;" dest="4+">
<expression>&lt;Rating&gt;([^&lt;]+)&lt;/Rating&gt;</expression>
</RegExp>
<RegExp input="$$1" output="&lt;runtime&gt;\1&lt;/runtime&gt;" dest="4+">
<expression>&lt;Runtime&gt;([^&lt;]+)&lt;/Runtime&gt;</expression>
</RegExp>
<expression noclean="1"/>
</RegExp>
</GetEpisodeDetails>
</scraper>
254
Setting up a Shared Library
Basic Explination here - http://lifehacker.com/5634515/how-to-synchronize-your-xbmc-media-centeracross-every-room-in-the-house
Full guide http://wiki.xbmc.org/index.php?title=HOW-TO:Share_libraries_using_MySQL
(N.B. Only use version 5.5 of SQL the latest version 5.6 doesn’t work!)
First setup the SQL DB.
1.
2.
3.
4.
5.
6.
Download a copy of MySQL server from http://dev.mysql.com/downloads/mysql/
Select Standard configuration
Create a password when asked
Select that you want the database to have network access when prompted during installation.
Open the "MySQL Command Line Client" from the MySQL start menu
Enter the following commands:
1.
2.
7.
8.
9.
10.
Type in: CREATE USER 'xbmc' IDENTIFIED BY 'xbmc'; and press return
Type in: GRANT ALL ON *.* TO 'xbmc'; and press return
Close out the command line tool
In Windows 7, you may need to make an exception in the "Windows Firewall"
1. Go to control panel and open windows firewall
2. Click on advanced settings
3. Click on Inbound Rules, then new rule
4. Chose the port option, click next
5. Then type in the port number you set mysql to use(Default is 3306)
6. Make sure Allow the connection is checked then click next
7. Name it MYSQL Inbound(or whatever you want) then click finish
8. Use these same steps to set up the Outbound exception then name it MYSQL Outbound(or whatever you want)
then you're finished.
You may or may not have to set up both in and outbound, someone with more knowledge please edit this if you know.
In Windows XP, you may need to make an exception in the "Windows Firewall"
1. Open Control Panel and Set to 'Classic View'
2. Double Click on Windows Firewall
3. Click on Exception-->Add Port
4. Name It MySQL XBMC or whatever you want
5. Then type in the port number you set mysql to use(Default is 3306)
Edit the advancedsettings.xml
(in the userdata folder!)
GNU nano 2.2.6 File: /$HOME/.xbmc/userdata/advancedsettings.xml Modified
<advancedsettings>
<videodatabase>
<type>mysql</type>
<host>192.168.1.2</host>
<port>3306</port>
<user>xbmc</user>
<pass>xbmc</pass>
<name>xbmc_video</name>
</videodatabase>
<musicdatabase>
<type>mysql</type>
255
<host>192.168.1.2</host>
<port>3306</port>
<user>xbmc</user>
<pass>xbmc</pass>
<name>xbmc_music</name>
</musicdatabase>
<videolibrary>
<importwatchedstate>true</importwatchedstate>
<backgroundupdate>true</backgroundupdate> <!-- set to hide the $
</videolibrary>
<videoscanner>
<ignore errors>true</ignore errors>
<videoscanner>
</advancedsettings>
256
Remote Controls.
There are many ways to control XBMC on the Pi.
You can use a mouse, which has limited functionality.
You can use a keyboard, a little difficult to navigate sometimes.
You can use remote (£30 from CPC) or from a chinese wholesaler if you’re not in a rush - http://
www.tomtop.com/computers-networking/hausbell-2-4g-mini-wireless-qwerty-keyboard-mouse-touchpadfor-pc-notebook-android-tv-box-htpc-c1705.html
This works remarkably well, comes with a
rechargeable phone battery and reciever.
You need direct line of site, but half the price.
The final option is to use your phone / ipad / tablet
etc. Most of them have XBMC remote apps. The
official iOS xbmcRemote app works well, although
I would recommend using static IP. (it can then
control multiple instances (just not at the same
time!)
To do this you will need to turn on Zeroconf in the
XBMC -> Settings -> Services-> Zeroconf.
I’d also recommed you change the network ID of
each of the Pi’s if you’re using multiple ones. (see
elsewhere in this guide!)
257
Accessing Region Locked Content. :)
Getting the iPlayer to work in the States, or 1 channel or FreeCable plugins to work outside the US-ofA is a pain in the butt. However I have recently had some success using the excellent Tunlr service,
admittedly you have to fiddle a bit with XBMC settings, but ttings, but not too dtastically. Basically it
jut requires you to set hte Primary DNS server to theirs. In RaspBMC goto the RaspBMC settings > Network and just enter the dteails, sometimes you’ll ahve to check the numbers, other times you
might ahve to choose thihjeir backup serverseir backup server. Through this I’ve watched episdoes of
the ‘Colbert Report’ on Comedy Central, an episode of ‘ANTM’ on theCW, and an ‘Intervention’ on A&E.
I will keep this updated .
Plugins I know are working.
Plugins that are currently broken.
Video
●
●
●
●
●
●
●
●
Video
Demand 5
4OD
(both are broken till someone can reverse
engineer thei encryption)
iPlayer
FreeCable
1Channel
Navi-X
IceFilms
YouTube
Vimeo
Radbox
Audio
● 8Tracks
● PBS
● Digitally IMported
Get iPlayer
Although technically not XBMC as this is designed to run in Raspbian this sounded useful and pretty
cool.
This software should allow you to capture and record BBC programs from iPlayer (of course this wont’
work if you’re outside GB unless you’re smart with a Proxy. (see www.tunlr.com)
Full instructions here.
http://raspi.tv/2012/get_iplayer-full-instructions-for-raspberry-pi-install-from-scratch
258
USEFUL BITS OF PYTHON
187
Running A Console Command Via Python
First
import os
The call any command you would usually type in the console using
os.system(‘<command>’)
Notice the single quotes, you can use multiple commands, string them together using && or use single &
to put them in the background.
Passing Arguments to Python programs
You can pass arguments to python progams, e.g. TwitterPhoto.py listed later
python TwitterPhoto.py ‘arg1’ ‘arg2’
in the python code you can then recall these using
x = sys.argv[1]
y = sys.argv[2]
Changing Terminal Text Colours / Effects Via Python
This I would have thought would have been simple enough, sadly it was not. The only way I found to
do this was to download and address a python module called colorama, ensure you call the commands
Fore, Back, Style etc from the colorama script. then use print(<colour bit> + ‘message’)
from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + and with a green background')
print(Style.DIM + 'and in dim text')
print(+ Fore.RESET + Back.RESET + Style.RESET_ALL)
print('back to normal now')
Quick Python Pygame Joystick Axis Detection (Tested and Rechecked.)
From here
#!/usr/bin/env python
259
import pygame
import time
import math
# init controller
pygame.init()
controller = pygame.joystick.Joystick(0)
controller.init()
print 'Xbox Controller Connected'
print
print
print
print
'/*********************************/'
' Joystick Drive Program
'
"Updated by MRO for XBox Pad
"
'/*********************************/'
key = 0
y = 0
x = 0
while key != 'q':
for event in pygame.event.get():
if event.type == pygame.JOYAXISMOTION:
#Print out the Axis pressed and the Value turned out (usually between -1 and 1)
print "Axis: ",event.axis," Value: ",event.value
if event.axis == 1:
y = event.value
# to make these less sensetive turn them to 0.5s (for bigger deadzone?)
if math.fabs(y) < 0.2:
y = 0
if event.axis == 0: #I had to check this value using the above event.axis!!!
x = event.value
if math.fabs(x) < 0.2:
x = 0
# Display the
command = ' '
if y < 0:
command =
elif y > 0:
command =
elif x < 0:
command =
elif x > 0:
command =
correct output hopefully!
'up'
'down'
'left'
'right'
if command != ' ':
print command
Using Pygame to detect Joystick Presses
<from here> N.B. I had to change the ‘def print’ function to ‘def printout’ as this
conflicted with Python’s exisiting print command.
textpring.printout
No biggy.
Just change textprint.print to
import pygame
# Define some colors
BLACK
= (
0,
0,
0)
WHITE
= ( 255, 255, 255)
# This is a simple class that will help us print to the screen
# It has nothing to do with the joysticks, just outputing the
# information.
class TextPrint:
def __init__(self):
260
self.reset()
self.font = pygame.font.Font(None, 20)
def print(self, screen, textString):
textBitmap = self.font.render(textString, True, BLACK)
screen.blit(textBitmap, [self.x, self.y])
self.y += self.line_height
def reset(self):
self.x = 10
self.y = 10
self.line_height = 15
def indent(self):
self.x += 10
def unindent(self):
self.x -= 10
pygame.init()
# Set the width and height of the screen [width,height]
size = [500, 700]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
#Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# Initialize the joysticks
pygame.joystick.init()
# Get ready to print
textPrint = TextPrint()
# -------- Main Program Loop ----------while done==False:
# EVENT PROCESSING STEP
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
# Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP
JOYHATMOTION
if event.type == pygame.JOYBUTTONDOWN:
print("Joystick button pressed.")
if event.type == pygame.JOYBUTTONUP:
print("Joystick button released.")
261
# DRAWING STEP
# First, clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
screen.fill(WHITE)
textPrint.reset()
# Get count of joysticks
joystick_count = pygame.joystick.get_count()
textPrint.print(screen, "Number of joysticks: {}".format(joystick_count) )
textPrint.indent()
# For each joystick:
for i in range(joystick_count):
joystick = pygame.joystick.Joystick(i)
joystick.init()
textPrint.print(screen, "Joystick {}".format(i) )
textPrint.indent()
# Get the name from the OS for the controller/joystick
name = joystick.get_name()
textPrint.print(screen, "Joystick name: {}".format(name) )
# Usually axis run in pairs, up/down for one, and left/right for
# the other.
axes = joystick.get_numaxes()
textPrint.print(screen, "Number of axes: {}".format(axes) )
textPrint.indent()
for i in range( axes ):
axis = joystick.get_axis( i )
textPrint.print(screen, "Axis {} value: {:>6.3f}".format(i, axis) )
textPrint.unindent()
buttons = joystick.get_numbuttons()
textPrint.print(screen, "Number of buttons: {}".format(buttons) )
textPrint.indent()
for i in range( buttons ):
button = joystick.get_button( i )
textPrint.print(screen, "Button {:>2} value: {}".format(i,button) )
textPrint.unindent()
# Hat switch. All or nothing for direction, not like joysticks.
# Value comes back in an array.
hats = joystick.get_numhats()
textPrint.print(screen, "Number of hats: {}".format(hats) )
textPrint.indent()
for i in range( hats ):
hat = joystick.get_hat( i )
textPrint.print(screen, "Hat {} value: {}".format(i, str(hat)) )
textPrint.unindent()
262
textPrint.unindent()
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Limit to 20 frames per second
clock.tick(20)
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit ()
263
Pi Club 192
Here’s a rough list of what happened at Pi-Club, attendance, issues, problems etc.
Session 1 - Basic Setup (Network) and Minecraft (an Easy Win)
What worked
- Explain to kids they need a few commands to get them working on the network!
- Giving kids memory cards to look after / keeping hold of those kids did not want to take away.
- Giving kids small identifying sticker (from my £1.99 Lego sticker book) Put them on the cards so they
know who’s is who’s. Get cards stored in little wallet to carry around!
- Get kids to use every other computer in my room setup, then they can open this document on the other
as a reference.
- Sort out memory stick of Awesome (with stuff needed to be passed around)
- Nice to see some kids bringing their OWN Pi’s!!!!
Session 2 - USB Rocket Launchers
Got out 4 new USB Rocket Launchers explained about commands etc. Got them to acquire files etc.
Issues
- Getting all the darts back! (although most kids after explination and cost were very, very good!)
- Not enough USB Hubs (must buy 2 more!)
- Not enough exposed / accessible power sockets for hubs.
- 2 of the rocket launcher only seem to fire from certain hubs, they’d move, but not fire!
Session 3 - Quake 3 and Emulation (DGEN?)
Quake 3 Basic install!
Compiling your own code!
DGen (test if this work via a smbget!)
Games.
- Discuss legality of ROMs and full version of Quake 3.
Suggestions:
Currently some of the stuff in this doc requires access to sites like dropbox etc that are blocked by the
school proxy. I tried working around this with GDrive, but it’s a real faff. I stumbled upon a solution that
I thought was reasonable. Setup your /home/pi/ folder as a SAMBA share, (see guide), then get the kids
to install SAMBA, you can then use ‘smbget’ rather than ‘wget’ to grab files directly from the Master Pi!
(instead of just the AWESOME Pendrive).
What Worked.:
264
smbget did work, even when the Pi was running as a server! Problems arose when the kids hadn’t
expanded the root fs to fill the card and a couple of the cards got full. 4GB isn’t THAT big! Get 8GBs
if you can. One or two cards had a bit of corruption, this seems to happen if you power the Pi’s via
USB and connect them upto a high drain device, like the rocket launcher??? Q3 Areana was good fun,
we discussed custom servers, even ran the one at the front as a dedicated server, even better when
one ‘bright spark’ realised he could KICK people off using various commands (I wouldn’t have thought of
doing that!)
What didn’t work:
DGen / Snes9x - Despite the setup of the Megadrive 2 with Sonic 2 and the Pi running DGen (that
seems well fussy with SDL-DispMax (still can’t run on my own card!). I didn’t explain this very well.
Suggest kids go away and find models. One kid suggested he’s like to create his own (off the back of
the minecraft skinning, assuming it was just JPG files to edit!) I explained he’d need to learn a little 3d
modelling. I might see if I can find a guid on this! (Perhaps Sketchup to Q3 Arean!) I did offer rewards
for kids that emailed me links to level’s / Mods, got one to the Simpson’s neighbourhood, however this
would not run on the Pi due to the memory limitations, nothing else! But I did find some collective map
packs, lvl_10th_Anniversary pack, seemed to be quite good. Will have a play with some modifiers
perhaps try running ‘The Dark Conjunction’ mod. (now I have realised what the BAT files do!, just call
the standard quake exe (or in this case .arm) with some arguments!) One issue I found with Q3 on the
whiteboard was the teeny tiny console font (in Q3 console, not the BASH!).
Session 4 - Breakout Board(s), Wiring bits?
Suggestions:
Screaming Jelly Baby?
Intro to Python?
What Worked:
By this time I’ve had a couple of student asking about setting up wireless adapters (as most routers are
often away from their rooms!). The first one was a simple enable in X and disable the school bits in /etc/
apt/apt.conf (# out the school proxy). The second was issues installing drivers??? Still unsovled, but
working on it. A smaller group this time (due to 2 week absense and school trip to Holland!). Talked the
briefly through the project. Introduced the Cobbler Kit, or bits, showed the Pins, explained they’re an
interace to the outside world. Printed off 5 copies of the ‘Singing Jellybaby’ OCR Worksheet as a basis.
The more able students were EAGER to get going on this, one got through very quickly and moved on.
Another followed this up later and then tried expanding up on the idea, but wanted to change the text
colour in the Terminal of his output (found a python plugin called colorama), With a bit of tweaking got
this done! By this point those not interested in the GPIO etc were able to get up and running / networked
on Quake3 or Minecraft without much assistance. Keep backing up the SD Card Image!
What Didn’t Work
For many this was their first introduction to writing python scritps, some struggled with syntax. I didn’t
explain about Tabbing your code (across the page for loops etc). This caused one or two issues.
Should have checked earlier the MP3 was available. If done again grab the MP3, or create their own
(Have MIC setup for this!).
265
Session 4.5 - Fail.
This was a bit of a damp squid. Getting back from 2 weeks off, unprepared and without any resources.
It was a mulling around session and kids were distracted. Not a great turn out. Kids still not taking
ownership of memory cards. Need more incentives / rewards???
Session 5 - Robot Arm.
What Worked
One pupil was keen to try out the XBMC distro he’d found. Was able to setup and use his phone as
hotspot. Managed to stream lots of videos from YouTube.
Let kids loose on the Robot Arms that I’d got via STEM budget, they’re fun to build, but the kids need
*SOME* support. However one or two students really enjoyed creating them. Hoped to get them
hooked up to Pi’s but ran out of time. Managed to get the code for it to work with PS3 Pad (Wired I
assume!) But then forgot the PS3 pad. Found a Year 11 to fetch one at lunch. But they never came
back. :( (Don’t rely on Year 11s for kit!) Years 7-9 more reliable. Howeve they’re not allowed off site.
What didn’t work.
Forgetting equipment. Have multiples of everything for usage? This is one option. Need to write up
more tutorials, get laptops that were promised so can do SSH, a great way of getting large chunks of
code quickly on the Pis! School won’t let it be installed on the desktops! Boo. Security Risk Apparently!
Session 6 - Pi Camera.
What Worked
Demonstrated the camera, had a brief discussion about the Camera, why not USB, the fact uses fast
bus. Looked at the physical camera, commented on size, compared it to phone camera. Demo’d it
doing basic photo capture, then a bit of video capture. The magic was kept alive as this was done
through the magic of WinSCP which allowed quick access / viewing of photos. Nice that had a year
9 trying to download Quake 3 Mods, he eventually (through the school proxy) found a few. Then had
discussion on how to get this onto Quake on the Pi, discussed how AWESOME wget command was,
then via SSH enabled browser access on the Pi (this is different to just using the proxy at the bash!)
and he browsed on the Pi, found the file, downloaded the link, unzipped, put on the pi and tested! He
managed to find a good level that was a DJ Deck, if you stood on the desk you spun!!! Had one kids still
building robot arm, this has taken him nearly 4 sessions, but is almost complete! The other bright spark
wanted Pi Club stickers, so we killed a tree going through publisher lining up margins etc, only to finally
print on the laser and was badly aligned, but the child learnt quite a lot about Publisher, borders, paper
etc.
What didn’t work.
266
Wanted to try stop motion capture and possibly web streaming. This would have been brilliant to get
students next door (or on any other computer on the school network viewing the camera output. I did
not however have time to get this working in the club. (further reading and fiddly configuration shoudl
have been done before the club. Kids were marvelled at lego case that I have my Pi in, perhaps provide
tutorial PDF of instructions.
Session 6.5 - A Short Pi Club due to meetings and other commitments.
Talked about Torrents (Legal downloading of large files) as tried to demonstrate how I could not
download CrunchBang at school via the system as it was a torrent and ports are blocked at school, so
would have to do this at home. Want to be able to run Pi next to computer setup. Works better that way!
Less guessing! Did show that you could take over another students Pi by SSHing to it.
What Worked
Getting kids to log on to PCs and setup Pis relatively quickly.
Getting kids to write their IP Addresses on the whiteboard!
It’s worth downloadig useful videos, the Gigafide (Tinkernut) YouTube on how to hack minecraft is useful
and funny too. well worth grabbing for later use. - http://www.youtube.com/watch?v=YsXumCkcxLw
What didn’t work
The Github seemed blocked at school! (sigh another issue!)
Had lots of trouble setting up my end (laptop, and project screen hardly visible in the bright light!
Session 7 - Minecraft Hacking on the Pi using Python Scripts?
POA - Get Minecraft running on the Pi’s create a couple of custom ‘simple’ scripts to allow people to
hack minecraft, demonstrate how to get the PyScripts from the site (have them downloaded already, just
in case!) then run via SSH for extra awesomeness???
What Worked
What Didn’t work.
Session 8 - PiFM (Pirate Radio!)
POA - Get students to see how simple it is to get FM signal from a Pi.
Get students to record a piece of audio (convert to correct format!)
Get them to play it back out, possibly write a script to make the signal loop round and round (perhaps a
Zombie test message? Like I did.)
Setup Live Mic Example (tested and working).
Get them to run around the school testing just how far the signal will go. Also freak out random students
if you have a good clear view of the atrium!
267
Session 9 - Twittering
This requires the students to have Access to TWITTER! (otherwise the twitter API will not work!)
Show them how you call the API each time with useful bits of info!
Session 10 - Recap on SSH & Pi-Karaoke
I setup every other PC on one row with a Live install of Mint (16) on 4GB flash drives so could demo both
SSH, but also installed Quake3 to show it would work across platforms / architecture!
I also setup the demo Pi to connect to my phone as a hotspot, (Jailbroken Tethering) allowing me to
demo YouTube streaming from An SSH interface (iPad or pupil's phone)
Session 11 - Makey Makey and DGen
An interested student very kindly provided a Makey Makey they had got at Xmas to test. So after a
bit of tweaking we initially hooked it up to my laptop for basic testing, all good. The hooked it straight
up to the Pi via a Pi Hub. We then hunted around for something we could use to control. (As ALL the
sites suggested on the MakeyMakey site were blocked as they’re FLASH games!) I’d been compiling
DGen to get it working so we tried it with sonic, I had some cola bottles (gummi sweets) lying around
so we hooked them up via jumper wires (used for breadboard design, male / male), cliped them to the
makeymakey crocodile clips to use as buttons. We laid them out in a DPad config on a book / planner
(we found licking the bockktom and putting them on the whiteboard page worked!). However we had
the problem of how to hold th balck earthing wire. I’d seen someone do it with a wedding ring, so I tried
on mine, it worked. Later on one of the students found that a keyring from their keys weokred equally
as well. We found that both Sonic and Splatterhouse 3 worked on Dgen. There was lots of wonder and
interested from students generally! If trying to download Zip files via the browser I found Midori failed to
SAVE the zip file, leaving a file of 0KB, however the same file in iceweasel worked fine.
Session 12 - QR Codes
Setup using PS3 Eyetoy, some lag. But worked quite well with prompt & espeak. Launched Quake3, X,
and Minecraft (if in X). Had some kids generating some QR Codes of their own!
Also setup DGen in around an hour. A quick demo of Grooveshark on the pi. Worked via wirless
tethering of my phone.
268
COST OF STUFF / PRICE GUIDE 196
Product
Vendor
Approx
Cost
Raspberry Pi.
Farnell
£30.00
Suitable Adapter Plug
Farnell / RS
£5.00
HDMI Cable
(ASDA VALUE)
£3.00
HDMI -> DVI Cable
EBay
£3.00
USB Hub (Powered)
EBay / Amazon.
£7.00
Keyboard
Generic (Go Wilkinsons / Similar)
£5.00
PS3 Control Pad
Amazon (Must be Genuine!)
£30
Mouse
Generic
£5.00
Bluetooth Adapter
Poundland
£1.00
Wireless Adapter
Amazon (Edimax)
£8.00
Prototype Board Kit
Ebay
£10.00
Cobbler Interface Cable
Adafruit
£8.50
Pi Case
SK Pang
£12.50
Memory Cards 8GB
www.MemoryBits.co.uk or www.7dayshop.com
£7
USB Remote Control
Play.com / Ebay
£5.00
Textstar LCD Module
Cool Components
£28.00
Remote ATV ‘The Bear’(kit, with 3x Motors)
www.IWoot.com
£20.00
Assorted Electronic Components (Chips and
LCDs etc)
Maplins
£10.00
Jumper Wires (Motherboard type for LCD)
Maplins
£3.99
GERT Board
www.farenell.com
£40.00
Random LCD Displays Hitachi HD44780 LCD
controller Compatible
Ebay
£20.00
Motor Driver Chips and Breadboard Breakout
Bits
http://www.hobbytronics.co.uk
£18.00
Robot Arm (USB)
Maplins
£30.00
Pi-Car
Pi-Car.com
£30.00
LED Strip Lights (12volt)
Ebay (user - http://myworld.ebay.co.uk/gomepls?
_trksid=p2047675.l2559)
£4.00
269
Armtel Board (for lighting) - NooGroove USB
Board - ATMEGA32U2 (AT90USB162) AVR
Stick
Ebay
£11
New 5V 8 Channel Relay Module Board for
Arduino PIC AVR M
Ebay
£6.00
Solar Charger
Online (Paypal) - [email protected]
£20.00
PS3 Eyetoy
Game (2nd Hand)
£2
LED Borg
http://www.piborg.com/ledborg
£5
3.5" TFT LCD Car Rear View Monitor Color
Screen DVD VCR For Car Backup Camera
Ebay
£12.03
Dream Cheeky USB Rocket Launcher
Amazon.
£29
TV Tuner (USB) - August DVB-T205 USB
Freeview Tuner Stick
Amazhttp://www.amazon.co.uk/gp/product/
B002EHVP9C/ref=oh_details_o00_s00_i00?
ie=UTF8&psc=1on
£15
DC Power Supply (3-12V)
Wilkos
£5
Pebble Power Supply
Scan.co.uk
£14
Forward PowerTube Phone Battery
Scan.co.uk
£9
Pi Bow Case
www.pimoroni.com
£13
Camera Mount
thepihut.com
£3
Pi Heatsink
thepihut.com
£1
Pi Noodle Cable
thepihut.com
£3
Pi Vesa Mount (Slice)
thepihut.com
£5
Cheap Pocket Radio to test PiFM
Poundland
£1
PiHub
http://shop.pimoroni.com/products/pihub
£25 (inc
shipping)
Burger Speakers (USB Charge and fitted
audio jack.)
ebay
£3
Mini Portable Speaker LCD MP3/4 Player
Micro SD/TF USB FM ebay
£9
L9110S H-bridge Dual DC Stepper Motor
Driver Controller Board ebay
£2
48 LED illuminator light CCTV IR Infrared
Night Visio,K ebay
£6
AC Wall 100-240V To DC 12V 500mA Power
Supply Charger Adapter UK Plug ebay
£2.5
Spreadsheet Version (My Own Personal Cost)
270
271
Linux Mini Guide (for Laptop / PC)
198
Here is just where I will jot down some experiences that I’ve had since I’ve been bold enough to dabble
with Linux on Desktops / Laptops.
I’d recommend you start with LiveUSBs/DVDs.
I’ve tried different Debian based distros.
Ubuntu seems pretty friendly, but didnt’ work very well on old tech.
Linux Mint seems stable and works with many things out of the box!
Create a Live USB with Persistance.
This means you don’t loose the settings you’ve done / created every time.
This software LILI - Linux Live USB Creator allows you to add persistance to a live linux distro (Currently
Testing with Mint!) on a 4GB card (1.5 GB persistance!)
How to Enable SSH on Linux Mint 16/15 /14 / 13 / 12
I have noticed that a lot of people do not know how to enable SSH on Linux Mint systems, so I have
decided to make this article.
To enable SSH (secure shell) on Linux Mint 15 Olivia, Linux Mint 14 Nadia, Linux Mint 13 Maya and
Linux Mint 12, all you have to do is install the SSH package, which isopenssh-server.
Make sure have access to the Internet (edit /etc/apt/apt.conf for proxy if you need to!)
sudo apt-get update
sudo apt-get install openssh-server
sudo passwd mint
<enter a new password!>
VNC on Linux to Pi
Install the VNCViewer software
sudo apt-get install vncviewer
vncviewer <ip address of pi> :1
Quake 3 on Linux Mint.
You can download the 2 required setup file (ioquake....run), copy to Downloads folder on the Live
version of Mint. Run a terminal and then type
sh ioquake3....run
272
Then do the same for the other setup! Don't use SUDO (it will mess up the install).
I then also used sudo apt-get install ioquake3
Finally copy the.pak0 file to the base3q folder to get it to work.
273