Friday, February 22, 2013

Your Python-Fu is Strong


This coming monday, I'll be talking about Python-Fu, or "The Gimp: how to write a plugin in 10 minutes" at the next PYPTUG meeting:

PYPTUG meeting, Monday February 25th @ 5:30pm
Wake Forest University, Manchester 241

Graphical Apps Scripting

The Gimp is not the only graphical package to have support for Python. Blender, Dia, Scribus and Maya are a few of them. I will probably cover a few of those in the future.


Friday, February 15, 2013

Python in Europe


Python trademark at risk in Europe

"For anyone who works in a company that has an office in a EU Community member state, we need your help."

So if you work for a company who uses Python, in Europe, do follow the link above and read up about how a company is trying to hijack the Python name, and what you can do to help.


Wednesday, February 13, 2013

Minecraft Pi Edition available

The RaspberryPi edition download


The install

fdion@raspberrypi ~ $ gunzip minecraft-pi-0.1.1.tar.gz
fdion@raspberrypi ~ $ tar -xvf minecraft-pi-0.1.1.tar

More detail


So, before we get started in writing some python (such as the code I put here: minecraft python ), let's check out in the mcpi/api/python/mcpi directory. It contains the types of materials that can be used:

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

That's a lot. So, next post I'll try to build something using Python with all the materials, to get a feel for what they are.


Audio numerique sur RaspberryPi


Pour que le Raspberry Pi coute le moins possible, certaines décisions on du être prise. Par exemple, il n'y a pas de CODEC analogique - numérique. De sorte que l'audio se joue par soit:

1) le port HDMI - audio numérique passée directement au téléviseur ou a l'ampli intégré avec décodeur DTS, dolby digital, master audio etc... Si on utilise le Raspberry Pi comme serveur de media, c'est parfait. Mais si on ne peut utiliser le port HDMI?

2) le port 3.5mm analogique - l'audio est générée par PWM (Pulse Width Modulation). Avec une fréquence suffisamment élevée, on peut arriver a 16 bit de résolution, comme les convertisseurs plus conventionnels. Dans le cas du Raspberry Pi toutefois, la résolution est un peu moindre. En plus, il y a un problème avec le pilote ALSA, de sorte que le son n'est pas vraiment... a la hauteur.


