aut viam inveniam aut faciam

Useful snippets for working with the Raspberry Pi

General information on setting up a RaspberryPi, snippets of code for working in python or bash. Mostly things i've learned for my own projects but a lot will be useful for most people starting their journey with the Pi.

Various things i've found useful for my projects using raspberry pi's, covers things from turning the red light off on the camera to kiosk mode for Chrome.

Everything here can be downloaded in the original org-mode format: Snippets of code because of the way hugo interprets org files i've had to save it with a txt extension for the link to work. If you want to view the file in emacs/org then simply change the extension to org instead of txt or copy and paste.

Table of contents   TOC

Working with files

read csv and create an array variable

# read in stored values & initialise preset values
import csv
    with open('/tmp/tmpvalues.csv', 'r') as csvfile:
        fileRead = csv.reader(csvfile, delimiter=',')
        for row in fileRead:
            SensorValues = [float(x) for x in row if x != '']
    SensorValues = (

credential file

If you dont want to store your login details in a python script, for example if you want to share that script you dont want to give people you password do you? So you can create a file credentials file eg

emacs -nw credentials.py

Then type in the following;

# email login details
em_login = {
    'smtpdata': 'smtp.server.address',
    'login': 'login.address',
    'password': 'login.password',
    'toemail': 'send.to.email.address'
# initial state details
in_login = {
    'login': 'login.address',
    'password': 'login.password',
    'accesskey': 'access.key',
    'bucketname': 'monitorhome',
    'bucketkey': 'bucket.key'

now call this file as a module in the main code and assign to your chosen variable

import credentials

empassword = credentials.em_login['password']
inpassword = credentials.in_login['password']

print("email password:", empassword)
print("initial password:", inpassword)

convert windows CR (carriage returns) to linux

sed -i 's/\r//' filename

Use with care it could destroy your file, it might be better to the dos2unix utility


Notes on using the offical pi touch screen

rotate official display

Useful if the display case you've bought has a fixed orientation;

edit your /boot/config.txt file, and add the following line:


get backlight status

Weirdly (at least i think so) it's 0 for on and 1 for off and script must be run as root

#!/usr/bin/env python3
# gets current backlight state


kiosk mode

Kiosk mode runs your internet browser full screen useful for setting up a display system. Modify the /etc/xdg/lxsession/LXDE/autostart file or if using the NOOBS installation /etc/xdg/lxsession/LXDE-pi/autostart

@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
@xscreensaver -no-splash

@xset s noblank
@xset s off
@xset -dpms

@chromium-browser --noerrdialogs --kiosk --incognito --disable-translate

BE AWARE if the following file exists then it overrides any other files so the @chromium command must go in here.

nano .config/lxsession/LXDE-pi/autostart

so edit it to show the line;

@chromium-browser --noerrdialogs --kiosk --incognito --disable-translate

so my file reads;

@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
@xscreensaver -no-splash
@chromium-browser --noerrdialogs --kiosk --incognito --disable-translate


Enabling Audio Output

By default, the RPi audio output is set to automatically select the digital HDMI interface if its being used, otherwise the analog audio output. You can force it to use a specific interface via the sound mixer controls. amixer allows command-line control of the mixer for the ALSA driver.

You can force the RPi to use a specific interface using the command amixer cset numid=3 N where the N parameter means the following:

  • 0=auto

  • 1=analog

  • 2=hdmi

Therefore, to force the Raspberry Pi to use the analog output:

amixer cset numid=3 1

How to play Internet radio on your Raspberry PI (mpd/mpc)

first make sure your audio is working, using the ALSA package

install the mpd and mpc packages:

sudo apt-get install mpd mpc

change the permissions of mpd (just to make sure):

sudo service mpd stop sudo chmod -R g+w /var/lib/mpd sudo chmod -R g+w /var/run/mpd

make a change to the mpd config file /etc/mpd.conf

sudo nano /etc/mpd.conf

Note all the sites i visited suggested that it was simply commenting OUT the line:

bind_to_address "localhost"

however i had many issues and nothing seemed to work until i had the conf file set as follows;

# bind_to_address "localhost"
bind_to_address ""
port "6600"

shutdown/reboot your Raspberry PI after it's up and running again add an Internet radio URL, for instance:

  • mpc add http://icecast.omroep.nl/3fm-bb-mp3

to start playing the stream type:

  • mpc play

The other thing to be aware of is you may need to download the radio stations m3u playlist file and open it to extract the direct URL of the stream (i had to) so the stream i needed was;


then save that into MY OWN m3u playlist for for the MPD daemon to work.

python check if mpc is playing

from mpd import MPDClient

client.idletimeout = None          # timeout for fetching the result of the idle command is handled seperately, default: None
client.connect("localhost", 6600)  # connect to localhost:6600

if client.status()['state'] in ('play', 'pause'):


no data - waiting update



for example if you get tired of typing emacs -nw to start emacs without a gui window then add

alias enw='emacs -nw'

to the end of your .profile or .bashrc file located at /home or /home/usr


Display system's serial support

dmesg | grep tty

resulting output resembles;

pi@raspberrypi:~/xbee $ dmesg | grep tty
[    0.000000] Kernel command line: dma.dmachans=0x7f35 bcm2708_fb.fbwidth=656 bcm2708_fb.fbheight=416 bcm2708.boardrev=0x3 bcm2708.serial=0xf83a1e37 smsc95xx.macaddr=B8:27:EB:3A:1E:37 bcm2708_fb.fbswap=1 bcm2708.uart_clock=48000000 vc_mem.mem_base=0xec00000 vc_mem.mem_size=0x10000000  dwc_otg.lpm_enable=0 console=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait quiet splash plymouth.ignore-serial-consoles
[    0.000718] console [tty1] enabled
[    0.201139] 20201000.uart: ttyAMA0 at MMIO 0x20201000 (irq = 81, base_baud = 0) is a PL011 rev2
[    0.201529] console [ttyAMA0] enabled
[    2.333606] systemd[1]: Expecting device dev-ttyAMA0.device...
[    2.353451] systemd[1]: Starting system-serial\x2dgetty.slice.
[    2.354181] systemd[1]: Created slice system-serial\x2dgetty.slice.
[    9.556243] usb 1-1.2: FTDI USB Serial Device converter now attached to ttyUSB0
pi@raspberrypi:~/xbee $

nginx gpg key

The distributed version of nginx is old, if you want to install the newer versions you have to self compile but first you need to take a couple of steps;

create a file;

  • sudo nano /etc/apt/sources.list.d/nginx.list

and add the line;

deb-src http://nginx.org/packages/mainline/debian/ wheezy nginx

then run apt-get update and you will receive an error stating the signatures cannot be verified, to overcome this you need the nginx keys which you can get via;

curl -O https://nginx.org/keys/nginx_signing.key && apt-key add ./nginx_signing.key

now run sudo apt-key update sudo apt-get update

and you should get no error messages meaning you can now run;

apt-get source nginx

to finally get the latest nginx source for building on your pi (set aside quite some time for it to build) and to install use

sudo dpkg -i nginx_1.9.4-1~squeeze_armhf.deb


run in background during boot

The & at the end of the line makes the script run in the background whilst the pi carries on booting @reboot sudo python /home/pi/homeApp/ourhome.py &

enable cron logging

By default, the logging for the cron daemon is not enabled in Debian To enable it, open the file /etc/rsyslog.conf via

sudo nano /etc/rsyslog.conf

and uncomment the line

cron.* /var/log/cron.log

run on reboot

to run a command on boot i use the following in the crontab file

@reboot run_command

cron sleep

Starting a command on reboot after x seconds

For some reason my pi would not wait for the wifi network to come online (wait for network on boot is enabled) so my NAS wont connect, to be honest i had other things to do than fault find so as i added an @reboot mount command with a sleep period to ensure the drive was accessible;

@reboot sleep 10;sudo mount -a

specifying the crontab editor

if like me you've accidentally set the wrong editor when first using crontab you can specify the editor everytime using the following;

export VISUAL=nano; crontab -e

alternatively you can edit the ~/.selected.editor file and change to your chosen editor;

# Generated by /usr/bin/select-editor


Static or fixed IP address

add to /etc/dhcpcd.conf

#Custom static IP address
interface eth0
static ip_address=
static routers=
static domain_name_servers=

changing eth0 to wlan0 depending on connection type and also remember to use your own choice of IP address/subnet etc


Had problems with a cron job and no idea why & at the time had not setup logging and without an MTA [Mail Transport Assistant] i could not see what errors were being given, after reading up i installed postfix

sudo apt install postfix

Choosing "LOCAL" during setup, then after a reboot i could use the following to find out what went wrong:

sudo tail -f /var/mail/<user>

alternatively you can set up a more capable system and allow your Pi to send mail using your google account

sudo apt-get install ssmtp mailutils mpack
sudo nano /etc/ssmtp/ssmtp.conf
# Config file for sSMTP sendmail

# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
# root=localhost

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com

# Where will the mail seem to come from?
# rewriteDomain=gmail.com

# The full hostname

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address


AuthPass=either password or two-factor key

Example python script for using sSMTP

# Taken and modified from an example here:
# http://tombuntu.com/index.php/2008/10/24/server-monitoring-with-python-and-ssmtp/

import subprocess, re, time
import urllib, urllib2

# email address to use in the to field
recipient = 'towhomit@mayconcern'
# email address to use in the from field
sender = 'fromwhom@sentit'
# template for the email message
# first '%s' is recipient, second is sender, third is content
message = '''To: %s
From: %s
Subject: rpiELEC IP: %s


def send_mail(content):
        ssmtp=subprocess.Popen(('/usr/sbin/ssmtp', recipient), stdin=subprocess.PIPE)
    except OSError:
        print('Error sending mail')

    # pass mail to sSMTP client
    ssmtp.communicate(message % (recipient, sender,content))

data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1)

access a network drive

Edit your /etc/fstab file and add the following line (changing the ip address and location of the credentials file to suit your setup);

// /media/nas_documents cifs credentials=/home/drakx/.nas_credentials,sec=ntlmv2,uid=1000,gid=1000,iocharset=utf8 0 0

Now create a file called .nas_credentials in your home directory



One trick i didnt learn until far too late was sshfs essentially it mounts your remote system as a folder on your desktop/laptop so instead of saving files then transfering etc you can open and load the remote files and work on them as if local. Excellent for tweaking your python website.

The line of code you need is really simple;

sshfs pi@ home/user/folder/


Most of my pi's run headless and when editing i like to use emacs so i need to type emacs -nw filename all the time. Creating an alias eases the typing

alias emacs="emacs -nw"


Disable red LED

Edit /boot/config and add the line


Recent posts


See more



former child, still love computer games & fantasy, future corpse