Tag Archives: Python

Make Games with Python – the latest e-book in The MagPi Essentials range!

via Raspberry Pi

Make Games with Python is designed to help you learn the coding skills you need to create amazing games and applications on your Raspberry Pi. The best bit? The price starts at free

While countless millions of us like nothing more than spending hours racking up high scores on our favourite games, too few of us are exposed to an even more gratifying way to spend the evening – making them.

RPi_Essentials_eBook2_PythonGames-001

Written by technologist and tinkerer, Sean M. Tracey, Make Games with Python is made up of ten chapters that take you on a whirlwind tour of Pygame’s game-making capabilities. The book helps you learn essentials Python skills like lists, dictionaries, classes and more.

Here’s a quick breakdown of what you can expect to learn:

  • Creating shapes and paths
  • Movement and animation
  • Using the keyboard & mouse
  • Adding sound and music
  • Simulating physics and forces
  • Building classes for actors
  • Creating your own shoot-em ‘up
Games_on_Tablet

Download the free PDF today (11MB)

Like the look of The Essentials range? You might quite fancy Conquer the Command Line. The terminal window isn’t as scary as you might think!

If you’d like to support the Raspberry Pi Foundation’s charitable aims you can buy both Make Games with Python and Conquer the Command Line on your favourite Apple or Android device for £2.99 / $3.99 each.

The MagPi app itself is entirely free to download and comes complete with the first 30 issues free!

app_store google_play

The post Make Games with Python – the latest e-book in The MagPi Essentials range! appeared first on Raspberry Pi.

GPIO Zero: a friendly Python API for physical computing

via Raspberry Pi

Physical computing is one of the most engaging classroom activities, and it’s at the heart of most projects we see in the community. From flashing lights to IoT smart homes, the Pi’s GPIO pins make programming objects in the real world accessible to everybody.

Some three years ago, Ben Croston created a Python library called RPi.GPIO, which he used as part of his beer brewing process. This allowed people to control GPIO pins from their Python programs, and became a hit both in education and in personal projects. We use it in many of our free learning resources.

However, recently I’ve been thinking of ways to make this code seem more accessible. I created some simple and obvious interfaces for a few of the components I had lying around on my desk – namely the brilliant CamJam EduKits. I added interfaces for LED, Button and Buzzer, and started to look at some more interesting components – sensors, motors and even a few simple add-on boards. I got some great help from Dave Jones, author of the excellent picamera library, who added some really clever aspects to the library. I decided to call it GPIO Zero as it shares the same philosophy as PyGame Zero, which requires minimal boilerplate code to get started.

led-gpio17

This is how you flash an LED using GPIO Zero:

from gpiozero import LED
from time import sleep

led = LED(2)

while True:
    led.on()
    sleep(1)
    led.off()
    sleep(1)

(Also see the built-in blink method)

As well as controlling individual components in obvious ways, you can also connect multiple components together.

GPIO_Zero_Diagram_3

Here’s an example of controlling an LED with a push button:

from gpiozero import LED, Button
from signal import pause

led = LED(2)
button = Button(3)

button.when_pressed = led.on
button.when_released = led.off

pause()

We’ve thought really hard to try to get the naming right, and hope people old and young will find the library intuitive once shown a few simple examples. The API has been designed with education in mind and I’ve been demoing it to teachers to get feedback and they love it! Another thing is the idea of minimal configuration – so to use a button you don’t have to think about pull-ups and pull-downs – all you need is the pin number it’s connected to. Of course you can specify this – but the default assumes the common pull-up circuit. For example:

button_1 = Button(4)  # connected to GPIO pin 4, pull-up

button_2 = Button(5, pull_up=False)  # connected to GPIO pin 5, pull-down

Normally, if you want to detect the button being pressed you have to think about the edge falling if it’s pulled up, or rising if it’s pulled down. With GPIO Zero, the edge is configured when you create the Button object, so things like when_pressed, when_released, wait_for_press, wait_for_release just work as expected. While understanding edges is important in electronics, I don’t think it should be essential for anyone who wants to

Here’s a list of devices which currently supported:

  • LED (also PWM LED allowing change of brightness)
  • RGB LED
  • Buzzer
  • Motor
  • Button
  • Motion Sensor
  • Light Sensor
  • Analogue-to-Digital converters MCP3004 and MCP3008
  • Robot

Also collections of components like LEDBoard (for any collection of LEDs), FishDish, Traffic HAT, generic traffic lights – and there are plenty more to come.

There’s a great feature Dave added which allows the value of output devices (like LEDs and motors) to be set to whatever the current value of an input device is, automatically, without having to poll in a loop. The following example allows the RGB values of an LED to be determined by three potentiometers for colour mixing:

from gpiozero import RGBLED, MCP3008
from signal import pause