Tout n'est pas perdu. En effet, on peut se procurer une carte son sur USB:
Mini PCM2704 USB sur ebay (A noter que le prix est a la hausse, de $4.00 par rapport a ce que j'ai payé ...).

C'est géré par le Raspberry Pi: 

$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 0424:9512 Standard Microsystems Corp.
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp.
Bus 001 Device 004: ID 08bb:2704 Texas Instruments Japan

Et ça donne une sortie analogique 3.5mm de qualité (super sur casque d’écoute), une sortie SPDIF rca numérique et une TOSLink optique numérique.
de USB a SPDIF, TOSLink et 3.5mm analogique

Illusion d'optique

Dans mon cas, je saute le DAC. J'utilise la carte son comme interface numérique optique, qui se relie a un processeur de son numérique Technics SH-AC500D (qui lui se branche a un ampli):

Le processeur de son est sur le dessus

La lumiere au bout ... de la fibre
On branche la fibre sur un des ports TOSlinks

Le soft

mpg123, aplay et d'autres lecteurs audio qui utilisent ALSA vont fonctionner avec la carte, mais il faut effectuer un changement a un fichier de configuration:

$ sudo vi /etc/modprobe.d/alsa-base.conf

et sur la derniere ligne, on change le -2 par un 1:

options snd-usb-audio index=-2
options snd-usb-audio index=0 nrpacks=1
et on reboot.


Thursday, February 7, 2013

sudo ./

Tron, Laser, Lissajous, RaspberryPi

Am I throwing together random words for titles now, in a weird captcha induced moment? No,  just condensing my interest in lasers in a few words.

You might have seen the laser digitizer in Tron: Legacy

However, in my case, what triggered my interest in laser, was the original Tron laser digitizer

A few years later, I had the chance to play with a good old HeNe red laser, pumping a mighty 5mW (well, in the 80s, it was impressive) in the college lab. One of the things I did with it was to draw Lissajous figures (or curves) on a wall (a large wall outside, at night - even cooler), using two little speakers and mirrors I had brought (the lab was set up to only do prism and mirror experiments).

Googling, I see a nearby school (Appalachian State) has one such kit in their physics dept:

Anyway, fun stuff, making math and physics a lot more interesting...


There was the artistic connection that also further fueled my interest in lasers. There is a lot to talk about here, since I've composed and performed electronic music for many years (still write some) and hosted a radio show for about 10 years etc, so that'll be for another time.

I will bring up one point right now though: you cant talk about lasers in music shows, without mentioning Jean Michel Jarre.

Jean Michel Jarre, Houston TX 1986
From his incredible live outdoor shows with lasers, lights and fireworks (one, a tribute to oceanographer Cousteau, had an attendance of over 2 million people in France in 1990) to his laser harp. Jarre without lasers wouldn't be the same.

On the road

The Raspberry Pi has a lot of appeal by itself, but I figured that it would probably be a good idea to add a laser in the mix. Since I had a presentation at PyCarolinas, I figured I'd write a script with Python (, hence the title of this article) and build a little rig to project interesting patterns on the wall behind me.

My 50mW laser rig (also 500mW for day use)

The code for the pulsing is basically what is found in the RPI.GPIO dot dash article, and for the motor, in the 2bit H bridge article and PWM article.

So, using a laser in presentations, does it work? Well, at PyCarolinas, I got a lot of feedback on this, both during the presentation, after the presentation and even during other talks (heard during another talk "so we've learned today that lasers are cool")

In the audience: "I just want to say that this is the coolest command, ever."

On twitter:

Calvin Spealman
sudo with actual lasers! #pycarolinas
08:45 PM - 21 Oct 12

And so on and so forth. The conclusion is this: Science needs some showmanship. But please, be careful when playing with lasers!


So I'll leave you with a video of my little rig above controlled by the Raspberry Pi, going to the music of a very British band, doing a cover of the theme of a very British TV show. Very apropos, since the Raspberry Pi is a very British computer, afterall.

Youtube video (Music by Orbital, Doctor? live at BBC)

[edit] I fixed the youtube link



de RaspberryPi a SD

Il y a un certain challenge a faire une carte SD pour le Raspberry Pi.

Ceci est du en partie a la grande variété de systèmes d’opération et d'ordinateurs (et leur matériel). D'autre part, beaucoup de personnes n'ont que le Raspberry Pi comme ordinateur, les autres étant hors de portée du au prix.

Il y a certains groupes d'usagers ici et la qui se débrouillent pour aider les usagers a faire leur propre carte SD, alors que d'autres doivent acheter des cartes SD avec le système d’opération déjà installé. Mais comment faire pour faire une copie de cette carte SD, n'est on pas de retour a la case départ?

Le lecteur

En fait, une fois que l'on a un système d’opération  sur la carte SD, on peut alors faire de l'autoréplication. Quésaco? me direz vous... Et bien, c'est quand un système d’opération peut se répliquer lui même (faire une copie de carte SD seulement avec le Raspberry Pi).

Pour ce faire, il faut un lecteur de carte SD, car le Pi n'a qu'une seule fente SD. Un lecteur comme celui ci, par exemple (ici, avec une carte 16GB, mais on peut faire 4GB ou 8GB ou plus, de la même façon):

Et on le branche (avec un câble ou en direct) au port USB.


La version la plus recente de Raspbian Wheezy est de Decembre 2012:

Ici, les instructions se basent sur une version plus vieille, mais c'est le meme principe. Il suffit de remplacer l'url par une de cette liste ici (choisir un serveur plus pres de soi):

Avant de commencer, il faut s'assurer d'avoir au moins 2.5GB de libre (df -h me donne 2.9G ici). On insere la carte SD vide dans le lecteur et on verra apparaitre /dev/sda ou sdb.

fdion@raspberrypi ~ $ df -h
Filesystem      Size  Used Avail Use% Mounted on
rootfs           15G   11G  2.9G  80% /
/dev/root        15G   11G  2.9G  80% /
devtmpfs        109M     0  109M   0% /dev
tmpfs            22M  248K   22M   2% /run
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs            44M     0   44M   0% /run/shm
/dev/mmcblk0p1   56M   35M   22M  62% /boot
fdion@raspberrypi ~ $ wget
fdion@raspberrypi ~ $ unzip
fdion@raspberrypi ~ $ ls /dev/sd*
ls: cannot access /dev/sd*: No such file or directory
fdion@raspberrypi ~ $ ls /dev/sd*
ls: cannot access /dev/sd*: No such file or directory
fdion@raspberrypi ~ $ ls /dev/sd*
/dev/sda  /dev/sda1
fdion@raspberrypi ~ $ ls *.img

Ici, le lecteur de carte avec SD est /dev/sda (si c'est sdb, il faut ajuster la commande ci dessous avec of=/dev/sdb). On est pret a faire la copie de l'image de la carte SD (le fichier .img), a partir du Pi (on peut aussi utiliser bs=4M qui va beaucoup plus vite avec certaines cartes):

fdion@raspberrypi ~ $ sudo dd bs=1M if=2012-09-18-wheezy-raspbian.img of=/dev/sda
1850+0 records in
1850+0 records out
1939865600 bytes (1.9 GB) copied, 428.218 s, 4.5 MB/s
fdion@raspberrypi ~ $ sudo sync

Le sudo sync est très important. Si on ne le fait pas, ça ne fonctionnera pas.

Et c'est tout! On peut maintenant donner cette copie a une autre personne. Tres pratique pour les clubs.

Il existe aussi une méthode pour faire une copie, sans utiliser de fichier .img, mais cela sera pour une autre fois...


Tuesday, February 5, 2013

Improved Pi-A-Sketch video

Mighty RaspberryPi drawing

I've made a new video of the Pi-A-Sketch:

youtube page

Not quite as circular

One thing you will notice is that the circles have a kink on each sides (at the interface of each quadrant). With time, it appears that the compensation factor for the slop has to be adjusted. I've demoed this so much that I guess there is a little less slop than there was before. That is quite curious. It also means that I will have to add a calibration mode, perhaps a little jumper or switch, and when the Pi boots, it will run the calibration mode instead of the drawing mode.

This will definitely increase the code in a significant way (currently less than 200 lines of Python)


100000th visit

Raspberrypi and Python

Seems like yesterday when I thought this would make a great combo, but it was in fact February 2012. I eventually got my first Raspberry Pi in June of last year, and then after a few months, I thought, I'm having a ton of fun with this, I should probably post this online.

I started this blog less than 6 months  ago, and considering how this blog is fairly technical, I didn't expect a lot of visitors. Plus, by having multiple languages mixed in, there was a definite possibility that it would make it even more out of reach of many. Still, the motivation was to help people learn more about Python, about the Raspberry Pi.

The visitor 

Yesterday, I saw the stats for my blog, and thought, wow, is that possible, I'm about to reach a nice milestone. I have to catch where that 100,000th visit will come from. Brought up the Analytics while tracking the visits, and it looks like that 100,000th visit came from King of Prussia, PA. That was an interesting coincidence, as this was the last city I knew that the friend I mentioned in the article going in the wrong direction lived in. We live in such a connected society, yet we can still somehow manage to lose connections.

King of Prussia, PA

Going back to our story, of course, Analytics only provide you the city of the internet provider, so I don't really know where this visit really came from...


Gráficos en la consola

Pygame, RaspberryPi, Webcams.

Pygame utiliza SDL para los gráficos, así que soporta directamente la consola o X windows. Es el caso en todas la plataformas (Unix, Linux, Mac, no solo en Raspbian sobre el RaspberryPi).

Si no conocen nada de Pygame, hay tutoriales en espanol aqui:

En mi caso, necesitaba código para capturar imágenes de una webcam (por un taller PyHack). con Python y Pygame, es muy sencillo. Hacer el import y init de los modulos, crear un objeto cam (de resolución 320x240), iniciar la camara, obtener una imagen (cam.get_image), y grabar como png.

import pygame
import  # experimental
from pygame.locals import *


cam ="/dev/video0", (320,240))  # webcam

image = cam.get_image(),'fablocker.png')

