OpenElec on the Raspberry Pi

OpenElec on the Raspberry Pi

The Home Theatre PC (HTPC) software distribution from OpenElec.tv is currently the easiest way to get high definition videos to play on the Raspberry Pi. Not only can you play your own videos from Windows or NFS shares, but by using add-ons you can stream video from many web sites. I previously have posted about OpenElec and some other distributions available for the Raspberry Pi in How the Raspberry Pi Spins. Recently, I posted about Playing HD Videos in Debian on the Raspberry Pi, which unlike XMBC does not provide a convenient way of browsing or creating play lists.

This post covers how to get started using OpenElec. First, it will cover how to download, extract and install it to your sd card. Next, it covers how to login remotely. For the security conscious, the next topic covers how to update the passwords on the system, or any other files on it's squashed root file system. A couple of Video Add-ons are also discussed. Finally, last but not least it explains how to calibrate your video output.

How do you install it?

The version of OpenElec for the Raspberry Pi does not appear on the http://openelec.tv/get-openelec page. At the bottom of that page is a link to Official Daily Builds, and on that page is the directory for openelec-rpi.  When you look at the filenames, they include the date of the build. The most recent one that works for me, including Video Add-ons, was built 2012-06-14. The two that were built on 2012-6-23, did not allow me to use Video Add-ons.

How do you login?

The console automatically logs in to the XMBC interface to be able to view or hear media, and to configure the system as well. Despite what the /flash/README.md file says, SSH is enabled in the build that is covered in this post.

From a remote machine, it is possible to login as the root user using SSH. Since OpenElec advertises using Avahi (ZeroConf), most systems should be able to resolve it's name as openelec.local. Otherwise, you can use the console to discover your network address under System Info. Windows users may want to install Putty to be able to have SSH capabilities.
  • ssh root@openelec.local
  • ssh root@ # address found in System Info

login: root
password: openelec

What if you want to change the password(s)?

The busybox executable that provides most of the commands for OpenElec does not have a passwd command, and the root file system is a read-only mounted squashfs file system. So, while you are running OpenElec, you cannot change the password. 

One way to set the password is to build OpenElec yourself, but I have an easier way. It is still not easy, but if you want to be able to have a secure system, then it is important to do.