led = RGBLED(red=2, green=3, blue=4)
red_pot = MCP3008(channel=0)
green_pot = MCP3008(channel=1)
blue_pot = MCP3008(channel=2)

led.red.source = red_pot.values
led.green.source = green_pot.values
led.blue.source = blue_pot.values

pause()

Other wacky ways to set the brightness of an LED: from a Google spreadsheet – or according to the number of instances of the word “pies” on the BBC News homepage!

Alex Eames gave it a test drive and made a video of a security light project using a relay – coded in just 16 lines of code.

GPIO Zero Security Light in 16 lines of code

Using GPIO Zero Beta to make a security light in 16 lines of code. See blog article here… http://raspi.tv/?p=8609 If you like the look of the RasPiO Portsplus port labels board I’m using to identify the ports, you can find that here http://rasp.io/portsplus

Yasmin Bey created a robot controlled by a Wii remote:

Yasmin Bey on Twitter

@ben_nuttall @RyanteckLTD pic.twitter.com/JEoSUlHtF6

Version 1.0 is out now so the API will not change – but we will continue to add components and additional features. GPIO Zero is now pre-installed in the new Raspbian Jessie image available on the downloads page. It will also appear in the apt repo shortly.

Remember – since the release of Raspbian Jessie, you no longer need to run GPIO programs with sudo – so you can just run these programs directly from IDLE or the Python shell. GPIO Zero supports both Python 2 and Python 3. Python 3 is recommended!

Let me know your suggestions for additional components and interfaces in the comments below – and use the hashtag #gpiozero to share your project code and photos!

A huge thanks goes to Ben Croston, whose excellent RPi.GPIO library sits at the foundation of everything in GPIO Zero, and to Dave Jones whose contributions have made this new library quite special.

See the GPIO Zero documentation and recipes and check out the Getting Started with GPIO Zero resource – more coming soon.

The post GPIO Zero: a friendly Python API for physical computing appeared first on Raspberry Pi.

Give me your number and get a unique micro-noise piece

via Arduino Blog

prankophone

Prankophone  is the new interactive installation by Dmitry Morozov (his amazing projects have been featured on this blog ).  This time he created  a sound object, a hybrid of synthesizer, telephone and logic module:

The main principle of the object’s functioning is as follows: depending on the current mode, the apparatus calls to random or pre-defined recipients and plays them algorithmic melodies created from their phone numbers. The speakers transmit both the synthesized sounds and the sound from answering person. The common sound layer is involving a random recipient who doesn’t suspect anything. The person who answers the phone can’t hear any other sounds except for the synthesized ones.

You can play with it in 4 different modes:

Autonomous mode –  it generates the numbers by itself and tries to reach them, and play them the sounds.
Manual mode – when you dial any number by pressing standard phone keys it gets automatically transformed into sounds.
Keyboard mode – mode of dialing the number on the one-octave keyboard where 10 keys correspond to 10 digits.
Live mode – the number is defined by any of the previous methods, but the sounds are reproduced not automatically but from the keyboard, thus the user may “communicate” through sound with the person who answered.
It runs on Arduino Mega and you can listen to its sounds on the following video:

Adding OAuth2 to OpenSelfie

via WyoLum Blog

As in most things Internet, when you make them more secure, things get more complicated. A little while ago, photo uploads from OpenSelfie (our OpenSource Raspberry Pi AlaMode Photobooth) stopped working. It turns out that Google disabled “programmatic login” (e.g. with a username and password) from most of their apis, including the picasaweb api that we use to upload photos. Now the only thing that works is OAuth2, and it requires a little dance between a web browser signed into your google account, and granting of credentials for your application.

Diagram from the google developers site

Diagram from the google developers site

I had a real hard time figuring out how it all works until I found this link:

https://groups.google.com/forum/#!topic/google-picasa-data-api/4meiAJ40l3E