El mismo código funciona en la consola o el escritorio, perfecto con los cron jobs.


Hay otros módulos Python que dependen de un servidor X windows. En casos de que no se require OpenGL (no hay en Raspberry Pi) o OpenGL ES, hay un servidor basico que podemos utilizar: xvfb.

Primeramente hay que hacer la instalación de xvfb:

$ sudo apt-get install xvfb

Matplotlib es bueno para hacer imagenes y incluirles en informes de actividad de servidor, por ejemplo. Un servidor web no requiere X windows, asi que porque deberiamos utilizar LXDE o otro escritorio grafico, solo por hacer imagenes que vamos a incluir en una pagina web?

Con xvfb, no hay problemas. Un script que contiene el código Python siguiente (poner en un fichero

from matplotlib.pyplot import *


Es lo que haria normalmente. Pero si tratamos de ejecutar el script directamente, vamos a recibir un error. A utilizar xvfb, eliminamos el error, así:

$ xvfb-run python
  Va a generar un fichero graph.png que se vera asi:

Todo de la consola, sin escritorio gráfico.


Friday, February 1, 2013

Making your own RaspberryPi GPIO cable

Example of a DIY circuit, connected by DIY cable

One feature that has contributed to the Raspberry Pi's success is the possibility of interfacing the virtual (software) with the physical world. We are speaking of course of the "General Purpose Input and Output" pins, more commonly known as GPIO. They are available on the Pi at the P1 connector.

Making a GPIO cable

We are doing some green computing today! We are going to recycle some old computer cable and make a Raspberry Pi interface cable with it. We will then be able to connect motors, LEDs, buttons and other physical components.

The interface cable is a flat cable with 26 conductors. It is quite similar to an IDE hard disk cable (or ATA) with 40 conductors (avoid the ATA66/133 with 80 conductors):

Original IDE/ATA cable with 40 wires

Let's get to work

We will only need 2 connectors on our interface cable and not 3. With a cable with 3 connectors, we just need to cut one section off.

Cutting it with a pair of scissors

Before doing the cutting, we will do some marking. The reason is that we only need 26 wires, and we have 40. With the red wire on the left, we have to count 26 wires and mark the split with a fine permanent marker. We count on the right side to make sure we do have 14 conductors, not a single one more or less.

Using a permanent marker to write
We are going to divide the cable in two parts, using an x-acto style knife or scalpel: one with 26 wires and one with 14 wires.

splitting in two parts

We then have to cut one section of the connectors off, with a small saw, such as a metal saw (or a Dremel style cutting wheel).

we need to cut on the 7th column from the right

We remove the top part, then the cable section with 14 wires, and finally, after notching it, we remove the bottom part.

almost done, just remove the part on the right

We are done with the cutting. We can now connect the cable to the Raspberry Pi. The red wire is closest to the SD card side, and farthest from the RCA video out (yellow connector):


With the cable ready, we are now going to test it. Let's add 2 LEDs to do this test. We will use a red and a green LED, but you can use amber or yellow LEDs too. Blue, violet or white LEDs will not work, since they need more voltage.

The connection is really simple:

Red LED and green LED, short leg -> third hole on the left.
Red LED, long leg -> second hole on the right
Green LED, long leg -> third hole on the right

Python Code

First thing first, you have to get the  RPi.GPIO  Python module.  It is a module that will allow us to control the GPIO of the Raspberry Pi. On Raspbian, it is now included, but for another version of Linux, it can be installed with

sudo easy_install RPi.GPIO

Or through apt-get  (or equivalent package manager):
$ sudo apt-get install python-rpi.gpio
Here is the code:
#!/usr/bin/env python  
""" Setting up two pins for output """  
import RPi.GPIO as gpio  
import time  
PINR = 0  # this should be 2 on a V2 RPi  
PING = 1  # this should be 3 on a V2 RPi  
gpio.setmode(gpio.BCM)  # broadcom mode  
gpio.setup(PINR, gpio.OUT)  # set up red LED pin to OUTput  
gpio.setup(PING, gpio.OUT)  # set up green LED pin to OUTput 
#Make the two LED flash on and off forever  
    while True:  
        gpio.output(PINR, gpio.HIGH)  
        gpio.output(PING, gpio.LOW)   
        gpio.output(PINR, gpio.LOW)  
        gpio.output(PING, gpio.HIGH)  
except KeyboardInterrupt:

Just save the code into a file named

  • PINR is the GPIO for the red LED (0 for Rpi V1 and 2 for V2)
  • PING is the GPIO for the green LED (1 for Rpi V1 and 3 for V2)
We select the Broadcom mode (BCM), and we activate the 2 GPIO as output (OUT). The loop will alternate between the red LED on / green LED off during 1 second, and red LED off / green LED on during one second ( time.sleep(1) ). By doing a CTRL-C during execution, the program will terminate after cleaning up after itself, through the gpio.cleanup() call.

Running the code

Usually, a LED should be protected with a resistor to limit the current going through it, but in this case it will blink intermittently, just to test the cable, so we don't need any.

For continuous use, it is recommended to put a resistor in series (about 220 Ohm to 360 Ohm).

Before we can run the program, we have to make it executable:
$ chmod +x
$ sudo ./
CTRL-C will stop the program.


Green LED
This concludes our article. I hope it was satisfying making this cable and recycling at the same time.

The follow up to this will be about making our own breadboard adapter, and having fun with a transistor.


Nouvelle publication DIY


Un nouveau magazine vient de paraitre, il s'agit de Fait Main, un magazine collaboratif en ligne et en PDF:

On y retrouve divers sujets autour du DIY("Do It Yourself"), et dans ce premier numéro, on y parle bien sur de Raspberry Pi.

J'ai écris l'article "câble d'interface pour Raspberry Pi" Lire l'article 

Mais ce n'est pas tout: 

Contenu du volume 1

La tribune de ce numéro est un parallèle entre web hébergé et OGM. Lire la tribune 

Le premier article présente une application de reconnaissance de feuille écrite pendant un Hackathon. C'est l'application qui a été écrite en 24 heures par Olivier, Ronan & Tarek lors du dernier AngelHack à Paris. On y parle de machine-learning au service des plantes, des hackathons de programmation & de responsive design . Lire l'article

Le deuxième article parle de domotique et vous explique comment piloter des dispositifs sans fils - portails, détecteurs de mouvements etc. On y parle d' Arduino , de Raspberry-PI et de signal en 433 mhz . Lire l'article 
Le troisième article présente le travail de Marcin Ignac: des méduses animées en 3D. Des captures d'écran de ces méduses ont ensuite été utilisées pour faire partie d'un projet de livre génératif. On y parle d' animation procédurale , de processing.js & d'hachurage. Lire l'article

Le quatrième article vous donne 5 conseils de photos culinaires pour que vous puissiez prendre en photos vos soupes, gigots et autres desserts comme un(e) pro. Lire l'article 

Suit une interview de Hugues Aubin au LabFab de Rennes. Lire l'article .

Un cinquième article sur la conception d'un Juke box avec un Raspberry-PI, sans aucune soudure requise :) Lire l'article 

Le sixième article vous explique comment recycler une vieille nappe de disque dur pour connecter le GPIO de votre Raspberry. Lire l'article 

Le septième article est une rapide présentation du jeu The Midst , conçu avec Processing et WebPD. Lire l'article 

Enfin, le huitième article aborde les bases du fonctionnement d'une CNC. Lire l'article 
Bonne Lecture!
— Tarek


Le projet FaitMain est monté par Tarek Ziadé mais est surtout possible grâce aux créateurs d'articles et aux relecteurs.

Ont participé à ce numéro :

RaspberryPi talk @ForsythTechCC


I'll be giving the talk "Raspberry Pi: From Kindergartners To Mad Scientists" at ForsythTech in Winston Salem, NC this coming Monday at 5:30pm (Feb 4th), and Thursday at 3pm (Feb 14th). It will be in the Hauser building, room 332.

Old school flyer

Just got a copy of the flyer:

It's that $25 computer talk

Each time I give this talk somewhere, it ends up quite different from the previous one. In part due to questions, and in part because I adjust the content to the target audience.

Should be fun, there is interest from several programs, so I'll cover a wide range of material.


New DIY publication


It is a collaborative magazine that is both online and in PDF format. It was just launched this morning. It is in french.

 So why am I talking about it in english?

Because one of the article from the publication will be available on my blog, a little later. This is just a heads up.

How to make your own cable

The Raspberry Pi has a connector with a bunch of pins, and it is taunting you!  Make good use of it by recycling an old IDE hard disk cable. The article will also show you how to test it with some Python code.

The article in French on  faire un cable gpio

The article in Portuguese on this blog: fazer um cabo gpio

I'll update this post when the English version is available, and add it also to the tutorial section

[UPDATE] The article in english: making a gpio cable