First, you have to have squashfs-tools installed on your Linux system, then you can use the following procedure to change the password without having to rebuild OpenElec.  
  • Become the root user and make some directories to mount file systems
    • sudo su -
    • mkdir /openelec
    • cd /openelec
    • mkdir flash original updated newsquashfs
    • cd /
  • Insert the SD card with OpenElec installed on it and determine it's name
    • fdisk -l 
    • Should be the last device listed, in my case /dev/sdb
  • Mount the flash partition 
    • mount /dev/sdb1 /openelec/flash
  • Mount the squashfs SYSTEM file from the flash partition with loop option
    • mount -o loop /openelec/flash/SYSTEM /openelec/original
  • Copy the original root file system to /mnt/updated
    • cp -a /openlec/original/* /openelec/updated
  • (Optionally) Create a new user whose password you will use
    • useradd username
  • Set a password for this username
    • passwd username
  • Extract the password for the /etc/shadow file for the username
    • grep username /etc/shadow | cut -f2 -d:
  • Select and copy the password 
    • Use the mouse to select 
    • Right click, Copy or CTRL+SHIFT+c
  • Edit the updated file system shadow file
    • I use vim, but any editor will do: 
      • vim /openelec/updated/etc/shadow
    • On the line that starts with root, replace what is between the first and second colon(:) with what you have copied. (Right click, Paste or SHIFT-INSERT)
    • Save your changes
  • Edit any other user's passwords, or any other files you want to update. I also changed the password for the openelec user.
  • Make an updated squashfs SYSTEM file
    • mksquashfs /openelec/updated/  /openelec/newsquashfs/SYSTEM
  • Unmount the original SYSTEM squashfs file
    • umount /openelec/original 
  • Copy the new SYSTEM file over the old file 
    • cp /openelec/newsquashfs/SYSTEM /openelec/flash/SYSTEM
  • Unmount the flash partition
    • umount /openelec/flash
  • (Optional) Clean up the /openelec directory
    • rm -rf /openelec

What Video Add-ons?

In a working build, if you go to Videos, then Video Add-ons, Get More, then you can select numerous Add-ons to view videos from many sites. In the past, I was able to get the You Tube add-on working. Despite it warning me that the You Tube add-on was broken, everything I tried worked, although slowly.

I have also installed a video add-on for the Khan Academy. The Khan Academy has tons of educational videos nicely organized by this add-on. This could be another great way to use your Raspberry Pi for educational purposes.

How to Adjust the Video Output?

One of my early grievances with using OpenElec was that the video was not synchronized properly to my television. I discovered that it is easy to correct this problem. Simply navigate to the System, Settings, System, Video Output. Here you can change the Resolution, Refresh Rate, Vertical blank sync, Video calibration, Test patterns, and Enable LCD/VFD. 

Shortcut to video calibration:
  • While watching a video, move the mouse so the controls appear
  • Click on the icon in the lower right corner that looks like a film reel
  • Choose video calibration from the menu
Here's how to perform the video calibration:
  • Top left corner
    • The process begins by using the up and down arrows to align the top edge of a blue right angle. I had to press down many times before I even saw the blue right angle in the upper left corner of the screen. Next, use your right and left arrow keys to align the left edge of the blue right angle to the left edge of the screen. 
    • Press Enter
  • Bottom right corner
    • Aligning the bottom right corner of the screen with your arrow keys like the top left corner was aligned
    • Press Enter
  • Subtitle position
    • Use the up and down arrows to move the position of subtitles up or down the screen
    • Press Enter
  • Pixel adjustment ratio
    • Adjusting the width of the rectangle to make it a square can be done two ways
      • Hold down mouse button 1, and drag left or right and release when correct
      • Press left or right arrow keys
    • Press Enter
  • Press the ESC key to return to the menu 


Python on the Raspberry Pi: Leap Year Module

Python on the Raspberry Pi: Leap Year Module

I mentioned in the first Python on the Raspberry Pi: Numbers and Dates that I if I had an advanced student, I might have created a function for the pseudo code that was posted at Wikipedia about leap years. This post describes settings that are appropriate for vim for use as an editor for Python, the algorithm used for calculating a leap year, and how to use a module called leapyear, stored in a file called leapyear.py. This file is available for download at https://github.com/wrightrocket/PythonOnTheRaspberryPi.

Vim Settings for Python  

I like to use vim to edit in a terminal, but I create a ~/.vimrc file to add some settings that make it work well for Python. Of course, you can use an editor you like, but be careful not to mix tabs and spaces for creating your indentation.

These settings for vim set the width of a tab to four spaces, but convert any new tabs to spaces automatically.

My ~/.vimrc:
set expandtab  
set tabstop=4 
set list       
set backup 

Leap Year Algorithm

The Algorithm came from a WikiPedia article found at http://en.wikipedia.org/wiki/Leap_year. This is implemented in the leapyear.py file as the function named isLeapYear(). 

if year modulo 400 is 0 then 
else if year modulo 100 is 0 then 
else if year modulo 4 is 0 then 

In the directory where you start Python (or on the PYTHONPATH) create a file named leapyear.py containing the following code:

''' Module provides a simple function to test whether a year is a leap year'''

def isLeapYear(year):
    ''' Returns True if a year is a leap year, otherwise False 

    This function first checks the passed value of year to ensure to that is an Integer.
    It then tests the year to see if it is a Leap Year according to the algorithm 
    expressed in the pseudo-code found at http://en.wikipedia.org/wiki/Leap_year '''

    if type(year) is not int:  #  verifying year is an int (Integer) object
        # if year is not an Integer then return False
        # print year, "is a not an Integer, so unable to check if it a leap year"
        return False
    else:  # This is where the pseudo-code of the function begins
        if not (year % 400):  
            # zero is considered False
            return True 
            #  if year / 400.0 has zero remainder then is a leap year
        elif not (year % 100):
            return False  
            # if year / 100.0 has zero remainder than is not leap year
        elif not (year % 4):
            return True  
            # if year / 4 has zero remainder and both above are not true
            return False  # otherwise it is not a leap year

def test_isLeapYear():
    ''' Display a range of leap years from 1752 to 2012 '''
    print "\nPrinting the the list of leap years from 1752 to 2012:"
    years = 0
    for year in range(1752, 2013):
        # start the year at 1752, when they began and go to 2013 - 1
        if isLeapYear(year):
            print year, 
            # don't add a new line by using trailing comma
            years += 1
            # add one to the years variable
            if not (years % 10):
                # every 10 leap years print a new line
            # do nothing instead of printing years that are not leap years
            # print "%s IS NOT a leap year" % year
        # when through with the loop finish the line of print

def test_logic_isLeapYear():
    ''' This function tests every branch of isLeapYear() to verify logic 

    If this function raises an AssertionError then the logic of isLeapYear() 
    is not working correctly according to pseudo-code for calculating 
    Leap Years found at http://en.wikipedia.org/wiki/Leap_year'''

    print "\nTesting each branch of isLeapYear for accurate results:"
    print "Is the year 2000 a leap year? Why, or why not?", isLeapYear(2000)
    # 2000 modulus 400 is 0, so it is a leap year
    assert isLeapYear(2000)
    # if isLeapYear returns False, then this assertion will halt execution
    print "Is the year 1800 a year year? Why, or why not?", isLeapYear(1800)
    # 1800 modulus 400 != 0, and 1800 % 100 == 0, so it is not a leap year
    assert not isLeapYear(1800)
    # if isLeapYear returns True, then this assertion will halt execution
    print "Is the year 2012 a leap year? Why, or why not?", isLeapYear(2012)
    # 2012 % 400 != 0, 2012 % 100 != 0, but 2012 % 4 == 0, so it is a leap year
    assert isLeapYear(2012)
    # if isLeapYear returns False, then this assertion will halt execution
    print "Is the year 2013 a leap year? Why, or why not?", isLeapYear(2013)
    # 2013 % 400 != 0, 2013 % 100 != 0, and 2013 % 4 != 0, so not a leap year
    assert not isLeapYear(2013)
    # if isLeapYear returns True, then this assertion will halt execution

if __name__ == '__main__':
    # when not being imported execute the following block of code

Execute a Module from the command line:

When the module is executed directly, and not being imported, then it will execute the code indented underneath if __name__ == '__main__':

pi@raspberrypi:~/PlayingWithPython$ python leapyear.py 

Printing the the list of leap years from 1752 to 2012:
1752 1756 1760 1764 1768 1772 1776 1780 1784 1788
1792 1796 1804 1808 1812 1816 1820 1824 1828 1832
1836 1840 1844 1848 1852 1856 1860 1864 1868 1872
1876 1880 1884 1888 1892 1896 1904 1908 1912 1916
1920 1924 1928 1932 1936 1940 1944 1948 1952 1956
1960 1964 1968 1972 1976 1980 1984 1988 1992 1996
2000 2004 2008 2012

Testing each branch of isLeapYear for accurate results:
Is the year 2000 a leap year? Why, or why not? True
Is the year 1800 a year year? Why, or why not? False
Is the year 2012 a leap year? Why, or why not? True
Is the year 2013 a leap year? Why, or why not? False
pi@raspberrypi:~/PlayingWithPython$ chmod a+x leapyear.py
pi@raspberrypi:~/PlayingWithPython$ ./leapyear.py

Printing the the list of leap years from 1752 to 2012:
1752 1756 1760 1764 1768 1772 1776 1780 1784 1788
1792 1796 1804 1808 1812 1816 1820 1824 1828 1832
1836 1840 1844 1848 1852 1856 1860 1864 1868 1872
1876 1880 1884 1888 1892 1896 1904 1908 1912 1916
1920 1924 1928 1932 1936 1940 1944 1948 1952 1956
1960 1964 1968 1972 1976 1980 1984 1988 1992 1996
2000 2004 2008 2012

Testing each branch of isLeapYear for accurate results:
Is the year 2000 a leap year? Why, or why not? True
Is the year 1800 a year year? Why, or why not? False
Is the year 2012 a leap year? Why, or why not? True
Is the year 2013 a leap year? Why, or why not? False

Import the Module into the interpreter:

The way a module is used from other modules, or in the interpreter is to use an import statement. In the case of importing a module, the code indented underneath if __name__ == '__main__': is not run. 

First the whole module is imported into the main namespace. Accessing functions of the module will require modulename.functionname. 

Next, a function is directly imported into the namespace. The function can be accessed directly like Python's own built in functions.

The use of help(module), help(module.function) and help(function) demonstrate how to view the '''docstrings''' used when creating a module or function. 

The use of dir() illustrates how to view the main namespace. The use of dir(module) how to view the namespace of a module. 
pi@raspberrypi:~/PlayingWithPython$ python
Python 2.7.3 (default, Jun 18 2012, 16:19:55) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> import leapyear
>>> leapyear.isLeapYear(2012)
>>> dir(leapyear)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'isLeapYear', 'test_isLeapYear', 'test_logic_isLeapYear']
>>> help(leapyear)
>>> help(leapyear.isLeapYear)

>>> leapyear.test_isLeapYear()

Printing the the list of leap years from 1752 to 2012:
1752 1756 1760 1764 1768 1772 1776 1780 1784 1788
1792 1796 1804 1808 1812 1816 1820 1824 1828 1832
1836 1840 1844 1848 1852 1856 1860 1864 1868 1872
1876 1880 1884 1888 1892 1896 1904 1908 1912 1916
1920 1924 1928 1932 1936 1940 1944 1948 1952 1956
1960 1964 1968 1972 1976 1980 1984 1988 1992 1996
2000 2004 2008 2012
>>> leapyear.test_logic_isLeapYear()

Testing each branch of isLeapYear for accurate results:
Is the year 2000 a leap year? Why, or why not? True
Is the year 1800 a year year? Why, or why not? False
Is the year 2012 a leap year? Why, or why not? True
Is the year 2013 a leap year? Why, or why not? False
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'leapyear', 'sys']
>>> from leapyear import isLeapYear
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'isLeapYear', 'leapyear', 'sys']
>>> help(isLeapYear)
>>> isLeapYear(2000)
>>> isLeapYear(1800)
>>> import this

By creating a file called leapyear.py, we created a module. By using python on the command line, we were able to execute this module in the __main__ namespace. By using an import modulename statement, we were able to import name of the module into our  __main__ namespace. We were then able to reference the functions by using modulename.functionname. By using a from modulename import functioname, we were then able to access the functioname directly, or in or __main__ namespace. Finally, by using 'import this' we have uncovered a Python 2 Easter Egg.


Python on the Raspberry Pi: Numbers and Dates

Python on the Raspberry Pi: Numbers and Dates

The very reason for being for the Raspberry Pi is to be able to use it to teach kids. By having a computer inexpensive enough to widely distribute them to schools, the The Raspberry Pi Foundation  hopes to be able to teach many young people about computers.

Python is both powerful and easy to understand as a programming language. Python is used by many educators to introduce programming to students.

While I am enjoying learning and sharing what I have learned about my Raspberry Pi on blogspot, I am also attempting to teach an eleven year old boy, Chris, about computer science, as well.

In this post, I will be sharing my first actual Python session that I guided Chris through. We start out calculating our ages in years, and then in days. We covered the basic use of a variable to store values in names that we can reference. Finally, we took a look at a precise way to calculate our ages in days by using the datetime module. Here are some things to note:

  • (#) Comments starting with a # are made where I typed the next line
  • (##) Comments starting with ## are made where Chris was supposed to type the line
  • The dates have been changed, but are close enough
  • Many error in our typing have been removed

To get started, if you are in the GUI (startx), then open the terminal. If you are on the command line only, then your are ready to go!

pi@raspberrypi:~$ python
Python 2.7.3 (default, Jun 18 2012, 16:19:55)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

# How many years old am I?
>>> 2012 - 1966
# So, how about many days old does that make me?
>>> 46*365
## About how many years old are you?
>>> 2012 - 2001
## So, how many days old are you?
>>> 11*365

# One of the cool things about Python is it can use variables, as names to store values.
# If I wanted to remember how many days old I am, I could store it in a variable called keithdays
>>> keithdays=46*365
>>> keithdays
## What would good be a good variable name to use to store how many days old you are?
>>> chrisdays=11*365
>>> chrisdays

# Why would we want to have Python remember a value for us?
# So, we wouldn't have to remember ourselves or have to type those values in again like:
>>> 16790/4015
>>> 46/11
# Oh, we noticed Python pushes the value down to the floor, or rounds it down.
# It won't in other cases though. If we do operations with decimals, it won't.
>>> 46/11.0

# Back to the variables, if I wanted to know about how many more times old I am than you, I could use:
>>> keithdays/chrisdays
## So, if we wanted a variable to store your Mom's age in days, how would you do it?
>>> momdays = 47*365

## How can you view that value?
>>> momdays
# You can also ask Python to print a value or a variable
>>> yeardays=365
# You can assign the value from one variable to another, especially for a shorter name
>>> y=yeardays
>>> print yeardays

>>> print y

## What is the value of y?
>>> y
## How do you print the value of yeardays?
>>> print yeardays
# See now we can use this variable along with numbers or other variables to do calculations
>>> 10 * y
>>> 10 * 365
## Try to use y in a calculation
>>> 100 * y
# Reminds Chris about how multiplication with factors of 10s is an easy pattern to follow
# What if you multiply y by 1000?
>>> 1000 * y

# Let's do some calculations with variables that have long descriptive names that later on will be clear
>>> daysPerYear = 365
>>> chadiAgeYears = 14
>>> chadiAgeYears * daysPerYear
## Create a variable to store Chadi's age in days.
>>> chadiAgeDays = chadiAgeYears * daysPerYear
>>> chadiAgeDays
## Create a variable to store how many days in a week.
>>> daysPerWeek = 7
## Calculate Chadi's age in weeks
>>> chadiAgeWeeks = chadiAgeDays / daysPerWeek
>>> chadiAgeWeeks

# Does this value make sense, I might double check it like:
>>> 730*7

# Is Chadi really that many days old. Do you remember some years we have a leap year?
# This went off on a whole tangent about leap years and http://en.wikipedia.org/wiki/Leap_year
# (If I had a more advanced student, I would be tempted try a Python function for the pseudo code)
# (update: function is posted in Python on the Raspberry Pi: Leap Year Module)
# So, given Chadi's age, how might we calculate how many leapDays?
>>> leapDays = chadiAgeYears * 1/4
>>> leapDays
>>> 14/4

>>> 14/4.0
## Instead of using 1/4.0, what might we do instead?

>>> leapDaysPerYear = 1/4.0
# Remember the decimal is added to avoid the rounding.
>>> 1/4
>>> 1/4.0
## How many days old are you including leap days?
>>> chrisAgeYears = 11
>>> chrisAgeDays = chrisAgeYears * daysPerYear
>>> chrisLeapDays = chrisAgeYears * leapDaysPerYear
>>> chrisLeapDays
# We did have an old value for your age in days, but the new one reads better

>>> chrisdays

>>> chrisAgeDays
## So now add them together
>>> chrisAgeDays + chrisLeapDays

# Is that really how old you are in days?
# Should the leap days be rounded up or down?
# What about the days since your birthday?
# What is we wanted to calculate your age in days exactly as of today, would that be hard in Python?
# It would be hard if we tried without taking advantage of what other people have already written for Python.
# To be able to use code already written to be used in Python, you import a module like so:

>>> from datetime import datetime
>>> help(datetime)
>>> keithFakeDate = datetime(1966, 12, 31)
>>> keithFakeDate
datetime.datetime(1966, 12, 31, 0, 0)
>>> print keithFakeDate
1966-12-31 00:00:00
>>> todayDate = datetime.today()
>>> todayDate
datetime.datetime(2012, 6, 24, 13, 57, 38, 194119)
>>> print todayDate
2012-06-24 13:57:38.194119
>>> dateDelta = todayDate - keithFakeDate
>>> dateDelta
datetime.timedelta(16612, 50258, 194119)
>>> print dateDelta
16612 days, 13:57:38.194119
>>> dateDelta.days
# We made a lot more mistakes than this, but if we try to access attribute that doesn't exist we got:
>>> dateDelta.hours
Traceback (most recent call last):
  File "", line 1, in
AttributeError: 'datetime.timedelta' object has no attribute 'hours'
>>> dateDelta.seconds
>>> dateDelta.microseconds
## So how old are you in days exactly?
>>> bday = datetime(2001,6,1)
>>> today - bday
datetime.timedelta(4041, 51691, 369045)
>>> days = today - bday
>>> days
datetime.timedelta(4041, 51691, 369045)
>>> days.days
>>> print days
4041 days, 14:21:31.369045

Parsing and Formatting Dates and Times in Python

At this point, we spent a bit of time looking at and playing around with some of the stuff from the Python documentation of the datetime module. One especially interesting section was useful for strptime() and strftime() functions in Python.

As result we also looked at doing simple string concatenation and raw_input() for obtaining user input:

>>> yearNum = raw_input('Enter the four digit year that your were born in (yyyy): ')
Enter the four digit year that your were born in (yyyy): 1966
>>> monthNum = raw_input('Enter the two digit month that your were born in (01-12): ')
Enter the two digit month that your were born in (01-12): 12
>>> dayNum = raw_input('Enter the two digit day that your were born on (01-31): ')
Enter the two digit day that your were born on (01-31): 31

# We captured three strings and we can combine them together with the slashes
>>> dateString =  monthNum + '/' + dayNum + '/' + yearNum
>>> dateString

# We can use the datetime.strptime to parse our string with a certain format string
>>> keithBday = datetime.strptime(dateString, '%m/%d/%Y')
# We get a new datetime.datetime object
>>> keithBday
datetime.datetime(1966, 12, 31, 0, 0)

# We can use many different formatting codes to change the appearance of our date
>>> print keithBday.strftime('%A the %d of %B in %Y')
Saturday the 31 of December in 1966

Keeping Your Raspberry Pi Fresh

Keeping Your Raspberry Pi Fresh

In order to keep your Raspberry Pi secure, and to get updated functionality, you should get the firmware and the software updated. This post will describe how to keep your Raspberry Pi updated, as well as how to manage the software for the system. 

Updating the Firmware

As described in Getting Sound and Video to Work on Raspberry Pi, the rpi-update tool should be downloaded from Hexxah's Github, copied to /usr/local/bin/, and made executable.

  • Install software needed to perform the update:
    • pi@raspberrypi:~$ sudo apt-get install ca-certificates git-core binutils
  • Download the script:
    • pi@raspberrypi:~$ sudo wget https://raw.github.com/Hexxeh/rpi-update/master/rpi-update
  • Copy the script to /usr/local/bin:
    • pi@raspberrypi:~$ sudo cp rpi-update /usr/local/bin/rpi-update
  • Make the script executable:
    • pi@raspberrypi:~$ sudo chmod +x /usr/local/bin/rpi-update
  • Run the script:
    • pi@raspberrypi:~$ sudo rpi-update
    • In the future to check for updates, just execute this last step!

Every time you want to check for firmware updates, then execute:

pi@raspberrypi:~$ sudo rpi-update

Raspberry Pi firmware updater by Hexxeh, enhanced by AndrewS
Performing self-update
Autodetecting memory split
Using ARM/GPU memory split of 192MB/64MB
Updating firmware (this will take a few minutes)
Checking out files: 100% (21/21), done.
Using SoftFP libraries
If no errors appeared, your firmware was successfully updated
A reboot is needed to activate the new firmware

If you have firmware that is already updated, then the output will look like this:

Raspberry Pi firmware updater by Hexxeh, enhanced by AndrewS
Performing self-update
Autodetecting memory split
Using ARM/GPU memory split of 192MB/64MB
Updating firmware (this will take a few minutes)
Your firmware is already up to date

Checking Your Firmware Version

If you haven't updated recently, then your output might be something like this:

pi@raspberrypi:~$ /opt/vc/bin/vcgencmd version
Jun 22 2012 19:43:47
Copyright (c) 2012 Broadcom
version 321258 (release)

Today. I ran sudo rpi-update again, and sudo reboot and found that the Raspberry Pi firmware has been updated as recently as June 22, 2012. The update shown to the version did not appear until after I rebooted:

pi@raspberrypi:~$ /opt/vc/bin/vcgencmd version
Jul  1 2012 12:48:16 
Copyright (c) 2012 Broadcom
version 323014 (release)

Updating Software Packages

As I described in Slicing into the Raspberry Pi, the first thing to do after going through the initial boot and reboot is to update the software for the system:

  • Check for updates: 
    • pi@raspberrypi: ~$ sudo apt-get update 
  • Apply updates: 
    • pi@raspberrypi: ~$ sudo apt-get upgrade

Updating Software Releases

At the time of this writing, Debian is on the Squeeze release for it's stable packages. If you stay on this stable release, then the only updated software that you will be able to get will be software updated for security reasons, and not for added functionality. The most current, but unstable release is always known as Sid. When the current Sid is eventually released it will be called Wheezy. The unstable release always stays with the name Sid. 

If you want to get the most updated, and possibly face broken packages from time to time, then you can edit with sudo nano /etc/apt/sources.list and replace squeeze with sidHere is an example of my updated /etc/apt/sources.list. Notice the original lines that referred to squeeze have been commented out, and lines added where squeeze has been replaced with sid:

pi@raspberrypi:~$ cat /etc/apt/sources.list
# deb http://ftp.uk.debian.org/debian/ squeeze main
# deb http://ftp.uk.debian.org/debian/ squeeze main non-free
deb http://ftp.uk.debian.org/debian/ sid main
deb http://ftp.uk.debian.org/debian/ sid main non-free

# Nokia Qt5 development
deb http://archive.qmh-project.org/rpi/debian/ unstable main

After updating the sources.list file, perform the following to update your release:

pi@raspberrypi:~$ apt-get update && apt-get dist-upgrade

Before you try this, be sure you expand your SD card image, as described in A bigger slice of Raspberry Pi. You might also have to do apt-get -f install to finish the upgrade.

Listing Installed Debian Packages

pi@raspberrypi:~$ dpkg -l

or to be to page through the listing use:
pi@raspberrypi:~$ dpkg -l | less
pi@raspberrypi:~$ dpkg -l | more

or to send it to a file:
pi@raspberrypi:~$ dpkg -l > ~/dpkg.list

Listing the Contents of a Debian Package

If you know the name of a package, then you can list the files it contains by using dpkg -L package.

pi@raspberrypi:~$ dpkg -L python

Showing the Information about a Debian Package

To display status information about a package use: dpkg -s package.

pi@raspberrypi:~$ dpkg -s python

Package: python
Status: install ok installed
Priority: standard
Section: python
Installed-Size: 655
Maintainer: Matthias Klose
Architecture: all
Source: python-defaults
Version: 2.7.3~rc2-1
Replaces: python-dev (<< 2.6.5-2)
Provides: python-ctypes, python-email, python-importlib, python-profiler, python-wsgiref
Depends: python2.7 (>= 2.7.3~rc2-1~), python-minimal (= 2.7.3~rc2-1)
Suggests: python-doc (= 2.7.3~rc2-1), python-tk (= 2.7.3~rc2-1)
Breaks: python-bz2 (<< 1.1-8), python-csv (<< 1.0-4), python-email (<< 2.5.5-3), update-manager-core (<< 0.200.5-2)
Conflicts: python-central (<< 0.5.5)
Description: interactive high-level object-oriented language (default version)
 Python, the high-level, interactive object oriented language,
 includes an extensive class library with lots of goodies for
 network programming, system administration, sounds and graphics.
 This package is a dependency package, which depends on Debian's default
 Python version (currently v2.7).
Homepage: http://www.python.org/

Searching for Debian Software

In order to have the most recent results, be sure to follow the previous steps to Update Software Packages. If you want to install software, but are not sure which package name to use, then try apt-cache search keyword. For example I wanted to install Python 3, so I used the following. What is listed, is just a partial listing of the packages found, and I have omitted all the listings after the actual one that is needed to install Python 3. If you are logged in directly on terminal without scroll back, then you may want to pipe the output or more, or less, or redirect the output to a file:

pi@raspberrypi:~$ apt-cache search python3
pi@raspberrypi:~$ apt-cache search python3 | less # allows scrolling back and forth results hide on q
pi@raspberrypi:~$ apt-cache search python3 | more # allows scrolling forward only results seen on q
pi@raspberrypi:~$ apt-cache search python3 > python3.search # file can be viewed for results

python-apipkg - namespace control and lazy-import mechanism for Python
python3-authres - RFC 5451 Authentication Results Header manipulation for Python3
diveintopython3 - Book for learning Python 3
ipython3 - enhanced interactive Python 3 shell
python3 - interactive high-level object-oriented language (default python3 version)

Installing Debian Software Packages

Once you know the name of the Debian software package, then using sudo apt-get install package... is used to install one of more software packages. For example, in order to install python3 and diveintopython3 I used:

pi@raspberrypi:~$ sudo apt-get install python3 diveintopython3

Don't walk away too quickly, as you need to confirm by pressing Enter sometimes. When apt-get it needs to install other packages as dependencies, it will require confirmation. Another reason to watch the output is it will show the extra packages that are installed as dependencies, suggested packages, and recommended packages:

The following extra packages will be installed:
  libexpat1-dev libpython3.2 libssl-dev libssl-doc python-pkg-resources python-setuptools python3-dev python3-pkg-resources python3-setuptools python3.2-dev
Suggested packages:
  python-distribute python-distribute-doc
Recommended packages:

Removing Debian Software Packages

If you have installed packages, and you realize that they are either defective (audacious), or using space you don't want for something that doesn't work that well (totem). Then, using apt-get remove package... will remove the packages that you specify, and any packages that depend upon it. Packages that were installed as dependencies, however, are not removed when this is done. If this occurs, then apt-get will suggest using apt-get autoremove. When I wanted to remove totem, I used:

pi@raspberrypi:~$ sudo apt-get remove python3

The following packages were automatically installed and are no longer required:
  libexpat1-dev libpython3.2 libssl-dev libssl-doc python3.2-dev zlib1g-dev
Use 'apt-get autoremove' to remove them.
The following packages will be REMOVED:
  python3 python3-dev python3-pkg-resources python3-setuptools

Do you want to continue [Y/n]? 

The partial output of the command above shows that python3 and packages that depend it on will be removed. However, the packages that were shown as "packages were automatically installed and are no longer required" will not be removed unless apt-get autoremove is used to remove them.

So, to complete the process, I would have used the following. However, since I didn't really get rid of Python 3, I didn't need to do it. There is a really fun Easter Egg to check out in Python 3!

pi@raspberrypi:~$ apt-get autoremove.

Python 3 Easter Egg (Spoiler Alert)

One cool thing about Python 3, not only are batteries included, but it includes antigravity!

What I am referring to as antigravity is an Easter egg in Python 3.

By default, Python 2 is installed on most systems. If you want to install Python 3, then in Fedora I use:
# yum install python3

On the Raspberry Pi, or in Debian-based distributions in general like Ubuntu or Mint, I use:
$ sudo apt-get install python3

After the install finishes, in a GUI environment open up a terminal and start the Python 3 interpreter:
$ python3

Python 3.2.3 (default, Jun  8 2012, 05:40:06) 
[GCC 4.6.3 20120306 (Red Hat 4.6.3-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>>import antigravity

It will pop up your browser to view this web page:

If you don't have a GUI started, then no web browser will pop up, and nothing happens. It looks like this:
Python 3


Getting Sound and Video to Work on Raspberry Pi

Getting Sound and Video to Work on the Raspberry Pi

NOTE: There is a new default operating system for the Raspberry Pi that includes omxplayer. The following post, assumes that you are using the original Debian image for the SD card image of your operating system. To learn more, please see my post Raspbian Optimize Raspberry Pi.

After following Slicing into the Raspberry Pi, your Debian system should be booting and updated. In order to have room for the audio and video software, you should also followed Getting a bigger slice of Raspberry Pi to expand your root file system.

This post describes how to get audio and small videos to play back within Debian on the Raspberry Pi.
If you want sound and video to work without having to make the following changes, and take advantage of hardware playback, then you might want to set up OpenElec as described in OpenElec on the Raspberry Pi.

Update: If you want to get video to high definition video to play back under Debian Linux, then you may want to look into omxplayer compiled to take advantage of the GPU on the Raspberry Pi, this is described in my new post Playing HD Videos in Debian on the Raspberry Pi.

Playing the right videos

If you want to be able to play videos using Debian on the Raspberry Pi, then they often have to be scaled down to be able to play without hardware acceleration, and I've already mentioned how to get a distribution that does take advantage of hardware to accelerate play back (OpenElec). What I use to transform videos to use different codecs and target sizes is ffmpeg.

As an example, there was no way to play back a full 720p video encoded with ogg/theora without it either freezing the system, or having horrible play back 

Thus, I transformed the Big Buck Bunny video to be able to play by using the following. The original file was named big_buck_bunny_720p_stereo.ogg. It's video is encoded with the mpeg4 video codec at a bit rate of 22050 bits per second. The audio is encoded as mp3 with a frequency of 44100 Hz. The target is what gives it a size of 352x240 pixels. The new name of the encoded file is big_buck_bunny.mp4.

ffmpeg -i big_buck_bunny_720p_stereo.ogg  -vcodec mpeg4 -ar 22050 -acodec libmp3lame -ab 44100 -target ntsc-vcd big_buck_bunny.mp4

Updating the Firmware

Without updating the firmware, the Raspberry Pi will probably freeze it you attempt to play media.
It did to me before updating the firmware. Afterwards, sound and video play back worked.

After updating the firmware, the system will also run smoother with the newer kernel. While it can be done manually, it is much easier to use a script created by Hexxah to update the firmware of your Raspberry Pi. The README.md file for this script also explains advanced usage which can allow you to split the memory between the system and graphics:

  • Install software needed to perform the update:
    • pi@raspberrypi:~$ sudo apt-get install ca-certificates git-core binutils
  • Download the script:
    • pi@raspberrypi:~$ sudo wget https://raw.github.com/Hexxeh/rpi-update/master/rpi-update
  • Copy the script to /usr/local/bin:
    • pi@raspberrypi:~$ sudo cp rpi-update /usr/local/bin/rpi-update
  • Make the script executable:
    • pi@raspberrypi:~$ sudo chmod +x /usr/local/bin/rpi-update
  • Run the script:
    • pi@raspberrypi:~$ sudo rpi-update
    • In the future to check for updates, just execute this last step!
The output of the script should like the following, including the error about no such file or directory:

Raspberry Pi firmware updater by Hexxeh, enhanced by AndrewS
Performing self-update
Autodetecting memory split
Using ARM/GPU memory split of 192MB/64MB
We're running for the first time
Setting up firmware (this will take a few minutes)
Using SoftFP libraries
/opt/vc/sbin/vcfiled: error while loading shared libraries: libvchiq_arm.so: cannot open shared object file: No such file or directory
If no errors appeared, your firmware was successfully setup
A reboot is needed to activate the new firmware

Enabling the Sound Module

In order to enable sound to work, add a line to /etc/modules to load the sound module automatically at boot time:
  • pi@raspberrypi:~$ sudo su -
  • root@raspberrypi:~# echo 'snd-bcm2835' >> /etc/modules
  • root@raspberrypi:~# exit
To view the modules loaded use:
  • pi@raspberrypi:~$ lsmod
Before loading the sound module, the output should look like:
Module                  Size  Used by
fuse                   49036  1 
evdev                   6404  2 

After either rebooting, or using sudo modprobe snd-bcm2835 to load the module immediately, the output of lsmod should look like this:
Module                  Size  Used by
snd_bcm2835            15388  0 
snd_pcm                49240  1 snd_bcm2835
snd_timer              13560  1 snd_pcm
snd                    31624  3 snd_bcm2835,snd_pcm,snd_timer
snd_page_alloc          2660  1 snd_pcm
fuse                   49036  1 
evdev                   6404  2 

Installing Sound and Video Software

For video media players, I tried VLC, and Totem, but it either wasn't working for me in the case of VLC, or it didn't work smoothly Totem. What I found worked was Mplayer

The system also requires a sound server and sound driver, which I found installing pulseaudio and alsa-base provided. For testing sound with wave files, I also installed alsa-utils, which provides aplay, to play a sound file.

  • Install the software:
    • pi@raspberrypi:~$ sudo apt-get install mplayer mplayer-gui alsa-base alsa-utils pulseaudio mpg123
  • Reboot the system
    • pi@raspberrypi:~$ sudo reboot

Command Line Audio Playback

If you want to test whether sound is working quickly, then the alsa-utils includes aplay, which can play back wav files, but not mp3 files. If you want to be able to play back mp3 files and more, then install mpg123. For very sophisticated control, there is also the xmms2 client, which has many plugins. Given that there are several GUI clients for xmms2, including a default installation of lxmusic,  it may be easier to control it with visual controls.

pi@raspberrypi: ~ $ mpg123 /usr/share/scratch/Media/Sounds/Vocals/Come-and-play.mp3
High Performance MPEG 1.0/2.0/2.5 Audio Player for Layers 1, 2 and 3
version 1.14.2; written and copyright by Michael Hipp and others
free software (LGPL/GPL) without any warranty but with best wishes
Playing MPEG stream 1 of 1: ilovelinux.mp3 ...

MPEG 1.0 layer III, 128 kbit/s, 44100 Hz joint-stereo

Command Line Video Playback

I was frustrated at first trying to get video to playback from the command line. If I ran mplayer as an ordinary (pi) user, then it played back sound, but no video appeared. I ran sudo mplayer, then I could see video, but I could not hear sound. I discovered that device /dev/fb0, which is the framebuffer video device is owned by the "video" group. To solve this problem, the pi user must be added to the video group to be able to write to the framebuffer device.
  • Modify the pi user to belong to the video group:
    • pi@raspberrypi:~$ sudo usermod -aG video pi
  • Logout and login for changes to take effect:
    • pi@raspberrypi:~$ exit
If you expect large videos to play smoothly, then again I refer you to OpenElec. I found some videos that I converted to play on my old GPS  unit that were only 360x240 resolution, and they were able to play smoothly by adding a few options to mplayer as I started it up:

Playing back a video can be as simple as typing: mplayer /path/to/video.avi. However, your video may not play back, and the system may even have to be rebooted to be unfrozen. 

Rather than using many options on the command line, I use the /home/pi/.mplayer/config file to customize playback settings for mplayer, so that it optimizes the play back for the slow CPU, and audio to the correct frequency.  Only the lines with the bold entries need to be added to the file /home/pi/.mplayer/config:

# Let sdl decide video output which will use the /dev/fb0 device or X if it is running

# Decoding options for the video: lowres, fast, and skipfilter
# lowres=1 is half size
# lowres=2 is quarter size
# lowres=3 is eighth size 
# Use higher values of lowres if unable to play back smoothly
# fast optimizes MPEG-2, MPEG-4, and H.264 videos 
# skiploopfilter=none produces the best quality
# Other skipfilter settings include all and nonref which look worse but play back smoother
lavdopts=lowres=3:fast=1:skiploopfilter=all # most aggressive

# vfm can be a comma separated list of video family codecs to use

# ao is the audio output and should be pulse if using pulseaudio

# af is the audio filter, using re-sampling in this case, to provide audible sound

# Allow framedropping might reduce video quality, but allows video and audio to stay synced
framedrop = yes

GUI Play Back


Surprisingly, the video play back seems to work better in the GUI! Out of all the alternatives, mplayer or mplayer-gui seem to work best, or at all for me. VLC failed to work for me, and Totem had huge Gnome requirements and slow play back.

If you installed mplayer-gui package, then in the menu under Sound and Video, you will find the application Mplayer to start mplayer-gui. If you open a terminal, then you can also launch mplayer /path/to/video.mpg to view your video like:

pi@raspberrypi:~$ mplayer /usr/share/pyshared/pygame/examples/data/blue.mpg


Out of the box, the lxmusic application is installed. The easiest way to start it is from the menu under Sound and Video as the Music Player application. There a couple of other xmms2 based players available like abraca and promoe. Don't forget that mplayer can also be used as a audio player.

It is not hard to find lists of music players for Linux, but finding one that doesn't use to much RAM or require too much space is a concern for the Raspberry Pi. I also tried to use audacious, but there appears to be a serious problem with it combined with mpg123 or mpg321, where it is unable to play sound.


How the Raspberry Pi Spins

Which Distribution to use for the Raspberry Pi?

There are a number of distributions available for the Raspberry Pi. Which one should you choose? Below I've made some notes about a few that I've tried. I've tried out Qtonpi and Arch Linux but I didn't find them very useful initially or helpful to new comers, but advanced users might also want to consider those distributions.


Debian is most stable, and it worked with SD cards that other spins failed to boot. Although it does not expand itself to fill your SD card, it can be done as shown in A bigger slice of Raspberry Pi.
This is the one to get right now if you want to get started with both the command line and GUI: http://downloads.raspberrypi.org/images/debian/6/debian6-19-04-2012/debian6-19-04-2012.zip

If you want to get the most updated, and possibly face breakage, then you can edit your /etc/apt/sources.list and replace squeeze with sid, do an apt-get update && apt-get dist-upgrade to get the latest packages. Before you try this, be sure you expand your SD card image, as described in A bigger slice of Raspberry Pi. You might also have to do a apt-get -f install to finish the upgrade.

Performing a full upgrade from stable to unstable (squeeze to sid) can take over an hour, especially since it will ask several times for information before continuing.

Login: pi
Password: raspberry


Raspbian is a spin off of Debian specifically compiled for the Raspberry Pi. Raspbian.org appear to be down at this time. Update (6/29/2012), when I first wrote this, the www.raspbian.org site was down, but now it is up again.

Login: root
Password: raspbian

Login: raspian
Password: raspbian

Fedora Remix

The Fedora Remix worked with a screen offset issue on the command line, and X wouldn't start in the version I downloaded on May 30th. My first attempt to boot from the installer created image seemed to get the kernel working, but failed to mount the root file system and prompt for a login. It definitely has a nice cross-platform installer, and they are working on an Remix for Fedora 17. I'll be checking back on the following site to see progress: http://zenit.senecac.on.ca/wiki/index.php/Raspberry_Pi_Fedora_Remix_Installation

Login: root
Password: fedoraarm


Raspbmc is supposed to let you use your Raspberry Pi to run XBMC, but it too was broken the last time I tried to get it working. They even admit their first RC was a complete failure. RC2 was recently released, but I haven't given it a try yet. It seems that DDoS was being used against this site, and it was down for a while. The site claims a RC3 image is done, but, the site still has no links to download an image.


Update 6/30/2012: I have posted about how to get started, change your password, and adjust your video calibration in OpenElec on the Raspberry Pi.

OpenElec is the only working spin to get hardware accelerated video working. To get the current image, follow the link at the top to Get OpenElec, Download OpenElec. Scroll down to the bottom, and click the link for the Official Daily Builds. Then, click the link for openelec-rpi, and click the most recent download OpenELEC-RPi.arm-devel-20120614193607-r11315.tar.bz2. My other post discusses the install procedure, but they also have a decent Wiki to help get you going.

OpenElec will try your patience on the Raspberry Pi. Try counting slowly to ten after you click something, and it might have obviously started to do what you clicked on before you are finished counting!  It is so slow to navigate, but once the video starts playing it is smooth. It seems to be the best option right now if you want to be able to play HD Video using XBMC from the time you boot it up.

Put your content on the second partition, an external USB drive, or share a directory with Windows or NFS.
You must SSH into your OpenElec installation to be able to mount anything other than the second partition, and mount it under /storage.

Username: root
Password: openelec

To navigate the XMBC menus, the mouse is helpful. It only takes one click to choose an item, and then be patient. You can also use the keyboard arrow keys to move, and Enter to select. Esc will back you out. Space bar toggles between play and pause a running video. Control-Alt-Delete will kill the system immediately, but it doesn't reboot the system.

While I was able to watch almost all of my own videos, I was most intruiged by the YouTube Add-on.
Here's what I've navigated with it so far. Using Search and Top 100 Music Chart are my favorites so far.
  • Videos
    • Add-ons
      • Get More (If YouTube isn't installed, then install it)
    • YouTube
      • Explore YouTube
        • Categories
        • Education
        • Feeds
        • Movies
        • Music
          • YouTube Disco!
          • Popular Artists
          • Recommended Music
          • YouTube Top 100 Music Chart
        • Shows
        • Trailers
        • Live
      • Search
      • Login...
        • Be sure to set up your username, password, and download directory

Samsung Galaxy SIII on Verizon

Samsung Galaxy SIII 
Last night I bit the bullet to buy what I hope to be the best smartphone available. I was feeling under pressure to move a second line to 4G LTE with unlimited data before Verizon changes it's data plans on June 28th, and I had just gotten the best paycheck in months, so I picked the Samsung Galaxy SIII. Instead of Marble White, I chose Pebble Blue as shown here in the picture.

Key Factors in Decision You can get more detailed specs from Samsung for this phone on the Verizon network, but the following were factors in my decision to choose this phone:
  • Ice Cream Sandwich (ICS), now, not in a few months. As an Android developer, I need a device running the most current operating system. 
  • Power to burn with a removable 2100 mAh battery, which is great if you go through two batteries a day 
  • Room to rock with 2 GB RAM, which is twice what most high end smartphones have on board
  • Awesome camera
    • Able shoot pictures while shooting video
    • Built-in HDR and Panorama modes
    • Zero lag shutter on 8 MegaPixel rear camera
    • 30fps 1080p video from rear camera
    • Good quality 1.2 MegaPixel front camera
    • 30fps 720p video from front camera
    • Front camera used to keep device awake while you look at it!
  • Plenty of space with 16 GB internal storage (or 32 GB for another $50)
  • More space with a Micro-SD slot for adding up to 64 GB 
Other Factors
  • The fastest 4G LTE network from Verizon, since I'm on Big Red and data speed is important to me
  • Big and bright HD 4.8" 1280 x 720 Super AMOLED display
  • Powerful Qualcomm S4 Dual core 1.5 GHz Processor (That's what the US gets!)
  • Near Field Communications (NFC) capabilities to do new and exciting things with the device

Samsung TecTiles

Samsung is marketing a new product, TecTiles, programmable NFC tags that will allow you to do things specific to your phone, like settings, as well as generic for any NFC enabled device like view location, check in to Foursquare or Facebook, or provide contact information.

Toolkit for Samsung Galaxy SIII
If you want to rule your phone, then head over to XDA where you can get a toolkit to do just about anything to the phone, its apps, data and partitions.

How to get into Recovery Mode
1. Unplug the USB cable.
2. Shut down the phone.
3. Hold down the 'HOME' + 'VOLUME UP' buttons and press the 'POWER' button for about 5 seconds 

How to get into Download Mode (For Odin)
1. Unplug the USB cable.
2. Shut down the phone.
3. Hold down the 'HOME' + 'VOLUME DOWN' buttons and press the 'POWER' button for about 2 seconds until a WARNING! Screen appears. Press the 'VOLUME UP' button to enter Download Mode.

About Me - WrightRocket

My photo

I've worked with computers for over 30 years, programming, administering, using and building them from scratch.

I'm an instructor for technical computer courses, an editor and developer of training manuals, and an Android developer.