There were bits of information missing, and a couple of errors but I eventually figured it out. The new code is in boothcam.py in a procedure called OAuth2Login, which takes a pointer to a secrets json file (more on this below), a credentials store file (where the authenticated credentials are cached for you, and the user’s email address.

There’s also a standalone version for listing Album ids (useful for configuring a new album for an event in listalbums.py

You’ll need to install the latest google python api:

$ sudo pip install --upgrade google-api-python-client

def OAuth2Login(client_secrets, credential_store, email):
 scope='https://picasaweb.google.com/data/'
 user_agent='picasawebuploader'

 storage = Storage(credential_store)
 credentials = storage.get()
 if credentials is None or credentials.invalid:
   flow = flow_from_clientsecrets(client_secrets, scope=scope, redirect_uri='urn:ietf:wg:oauth:2.0:oob')
   uri = flow.step1_get_authorize_url()
   webbrowser.open(uri)
   code = raw_input('Enter the authentication code: ').strip()
   credentials = flow.step2_exchange(code)

 if (credentials.token_expiry - datetime.utcnow()) < timedelta(minutes=5):
   http = httplib2.Http()
   http = credentials.authorize(http)
   credentials.refresh(http)

 storage.put(credentials)

 gd_client = gdata.photos.service.PhotosService(source=user_agent,
 email=email,

 additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token})

You can see it creates a flow and asks google for credentials using your secrets file. (note that this is not checked in as you could use up my api credits. You;ll need to create your own.) It then spins up a web browser, makes sure you are logged in to your google account (the email address you configured OpenSelfie with) and asks your permission.

It will then give you a code to enter into OpenSelfie. I had troiuble cutting and pasting from the default web browser so I installed luakit, and made it the default browser

$ sudo update-alternatives --config x-www-browser

Creating your own API keys with the Google Developer console

Head on over to the Google Developer console and create a project for your OpenSelfie

Google-dev-step1

The name here doesn’t really matter. I just used OpenSelfie.

Next, click on your project and click on Credentials under API’s and auth. You’ll want to “Add Credentials/OAuth 2.0 client ID” Note: you don’t have to explicitely enable any additional APIs, as we are dealing with basic authentication and authorization here which is used by every API, and the photo apis haven’t been explicitly added to the console.

google-dev-step3

Next you specify the type “Other” and I named it Installed. Most of the instructions I saw seemed to imply there used to be a type called Installed. I’m not sure it’s critical that this name be here, but I used it to be safe. Click Create.

google-dev-step4

Now you’ll see it in your list of credentials for this app.

google-dev-step5

Click OK, and then click on the “Installed” credential. When that’s open, click on Download JSON. It will download a file with a name like client_secret_90328409238409238……json

google-dev-step6-download

rename this file OpenSelfie.json and put it in the OpenSelfie/scripts directory.

Configuring OpenSelfie

Start up OpenSelfie in a terminal window:

cd OpenSelfie/scripts
python ./photobooth_gui.py

If you’ve already configured your OpenSelfie, when it tries to login to google, it will find it doesn’t have credentials and then start the flow to create them. Your web browser will pop up, you should sign in to google, (with the same email address you configured.) and then it will ask you if OpenSelfie  can manipulate your photos.

Permission

Click on Allow, and then it will display a box with a long string of numbers and letters. Cut and paste that into the console window where it says “Enter the Authentication Code.” hit enter, and if all is well it will snap a photo and upload it to the album you have previously configured (or fail if you haven’t set it yet.)

paste-code

Fortunately, you only have to do this once! After this it will remember the credentials and periodically refresh them. The cached credentials are stored in a file called credentials.dat, so if you delete it, you’ll have to do the web dance again, as long as your json file is still there.

Conclusion?

Well, it seems to me that Google is trying to be a good security player, at the cost of ease of use. It seems that it’s very difficult to interact with devices with a limited UI (they suggest printing URLs and having them typed into another device). Fortunately we’re working with a full Raspberry Pi so it can all be done on the same machine. I’m sure the UI can be finessed, and if you do fork the project and make improvements, please make pull requests!

Astro Pi: Mission Update 6 – Payload Handover

via Raspberry Pi

Those of you who regularly read our blog will know all about Astro Pi. If not then, to briefly recap, two specially augmented Raspberry Pis (called Astro Pis) are being launched to the International Space Station (ISS) as part of British ESA Astronaut Tim Peake’s mission starting in December. The launch date is December the 15th.

Britsh ESA Astronaut Tim Peake with Astro Pi

British ESA astronaut Tim Peake with Astro Pi – Image credit ESA

The Astro Pi competition

Last year we joined forces with the UK Space Agency, ESA and the UK Space Trade Association to run a competition that gave school-age students in the UK the chance to devise computer science experiments for Tim to run aboard the ISS.

Here is our competition video voiced by Tim Peake himself:

Astro Pi

This is “Astro Pi” by Raspberry Pi Foundation on Vimeo, the home for high quality videos and the people who love them.

This ran from December 2014 to July 2015 and produced seven winning programs that will be run on the ISS by Tim. You can read about those in a previous blog post here. They range from fun reaction-time games to real science experiments looking at the radiation environment in space. The results will be downloaded back to Earth and made available online for all to see.

During the competition we saw kids with little or no coding experience become so motivated by the possibility of having their code run in space that they learned programming from scratch and grew proficient enough to submit an entry.

Flight safety testing and laser etching

Meanwhile we were working with ESA and a number of the UK space companies to get the Astro Pi flight hardware (below) certified for space.

An Astro Pi unit in its flight case

An Astro Pi unit in its space-grade aluminium flight case

This was a very long process which began in September 2014 and is only now coming to an end. Read all about it in the blog entry here.

The final step in this process was to get some laser engraving done. This is to label every port and every feature that the crew can interact with. Their time is heavily scheduled up there and they use step-by-step scripts to explicitly coordinate everything from getting the Astro Pis out and setting them up, to getting data off the SD cards and packing them away again.

Astro Pi in laser-etched flight case

An Astro Pi in its flight case, showing off a beautifully laser-etched Raspberry Pi logo

So this labelling (known within ESA as Ops Noms) allows the features of the flight cases to exactly match what is written in those ISS deployment scripts. There can be no doubt about anything this way.

Astro Pi in laser-etched flight case

An Astro Pi in its freshly laser-etched flight case, all inputs and outputs clearly labelled

In order to do this we asked our CAD guy, Jonathan Wells, to produce updated drawings of the flight cases showing the labels. We then took those to a company called Cut Tec up in Barnsley to do the work.

They have a machine, rather like a plotter, which laser etches according to the CAD file provided. The process actually involves melting the metal of the cases to leave a permanent, hard wearing, burn mark.

They engraved four of our ground Astro Pi units (used for training and verification purposes) followed by the two precious flight units that went through all the safety testing. Here is a video:

Private Video on Vimeo

Join the web’s most supportive community of creators and get high-quality tools for hosting, sharing, and streaming videos in gorgeous HD with no ads.

After many months of hard work the only thing left to do was to package up the payload and ship it to ESA! This was done on Friday of last week.

Raspberry Pi on Twitter

The final flight @astro_pi payload has left the building! @gsholling @astro_timpeake @spacegovuk @esa pic.twitter.com/cwU9Sko7gT

The payload is now with a space contractor company in Italy called ALTEC. They will be cleaning the units, applying special ISS bar codes, and packaging them into Nomex pouch bags for launch. After that the payload will be shipped to the Baikonur Cosmodrome in Kazakhstan to be loaded onto the same launch vehicle that Tim Peake will use to get into space: the Soyuz 45S.

This is not the last you’ll hear of Astro Pi!

We have a range of new Astro Pi educational resources coming up. There will be opportunities to examine the results of the winning competition experiments, and a data analysis activity where you can obtain a CSV file full of time-stamped sensor readings direct from Tim.

Tim has also said that, during the flight, he wants to use some of his free time on Saturday afternoons to do educational outreach. While we can’t confirm anything at this stage we are hopeful that some kind of interactive Astro Pi activities will take place. There could yet be more opportunities to get your code running on the ISS!

If you want to participate in this we recommend that you prepare by obtaining a Sense HAT and maybe even building a mock-up of the Astro Pi flight unit like the students of Cranmere Primary School did to test their competition entry.

Richard Hayler ☀ on Twitter

We’ve built a Lego version of the @astro_pi flight case to make sweaty-astronaut testing as realistic as possible. pic.twitter.com/pYETedeWgn

It’s been about 25 years since we last had a British Astronaut (Helen Sharman in 1991) and we all feel that this is a hugely historic and aspirational moment for Great Britain. To be so intimately involved thus far has been an honour and a privilege for us. We’ve made some great friends at the UK Space Agency, ESA, CGI, Airbus Defence & Space and Surrey Satellite Technology to name a few.

We wish Tim Peake all the best for what remains of his training and for the mission ahead. Thanks for reading, and please watch this short video if you want to find out a bit more about the man himself:

Tim Peake: How to be an Astronaut – Preview – BBC Two

Programme website: http://bbc.in/1KgRjWC An intimate portrait of the man behind the visor – British astronaut Tim Peake. Follow Tim Peake @BBCScienceClub, as he prepares for take off. #BritInSpace

The Astro Pis are staying on the ISS until 2022 when the coin cell batteries in their real time clocks reach end of life. So we sincerely hope that other crew members flying to the ISS will use them in the future.

astropi

Columbus ISS Training Module in Germany – Image credit ESA

The post Astro Pi: Mission Update 6 – Payload Handover appeared first on Raspberry Pi.

A XSVF assembler/disassembler in python

via Dangerous Prototypes

xsvf-hex-dump-2

Marcelo Roberto Jimenez wrote an assembler/disassembler for XSVF, he writes:

As a sequence of my last project, the JTAG/XSVF library for Arduino, I felt I needed a XSVF assembler and disassembler, so that I could hack JTAG a little bit. I found that XSVF is very convenient, much more than SVF when you are dealing with a single component in the JTAG chain. I also found out that the XSVF files produced by programmers are very inefficient and full of unnecessary stuf. It would be great if I could write my own XSVF files.

Code is on github.

Details at Marcelo’s EE & CS blog.