Sunday, May 26, 2013

Pifi Mini - Tutorial Part Two

Tutorial Part Two - For those who wish to add an LCD
DISCLAIMER: Since the following instructions involve wiring something to your Pi there is a risk of damaging your Pi if you wire something wrong. I take no responsibility if you damage your Pi while following this tutorial. If followed correctly this tutorial should be quite safe for your Pi.

Skill level: Intermediate, requires soldering

Time: Varies, it really depends on your experience level. For someone used to doing this stuff it shouldn't be more than an hour.

Equipment & materials:
This will really depend on how you're planning on mounting the display but you'll basically need a 16x2 hd44780 LCD screen, wire, pin headers, and of course a soldering iron. If you want to play it safe you can start with a reusable breadboard and reusable jumper cables (look on ebay for  dupont breadboard cables). All of this stuff can be obtained even cheaper if you look on ebay and dx.com but for ease of use I'll just provide links to Adafruit products if you want to get them all in one place.

16x2 LCD display using the hd44780 chipset - Very common, available on ebay for $5
*Note if ordering a display do not get the EL or "Electro Luminescent" backlight because these require way more power.
Here's a link to one at Adafruit if you get this one it comes with the 16pin header strip and potentiometer

16 Pin Single Row Male Header with 0.1" pitch (2.54mm)
- These typically come in longer lengths and you simply break off what you need
- If you are buying the display from Adafruit via the link above it already comes with the header you need.

560ohm 1/4 watt resistor
- Not required if you're buying the LCD from Adafruit
- Some cheap Chinese displays do not have a current limiting resistor installed for the LED backlight, this resistor is only needed for those. Since it's just about impossible to tell until you actually apply power to the LCD it's a good idea to wire one in first just to be safe, if the backlight is very dim then you can remove it.

28 Gauge Wire - Rainbow ribbon isn't necessary but it is handy
Here is an Adafruit link

Dupont Breadboard Cables - Female/Female (Optional)
- Alternative to the above 28 gauge wire. I highly recommend these for prototyping even if you're not using a breadboard. 
- Look on ebay for these, they're cheap I got 100 cables 20cm long in 5 colours for $9


26 Pin Dual Row Female Header with 0.1" pitch ( 2.54mm) for 0.025" square pins
 Adafruit link
- I used an 80pin one from dx.com and just cut it down with a dremel


Bread board (Optional)
- Adafruit link


Wiring the LCD

Click here for a full size pdf of the wiring diagram





































It is especially important when wiring up the LCD that pin 5 of the LCD be connected to ground, this is the R/W pin and it is 5V. Connecting this to any other pin on the Pi will damage your Pi!! Since we're only writing to the LCD we don't need this pin so we're shorting it to ground.

Note that in the wiring diagram there is a 560 ohm resistor between LCD Pin 15 and pin 1 on the potentiometer, this is due to the fact that some cheaper LCD displays do not come with a current limiting resistor for the backlight LED. Installing a resistor around 560 ohms will ensure the LCD does not draw too much current from the Pi, if you install it and the display's backlight is barely on then your LCD already has a current limiting resistor and it is safe to remove the one we added.

Once you've triple checked your wiring plug in your usb wifi dongle and usb keyboard, connect the Pi to a display and apply power to your Pi. There shouldn't be any smoke or fire if you've done everything correctly :) There will be no display on the LCD screen yet, adjust the potentiometer until you can just see the start of black boxes.

If your Pi fails to boot at this point go back and re-check your wiring, if it still doesn't boot then it could be that your power supply isn't powerful enough (you should be using a 5V 700mA supply). Even if your supply says it's 700mA or higher it's not uncommon for cheap no-name supplies to lie, try using a name brand cell phone charger for a smartphone (ie Samsung, Blackberry etc), obviously it'll need to have a micro usb end. You can also try booting with just the LCD screen installed but no wifi dongle or usb keyboard, if it boots then this confirms that the power supply isn't strong enough.

If you've double checked your wiring and ensured your Pi is good but it still isn't booting it may also be a good idea to remove all wiring from the header on the Pi and ensure that it is still working.

Note: Depending on the LCD you chose you may find that the potentiometer used to adjust the contrast is unnecessary and that LCD pin 3 can simply be shorted to ground instead. In my experience the yellow screens with black letters do not need a pot but blue screens with white letters do.

Installing LCD Proc


Before we start we need to check what version of raspberry pi you have.
This command will return a number corresponding to the version of Pi that you have, this will become important later when we are configuring the GPIO pins. 


The main reason we need to know this is because on model B rev 1 boards pin 13 on the Pi's pin header relates to GPIO #21, on model B rev 2 boards and model A boards pin 13 is GPIO #27

If your pi returns either:
0x2 and 0x3 Then you'll follow rev 1 GPIO mapping.

If your pi returns 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xD, 0xE, 0xF or higher you'll follow rev 2 GPIO mapping.

Now we're ready to update packages and install lcdproc



Stop LCDd service just in case it started automatically after installing


Get custom drivers for using lcdproc with the GPIO on the Raspberry Pi, put them in a folder at /home/pi/lcd_extra_drivers


Backup then edit the LCDd.conf file


Find Driver=curses (not the one in the description at the top of the file that has a # in front of it) and change it to:
Driver=hd44780

Remember when using nano you can search for words by pressing ctrl+w

Find the lines
#Hello="  Welcome to"
#Hello="   LCDproc!"

Remove the # from the start and change the text to

Hello="Welcome to"
Hello="PiFi-Mini"

Find the lines
#GoodBye="Thanks for using"
#GoodBye="   LCDproc!"

Remove the # from the start and change the text to
GoodBye="PiFi-Mini"
GoodBye="Shutting Down"

Find the line
#ServerScreen=no

And remove the # from the front

ServerScreen=no

Search again for hd44780
Change the line ConnectionType to =rpi

IMPORTANT!! If you have a rev 1 Pi D6 should be 21, if you have a rev 2 it should be 27

Edit your lines so they look like the following:
For Rev 1 GPIO


For Rev 2 GPIO


Find the line Size=20x4

And change it to:
Size=16x2

Now save the file and exit (Press ctrl+x, then y, then hit enter)


Restart lcd proc


Now we write our lcd display script


Copy and paste the following text:
PASTEBIN IS BEING WEIRD AND ADDING 4 SPACES TO THE START OF EVERY LINE, INSTEAD RIGHT CLICK ON "DOWNLOAD RAW" AND OPEN THE LINK IN A NEW TAB THEN COPY/PASTE. SORRY I'LL WORK ON GETTING THIS FIXED ASAP. Test the script


You should see info come up on your screen that scrolls
Press ctrl c to end the program, you'll get a few lines of info after that will end with "KeyboardInterrupt" just ignore this it's fine

Now we must go back and uncomment the lcd lines in our rc.local script


There should be two lines in the document like this:

#python /etc/mpc_lcd_info.py& #start lcd script that displays mpd info

Remove the # from in front of it then save and exit the file.

Congrats, you should now have a working PiFi-Mini with an LCD display. From here you can choose to leave it as is and run it to your stereo or do what I did and incorporate it into a box with it's own speakers and amp.

PiFi Mini - Tutorial Part One


Tutorial Part 1 - Everything but the LCD
I've split the tutorial up into two parts so that people who only have a Pi and a USB Wifi dongle can get most of the benefits of this project without having to do any actual hardware stuff.

Skill level:
The ability to read and follow instructions

Time:
~20 minutes if simply downloading my image onto an SD card and tweaking some config settings
1-2 hours if following this tutorial step by step
If you have the time it's worth doing it step by step so you learn since that's what the Pi is all about!



Requirements:
-Raspberry Pi
  • Model B Rev 1 & 2 tested
  • Model A untested but should work, GPIO layout should be same as rev 2

 -Power supply for Raspberry Pi
  • Current capacity depends on your design, if you are powering speakers and an amp like in mine you'll need to determine your current draw needs first. If you're only connecting a wifi dongle, usb flash drive, and are using an LCD you should be fine with the standard 5V 700mA supply still.
-SD Card 2GB minimum, 4GB or higher recommended

-Software for writing a .img file to the SD card, use this guide's recommendations for sofware.

 -USB Wifi Dongle
  • Preferrably one using the Railink RT5370 chipset however this tutorial will also cover using one with the rtl8192 chipset. Note Airplay will not work properly in ad-hoc mode with the rtl8192 chipset.
  • NOTE: I've recently found some ebay listings claiming to sell RT5370 based dongles that are actually RT3070 dongles, I've posted about my experience here.
-Wireless internet connection (ie you need internet access and a wifi router)

- Earphones - You could opt to connect this to a stereo but I recommend earphones for initial setup.

Tools needed (for setup only):
TV or some sort of display with either composite video or hdmi inputs
Necessary cords to connect to the display
USB Keyboard




READ THIS FIRST!!!!!!!!
It is important that you follow these instructions closely.
Do not reboot unless instructed to do so in the procedure otherwise your Pi could be improperly configured and might not boot after. If this should happen don't worry you can always wipe your SD card and start again.
When editing any config files on your Pi you should always make a backup first, I try to include this in the instructions but I may miss one or two.
If you get any errors after entering a command check if you missed typing "sudo" in front of the command

From here out there will be code boxes, simply copy the code from the box and paste it into your terminal session.

Before beginning it is important to note that you should ensure you have a good power supply for the Raspberry Pi, a lot of people have ran into issues that were caused by a bad power supply. Often times cheap no-name power supplies (typically from China) will say that they are 700mA or 1A etc but will not actually provide that current level. They may allow the Pi to boot when nothing is plugged into the USB ports but as soon as you start "loading" down the supply their voltage drops and can cause your Pi to reboot. Since this project is using a Wifi Dongle which will draw more current than other peripherals like a USB mouse or keyboard you will need to have a proper supply. A safe bet is to use a charger from a name brand phone (Samsung, Motorola etc) that is 700mA or higher.

The Image and SD Card


Download Rasbian Wheezy from www.raspberrypi.org (I was using 2013-02-09-wheezy-raspbian but hopefully as newer images are release they will work too)
Unzip the file
Use Win32DiskImager to write the image file to the sd card

(Consult this guide if necessary)

Install the SD card into your Pi
Connect a usb keyboard
Insert your wifi dongle
Connect earphones to the Pi
Apply power to the Pi

First run setup


After a bit of a boot process you will be presented with the initial setup window

Expand Root Partition YES


Configure Keyboard (it takes a few seconds to start, don't worry)

  •     Choose Generic 102 key international keyboard
  •     On the next screen choose Other
  •     Select English US
  •     On the next screen select English US again (should be at the very top of the list)
  •     For the Alt Gr key just choose keyboard default
  •     Select the default options for the next questions
Optional: Change password for 'pi' user

Change  Locale
  • For Canada select en_CA ISO-8859-1 and en_CA.UTF-8 UTF-8
    Hint, use spacebar to make selection, hit enter to continue afterwards
  • For US select all of the en_US options
  • I'm not familiar with the requirements for other Countries so you're on your own, check for tutorials at rasberrypi.org or adafruit
  • Next you will be asked which to choose as the system default, choose one of the UTF options for your country of choice, for Canada this is en_CA.UTF-8

Change Timezone:
  •     For Canada or US select US
  •     Select the desired timezone

SSH Enable
  • Make sure this is enabled

Boot Behavior Start desktop on boot?
Disable, this is a headless system so we don't want it booting to the desktop each time

Do not select update

Don't bother messing with any overclocking, it really shouldn't be necessary.

Finish

It should ask if you wish to reboot now, say yes.

If you didn't get the option to reboot or if you accidentally clicked no then you will now be at a command prompt, enter



Log in
username is "pi"
password is "raspberry" unless you changed it in the initial configuration

Configure Wifi

The easiest way to do this is via the desktop app called wpa_gui, make sure you know your wifi network name, encryption type (ie WPA, WPA2 etc) and your password before continuing.

Start the desktop by typing:


It will take a little while to start but you should eventually get a desktop. Now this will be a little tricky because we don't have a free usb port to connect a usb mouse so we'll do this purely from the keyboard.

Press Alt F2, this will bring up a Run window, type wpa_gui and hit enter.
The wpa_gui window should open, press the right arrow to select the "Manage Networks" tab.
Press tab until "Scan" is highlighted then press the spacebar.
A new window opens, press enter to scan.
Note the SSID of the network you want to connect to.
Press tab until close is highlighted, then press spacebar.
Press tab until "Add" is highlighted and press spacebar.
Type in the SSID of your network, use tab to continue to the next fields as necessary.


When finished press enter, if everything was entered correctly you should connect and obtain an IP address, write down the IP address that your Pi was given. If for some reason you were unable to connect using wpa_gui repeat the steps and verify the information is correct. Note that your SSID is case sensitive.

Once connected press Alt-F and select exit.
We'll launch a terminal window next
Press Alt-F2 again and this time type lxterminal

Now we'll reboot, type the following into the terminal window

Once rebooted login again


Installing software MPD & MPC

*NOTE You can install multiple items at once by listing them one after another like apt-get install mpd mpc however if there is any errors during install it makes it really difficult to figure out where in the process it had issues so I suggest doing them one at a time even though it takes longer.



It will tell you how much disk space is required and ask if you want to continue, hit enter.
This will download mpd and install everything, it will take a few minutes

MPD will automatically try to start at the end of the installation, it will give an error saying "Failed to load database", this is fine. After a little while you should return to a command prompt, if not press enter and wait a little longer.

We now need to stop mpd and edit it's config file


 Find the section titled Audio Output
*Tip use ctrl+w to search when using nano as a text editor
Change "My ALSA Device" to "PiFi Analog Output"

And add the following line after name and before mixer_type:

mixer_type    "software"

Afterwards your Audio Output section should look like this:

audio_output {
        type            "alsa"
        name            "PiFi Mini Analog Output"
        mixer_type      "software"
        device          "hw:0,0"        # optional
        format          "44100:16:2"    # optional
        mixer_device    "default"       # optional
        mixer_control   "PCM"           # optional
        mixer_index     "0"             # optional
}


Find the line
music_directory         "/var/lib/mpd/music"

And change it to
music_directory         "/home/pi/music"

Find the line
bind_to_address        "localhost"

And change it to
bind_to_address        "any"

Save and exit the file by pressing ctrl x,  it will ask you if you want to save, press Y
It will ask the filename to write to, just press enter.


Now we need to make a music directory for the user pi




Start mpd again


Now we'll set the system volume to 100, this way whatever service is outputting sound will control the volume itself

This will open the alsamixer, press the up arrow until the volume is at 100, press esc when finished


Install mpc



It will tell you how much disk space is required and ask if you want to continue, hit enter.
This will download mpc and install everything, it will take about a minute.

Set mpc's volume to something low just to be safe
If for some reason you get any errors then mpd may need to be restarted after mpc is installed
You can do this by typing sudo service mpd restart


Now we'll copy a sample .wav file to test things out with


Now we'll tell MPC to update it's database


It should return the following
Updating DB (#1) ...
volume: 30%   repeat: off   random: off   single: off   consume: off

Now if we type


We should see our Front_Centre.wav displayed


Now we can add it to a playlist

Let's see if it plays


If you've followed everything correctly you should hear the words "Front Center" coming out of both headphones (*assuming you're listening through the headphone jack)


If you didn't get any sound at all try typing the following commands below. This should set the audio output to the headphones instead of hdmi, if you want to switch to hdmi change the last 1 to a 2




Try mpc play again


You may at this point wish to adjust the volume a little higher which you can do by using the mpc volume command like we used early and entering a percentage between 0 and 100. At this point I still would recommend keeping it low, probably no more than 50.

Installing Shairport an Airplay emulator



Again this will take a little while to download an install.

Now there are a bunch of other dependencies to download, its up to you if you want to try to install them all at once or one at a time.




Installing Net::sdp
 

Installing Shairport


Making shairport run at boot


Test shairport


Now fire up an iOS device, make sure you're on the same wifi network as your Pi and you should see a new icon beside your pause/play/ff/rw controls in your music app.


When you click this icon there should be an option "ShairPort 6736 on raspberrypi"
The number listed on yours will be different.
Select it and you should be able to stream music to your Pi now from your iOS device.

Setup hosts and hostname



Change this line
127.0.1.1     raspberrypi

To
127.0.1.1    pifi-mini

Press ctrl+x to save, type y, hit enter



Replace raspberrypi with pifi-mini

Note that after editing the above two lines you may get an error saying "could not resolve host pifi-mini" every time you use sudo in the next sections, don't worry this will clear after a reboot.

Make shairport broadcast PiFi-Mini as the airplay device name


We want to add one line and change one line
Under NAME add a new line and write
PUBLIC="PiFi-Mini"

Find the following line
DAEMON_ARGS="-w $PIDFILE"

And change it to
DAEMON_ARGS="-w $PIDFILE -a $PUBLIC"

It should look something like this

...
NAME=shairport
PUBLIC="PiFi-Mini"
DAEMON="/usr/local/bin/shairport.pl"
PIDFILE=/var/run/$NAME.pid
DAEMON_ARGS="-w $PIDFILE -a $PUBLIC"
...
Save the file by pressing ctrl+x, press y, press enter

Restart shairport


At this point if you are playing a song or stream using MPD and then send music to the Pi using Airplay both will come out of the speakers at the same time. Don't worry, we'll now write a little bash script that will fix this.


Copy and paste the following text:
PASTEBIN IS BEING WEIRD AND ADDING 4 SPACES TO THE START OF EVERY LINE, INSTEAD RIGHT CLICK ON "DOWNLOAD RAW" AND OPEN THE LINK IN A NEW TAB THEN COPY/PASTE. SORRY I'LL WORK ON GETTING THIS FIXED ASAP. NOTE THIS APPLIES TO ALL OF THE PASTEBIN SCRIPTS BELOW TOO.
Save the file by pressing ctrl+x, press y, press enter.

Make it executeable


Let's test it, but first lets delete the Front_Center.wav test file and download a better test file. This is a public domain mp3 so it's legal to download it. When you delete Front_Center it will ask you to confirm because it is a write-protected file, just type y and hit enter


We'll clear the current mpc playlist, update the database, then enable repeat.


At this point I recommend ensuring your volume is at a reasonable level, something 50 or less should be good.


Now we'll start the airplay monitor script and run it in the foreground to make sure there are no errors. It should just run and no text should appear.
Note that since we're running it in the foreground we'll have to press ctrl and c to stop it afterwards.



!!!!!!!!!!STOP and READ!!!!!!!!!!!!
The following could result in bad static that could damage your ears or stereo if you have the volume cranked so if you ignored my previous warning go back and set the volume to something below 50. At the time I write this (April 2013) there is still an audio glitch with the Raspberry Pi, at this point if you send a song via Airplay and it sounds fine and the MPD song pauses you're good. If not then skip to the next section called "Audio Fix".

On your iphone or ipod play a song to the Pifi Mini


Audio Fix
As of right now this is the only way I know how to do this, these files are taken from https://github.com/Hexxeh/rpi-firmware/commit/779f0fb6139452a0f1c4be32dab58eb87359517e

It is possible that later releases may not need this fix. First we'll backup the orginal files just to be safe.



You'll need to reboot once the files have downloaded


If your pi reboots without issue login and skip the next paragraph.

At this point if for some reason your Pi doesn't boot you'll have to power off the Pi and plug the card into a computer. Browse to the boot folder, delete the start.elf and fixup.dat files and rename the fixup.datBAK and start.elfBAK to fixup.dat and start.elf
If this is the case then I'm not sure what the issue is and you'll have to live with the audio glitch or google it to look for other solutions, one fix is using pulseaudio but it's not a great fix and I'm won't cover it in this tutorial anyway.

Assuming your reboot was sucessful try it all again, start mpc playing if it isn't already, start the monitor script, and try using airplay.


There should be a smooth transition (there will be a small pop when Airplay starts though), the song from your iOS device will start playing and the song MPD was playing should stop. When you end the Airplay connection the MPD song should resume without issue.

You can stop the airplay_monitor.sh script now by pressing the control key and c simultaneously.

Installing USB Mount

This is a nice little program that will automount a usb drive when it's plugged in so we can access it from MPD.


We'll make a symbolic link (ie shortcut) in our music folder to point to where our usb will automatically mount.


Plug in a usb drive with some mp3's on it (no portable hdd's unless you use a powered hub, stick with thumbdrives if powering off of the Pi itself).

Refresh the database.


Now we'll add all of your mp3's from the thumbdrive to a playlist - Later you can do all of this much easier using an app or the web interface.


Display all of the songs we just added to the playlist


In a little bit we'll install a web interface which will include a way to safely eject your usb drive, however if you wish to do this before then you'll have to do it manually.

We'll stop mpc so it's not accessing the usb otherwise we won't be able to eject it.


At this point you can safely remove your usb drive. You'll need to update MPC's database again to reflect the change otherwise it will think those files are still present.


Access Point failover mode, configure interfaces and rc.local


First we need to install a dchp server


The previous command will install the dhcp server and then automatically try to start, it will fail to start and give an error but don't worry about it.

Next we have to prevent the dhcp server from automatically starting.


Now we need to modify some config settings, as usual we'll backup the file first.


Find the line below with INTERFACES and add wlan0 between the quotes.
INTERFACES="wlan0"
Save and exit the file.

More configuring


Copy and paste the following into the new file.
Save and exit the file.

Configure Interfaces


Copy and paste the following into the new file

Save and exit the file.

!!!!!!!!!IMPORTANT!!!!!!!!!!
Before proceeding to the next step we should double check which chipset your wifi card is using.
Even if the packaging says one thing it could still be another



If you see Bus 001 Device 004: ID 0bda:8176 Realtek Semiconductor Corp. RTL8188CUS 802.11n WLAN Adapter then follow the Hostapd Realtek 8192 instructions below.

If you see Bus 001 Device 005: ID 148f:5370 Ralink Technology, Corp. RT5370 Wireless Adapter
Then follow the Hostapd Railink 5370 instructions below.

Note that your Bus and Device numbers may be different than shown

Realtek 8192 instructions:
Install Hostapd - Realtek rtl8192 chipset (requires custom binary).


Prevent hostapd from starting at bootup.


Make a backup of the hostapd binary.


Change directory to /usr/sbin.


Get the new binary file for hostapd.


Make it executable.


Create and edit the hostapd config file.


Copy and paste the text below.
Point hostapd's init.d file to the right config file.


Find the line
DAEMON_CONF=
And add /etc/hostapd/hostapd.conf after the = like so:

DAEMON_CONF=/etc/hostapd/hostapd.conf

Save the file and exit.
Ralink RT5310 Instructions:
Install Hostapd - Ralink RT5370 chipset


Prevent hostapd from starting at bootup

Create and edit the hostapd config file


Copy and paste the text below
Save and exit the file.

Point hostapd's init.d file to the right config file


Find the line
DAEMON_CONF=
And add /etc/hostapd/hostapd.conf after the = like so:

DAEMON_CONF=/etc/hostapd/hostapd.conf

Save and exit the file.

Test hostapd

This will stop the wlan0 interface, kill any wpa_supplicant programs running, start the hostapd daemon, start the wlan0 interface again at ip 10.10.10.1, and finally start running the dchp server daemon.


You should now see a new wifi network available called PiFi_Mini_AP, try connecting to it with a smartphone or laptop, remember the password is pifimini00

Your device should connect and should get an IP of 10.10.10.2, if you connected using an iDevice you should see the PiFi Mini available as an airplay device.

Reboot to get back to normal mode


rc.local

We're going to edit the rc.local file so everything gets done properly at startup. We'll backup the original, delete the original, then create a new rc.local file.


Copy and paste the following into your blank rc.local file, the code is commented for those who are curious or for advanced people who want to tweak or customize it.
UPDATED: I've improved the rc.local file, now it checks to see if a wifi card is present first, if not it then checks for a wired connection. 

Save and exit the file.

We'll reboot again at this point, this time during the boot process you should see more info like which wifi network your connected to. Log back in once it's booted.


Testing AP Failover mode
First we'll backup our working wpa_supplicant.conf file, then we'll remove it so that when the system reboots it will fail to connect thus sending into failover mode.


It takes awhile to failover to AP mode so be patient, after awhile you should see a message on the display saying "Starting AP Mode". Once this happens try to connect to it with your phone or laptop, at this point we don't have the web interface setup yet so you wont actually be able to do anything once connected but it's good to make sure your phone or laptop connects and is obtaining an IP from your Pi. Your device should be given an IP of 10.10.10.2

Web Interface - Installing lighttpd and PHP


Note install these in the order listed below, if you install php5 before php5-cgi it will install apache as well and we don't want that. I suggest copy and pasting these lines one at a time letting each install before continuing to the next line.




Set permissions for the /var/www folder so php will run properly there


Add "pi" user to www-data group
 
You'll need to log out and log back in to obtain the permissions we just set, you can do this by typing exit

Test your webpage by entering your Pi's IP address into a browser, on some systems you can now try simply typing pifi-mini.local instead of the numerical IP (Android OS does not seem to like this). If it works then it's a good idea to bookmark the page so you don't have to type it each time.
You should see a PHP Placeholder page

Making a more detailed index page for diagnostics


Paste the following text into the text editor

Save and exit the file.

Refresh your browser page, you should now see a long page with a bunch of info about your php installation

Now let's rename that index file to test.php in case we need it later


Installing PiFi Mini webui and an MPD web interface


Note: For the web interface I chose phpMP which is I found to be the most full featured and supports php5, you could try phpMPreloaded which contains a bunch of different MPD web clients, however at the time of writing it's not fully php5 compatible


Edit your sudoers so www-data has some extra permissions


 Add the following below pi All=(ALL) NOPASSWD: ALL

Save and exit the file.

In order for the webUI to be able to edit the wifi config file we need to allow non-root users to edit it
Note that if you edit the wpa_supplicant.conf file manually at any time you'll have to redo this step or else the webUI's Easy Wifi Config won't work


Before testing it out, we'll backup our working wpa_supplicant.conf file first in case it doesn't work


Now we'll replace the current wpa_supplicant.conf file with a blank one so that we know our webui actually did what it was supposed to.

We'll reboot now and you should see during the boot process that the Pi will be unable to connect to a network and will create it's own, note it takes about a minute before it fails over and creates the network. Look for the PiFi_Mini_AP network with your laptop or smartphone, once it appears connect to it. Remember the password is pifimini00.

Once connected open your browser and go to the PiFi Mini's web interface, at this point you should be able to simply point your browser to pifi-mini.local (unless you're using an Android device which doesn't resolve this address properly) else simply enter in the IP address 10.10.10.1
Click on Easy Wifi Setup
Enter in your wifi SSID, Encryption Type, and Password
Press "Submit and Reboot"

If all goes well your PiFi Mini will reboot and connect to your network without issue, if it doesn't then just look for the PiFi Access Point to show up in your wifi networks list and try again taking care to enter all of the info correctly. It should work but if not you can restore your old wpa_supplicant.conf file


At this point you should have a working PiFi-Mini smart radio minus an LCD screen. You can keep this as is or if you're feeling adventurous you can continue on to part II and add an LCD.

Removing Unnecessary Packages & Files (Optional)

If you used a 2GB card you'll only have ~115MB of space left so you may want to do a little house keeping and remove what you don't need, after you should have ~400MB of free space. If you used a 4GB card or higher I suggest just leaving it as is.

Note this will remove desktop functionality, if you wish to preserve it do not proceed.



Continue to Part 2 to add an LCD screen if you want to.

PiFi Mini - The ultimate Raspberry Pi boombox

IMG_20130501_001228
This post is about a project I've spent a considerable amount of time on, my goal was to not only create something that I would want to use but also to document my progress and share the whole design with others that would like to make their own.

So what is the PiFi Mini?
It's  a feature rich "smart radio", it can play files from a thumbdrive, stream internet radio, and play songs from your iOS device via Airplay all while being controlled by a smartphone or web browser. I've decided to differentiate this particular version by calling it Mini because down the road I may also make a version that is meant to be fixed and stay in your entertainment centre. You can check out the manual I made here.

Why did I create this?
I own a few wifi radios, none have all of the features that I wanted so I decided I'd make my own.

Features (Core)
  • Internet radio streams
  • Local file playback and playlist support
  • Airplay (shairport)

  • Web Interface
    • Allows for easy wifi configuration
    • phpMP a web control client for MPD
    • Various PiFi controls like Safe Shutdown, Reboot, Safely Eject USB Drive, Switch to AP Mode
    • Online user manual

  • Access Point fail-over mode
    • What this means is you'll always be able to connect to the PiFi-Mini even if you're in a new network, simply boot the device and wait until you see a new wifi network appear. Once you connect to the PiFi's access point you can use the PiFi's web page to easily enter the necessary wifi info to connect to the current network you wish to. No messy command line editing of wpa_supplicant files necessary!
  • Audio pops fixed - Only pops once when it turns on and once again when powered off.
  • Script that monitors whether Airplay is active so that it is impossible for both MPD and Airplay to be playing at the same time.

Optional Features:
  • LCD display (Current song, player state, volume, IP address, wifi signal quality out of 100)
    • While not absolutely necessary it is a very nice feature to have and only adds a little to the build cost
How can I make my own?
I've created a tutorial in two parts, part one covers everything but the LCD and is a good place to start, by the end of it you'll have a working smart radio that you can connect to your own speakers or stereo and control via smartphone apps or it's built in web interface. If you want to go further you can add an LCD display by following part two of the tutorial, this is purely optional. I will not have a tutorial covering the making of an enclosure or adding speakers, instead in the rest of this post I'll walk through my own build experience and if people want to copy my enclosure or my choice of built in amp/speakers they can.


Tutorial Part 1: Everything but the LCD
Tutorial Part 2: Adding an LCD screen
Or take the easy way out and download my pre-configured image (not available yet)

Building my Pi-Fi Mini

Warning: The following is a long read but it covers all of the issues I ran into along the way.
You can see my original build thread over at the raspberry pi forums here.

My initial plan for this project was to focus on roughing out the software first, then roughing out the hardware, and finally polishing both. To begin with I needed to get my wifi dongle working, initially I chose one with an rtl8192u chipset simply because I heard it worked "out of the box" with raspbian. In the final design stages I realized some limitations of this dongle so I switched to an RT5370 based dongle instead.
*Quick warning about ebay dongles here.

Wifi
Getting wifi up and running strictly via command line can be difficult, raspbian uses wpa_supplicant to connect to encrypted wifi networks and the config file is tricky when doing it by hand. I found the simplest way to do it was to start the desktop and use wpa_gui  for the initial wifi setup.

MPD & MPC
Getting MPD (Music Player Daemon) installed proved to be relatively painless and so was MPC which is a command line client for MPD. This program is the main backend for the music player, it allows playback of local files as well as network streams. Since it is a well established program there are plenty of apps available to choose from for controlling it, for iOS my hands down favorite is MPoD. For Android I tried MPDroid, BitMPC and DroidMPD Client. All are decent and since they're free you might as well try them all, one feature that BitMPC had that I quite liked was the ability to add a podcast RSS feed.

Shairport
(Note: The Shairport program is a bit of a legal grey area due to the means by which the program's author reverse engineered some of the elements. See this article and judge for yourself before installing.)

Next I installed Shairport to allow the PiFi Mini to act as an airplay device. Luckily I had found the updated tutorial first which used slightly different files to allow iOS 6 support. Installation was again pretty painless, some tweaking of the init.d file let me customize the name that is broadcast to airplay compatible devices.

Analog audio popping issue
I should mention at this point that when I was first getting started I followed some online advice for getting rid of the annoying popping when starting/stopping playback on the Pi when using the analog output. The fix at the time was to install Pulseaudio which acts like a go between to alsa, within one of the pulseaudio config files a module could be disabled that prevents the audio module from sleeping. It appeared that when the DAC in the audio out put would turn off it did so abruptly which caused the pop. For whatever reason installing this initially left me without sound and a few hours of troubleshooting got it sorted, still not sure what I did wrong. At this point I had zero popping with MPD since it was setup to use Pulseaudio, however I could not get shairport to work with pulseaudio. Eventually I found a different fix which required replacing the start.elf and fixup.dat files in the boot folder with modified versions, after this I uninstalled pulseaudio and now there is only 1 pop when the system starts and one when it stops. There is still a pop at the start when a song is played to the device over airplay but if you're playing numerous songs in a row there is no popping between songs.

One at a time...
While testing I realized that if I left MPD playing a song I could send a song over airplay and both would play out of the speakers at the same time. Now I'm still new to coding so my workaround to this is probably quite ham fisted but I found that using the command "sudo netstat -t" would show all tcp connections and when an Airplay connection was made that connection would always show "rfe". I set about writing a bash script that would run the netstat command, pipe it to grep to search out rfe, if doing so returned results my script would write "on" to a file in ram called airplay_state and it would pause MPD. I went further an had the script check if airplay had previously been running but now was stopped, if so it would resume playing MPD and write "off" to the file in ram. The purpose of writing it to a file in ram was so that other scripts I was using could easily tell if airplay was on or not, the main one being the LCD script.

Web Interface & Access Point Failover Mode
At this stage I had decided to make this a button-less system, solely controlled by a smartphone or computer since just about everyone has one on them nowadays or at least has a computer in their house. Because of this I needed to make the wifi setup part easier. If I want to bring this over to a friend's place I don't want to have to connect it to their TV and use a keyboard to edit my config files. I stumbled across this post about a nifty rc.local script that would try to connect to pre-defined networks and if none are available it would fail over into an ad-hoc mode. I didn't like that the network names had to be hard-coded into the script so I tweaked it so it relied on the existing wpa_supplicant.conf file. A dhcp server was also required to make it easier to connect to, also Android devices seemed to have issues with specifying  a static IP and seemed to prefer to be assigned an ip by the device they were connecting to. The program dchpd handled this quite nicely. Next a webserver was required, lighttpd is a good lightweight server and I'd found a good tutorial here for that and php5, before long I was browsing to a placeholder page being hosted by my Pi!

The next challenge was figuring out how to a) take info the user entered into the webpage and pass it to another page or script and b) have a script run wpa_passphrase or write the wpa_supplicant.conf file directly. Since we had php installed I opted to use that, the user would enter their SSID, Encryption type, and password and using GET it would send it to a second php page. Within the second php page if the encryption was "open" it would write the into to a temporary wpa_supplicant.conf file then call a bash script that would copy it over the real file in /etc/wpa_supplicant/. If the encryption was wep, wpa, or wpa2 a text file would be written and the same bash script called, this bash script would read the info from the text file and use wpa_passphrase to generate the correct conf file and write it to /etc/wpa_supplicant/.  At the end of the bash file the system reboots and if the info was all entered correctly by the user the Pi should reboot and connect to the desired network without issue. I'm sure "pros" are reading this and thinking I've probably done this very inefficiently but I'm no coder and it worked so I'm happy :) In doing it this way though I had to include another step, the commands I needed to run required root access and anything the webserver was doing was being ran as a user called "www-data" which did not have root permissions. I was able to give the user www-data special permissions only to run certain scripts and commands as root by editing the sudoers file.

Once I had the wifi config scripts figured out it was very simple to add a safe shutdown button and a reboot button. Since it wasn't costing me anything I added a "Switch to AP Mode" button, this is great for when you have friends over that want to play their music on the PiFi-Mini but you don't want to give everyone access to your home network.

MPD Web Client
Initially I installed phpmpreloaded, a very nice collection of the leading MPD web clients all packaged up and allowing the user to switch between them. Unfortunately this got off to a bad start and after talking with the developer (who was nice enough to talk with me) we discovered there were deprecated functions being used that were not compatible with php5. From monitoring /var/log/lighttpd/error.log and /var/log/syslog I was able to find the offending lines in the files and replace them with the appropriate commands. Ultimately since I didn't plan on using the web interface much (due to the nice Android and iOS apps) I opted to only keep phpMP which is very full featured albeit not as aesthetically pleasing as some of the others. I had in mind the tutorials I was going to write and I didn't want to have to cover all of the php fixes and phpMP works out of the box so that's the one I went with.

Auto Mounting USB drives
I found out that by default raspbian does not automatically mount external drives. Luckily I found a nice little program called usbmount that handles this for us. Adding a symlink in the music folder pointing at /media/usb makes it visible to MPD.

LCD Screen and LCD Proc
Initially I wired up the LCD screen using a breadboard and these handy cables that for some reason are called "duPont cables".

MPD Info

When I first wired up the screen I followed a guide online, regrettably this guide used one of the GPIO pins that changed between rev1 and rev2 which made my task of making it fully compatible with both difficult later. My initial LCD was the run of the mill yellow backlight version.


Once I had it wired up correctly a friend told me about LCD Proc which he figured would be easier than writing code that controlled the LCD directly. I later found there was an add-on for LCD Proc called MPDLCD however I initially ran into issues getting that to work so I wrote my own code to interface with LCDProc using this guide. Maybe it's just because I'm still new to coding but I found the documentation for LCDProc very confusing at first, eventually with trial and error and help from a few people I started getting somewhere.At the start the most important thing for me was having it display the IP just so I didn't have to have it connected to a monitor at boot, I could read the IP and then just ssh into it.

LCDProc (LCDd) doesn't support the GPIO interface of the Pi by default, the guide I followed linked to a special set of drivers that someone was nice enough to compile. Later when checking compatibility with a rev2 Pi I discovered that the custom drivers weren't compatible, on a rev 1 pin 13 is GPIO#21 but on a rev 2 it is GPIO#27. After quite a bit of digging I found another generous soul had fixed the issue and posted a recompiled hd44780.so driver file.

Setting up the LCDd.conf file is pretty straighforward once you have the proper drivers, however you need to then communicate with the daemon to write to the LCD, this has it's own protocol and is like learning a whole new language. I wrote a python script that pulls song and player info from MPC, checks the airplay state, and also displays the IP address. I commented the script pretty well so hopefully if people want to tweak it they can.

 Later when I switched to a "prettier" blue LCD I found my scroll speed for the text was set to high, the text on blue LCD takes longer to fade and with the speed I had it set too would smear the text making it hard to read. I slowed down the scroll quite a bit and it works good now, for those that follow the tutorial and use a yellow background screen you might want to speed the scroll up again.

Custom PCB (not a requirement for building your own)
PCB - Actual - Front And Back

This wasn't really necessary but I wanted things to look nice and "finished", plus I'd been wanting to try out some of these cheap PCB manufacturers for awhile. Using KiCad, a free program, I designed a connection board and threw in a few extras like vias for a serial connection, a spot for a power switch, room for 6 buttons with pull up resistors, lcd contrast pot, LED backlight current limiting resistor. For $15 I got 10 5cm x 5cm boards shipped to me door, not too shabby! I realized I'd made a few oversights in the design, I have a nice large via for a +5V input but forgot to include a complimentary ground via. Luckily since I'd had the space I included a second set of vias for each the 13x2 Pi header and the 16x1 LCD header so I had lots of extra places I could solder a ground to. Eventually I plan on spending more time and making a better LCD shield PCB for the Pi but for now for anyone interested I'll include a link to my KiCad files and Gerber output in case anyone wants to use my own (slightly flawed) design.
PCB Files

PCB Layout


Prototype Case
I found a wooden box for $3 at the local dollar store that I figured would do nicely for a temporary enclosure.

Proto box w lcd but no speakers

At this point I was still using a little portable speaker for testing. Since the box was pretty much made out of balsa wood it was very light and easy to cut. I used a dremel and it was like cutting tissue paper really.

Mounting a Rev1 Pi that has no mounting holes
When the Pi first came out I was baffled by the fact they had omitted such a basic and crucial feature. They knew that the DIY community was lining up in droves to buy Raspberry Pi's so for them to be missing was a surprise. Furthermore they still have not released an official mechanical drawing of the Pi, there are ones floating around made by the community which range in accuracy from way out to very precise. Using the best drawings I could find and by taking my own measurements I made the drawing below in Skethup.

Mounting Rev 1 Raspberry Pi with Standoffs

The standoffs are actually plastic spacers, I had to glue a nylon nut to the bottom of each and cut a slot in the side for the pcb to fit. Not the most elegant solution but it worked :).



Speakers & Amplifier
When I first set out to start this project I'd ordered some parts from www.dx.com a great site full of cheap stuff and a decent DIY electronics section. I opted for this 3W+3W amplifier board for $3.50 and for speakers I chose these which were $2.80 each and the required 3W. The only downside to ordering from dx.com is that it takes about 3 weeks for your stuff to arrive. While I was at a local surplus store I came across some Logitec Z110 powered speakers for $10 so I snapped them up thinking they'd be good for the time being. Taking apart the Z110's was not an easy task and if any others try it I recommend caution. Once apart though I was delighted to find the speakers had very robust magnets and best of all the speakers had brackets for screws. Ultimately due to these nice mounting brackets I opted to use them instead of the ones I ordered from dx.com, the sound quality is good however the one flaw with my final design is the speakers aren't enclosed and they really should be for optimal sound. Also, when my dx.com speakers arrived I realized I had misread the description and they were a lot smaller than I thought they were so I probably wouldn't have used them anyway.

Prototype With Speakers - Inside
At this point I my custom PCB's still had not arrived yet so I was using perfboard.

Designing a better case
A good friend of mine is a talented metal worker and has his own plasma table for cutting metal. I highly recommend him, you can see his work over at his website http://mint-design.ca/

A while back I had done some photography work for him so in exchange he gave me some credit, finally with this project I had a chance to spend it. I used Sketchup to design the box and do some 3D renderings, he took the file and converted it to the type he needed and cut out my design using 0.080" aluminum. The thinness was really overkill but since he already had another job he was working on using the same material he just added mine when cutting.

Front Panel Dimensions - Middle Section Zoomed

Front and Back Panels with Dimensions
I know I listed way more dimensions than required :)

Pi Boombox Bookshelf Render 4 High Res w screen
A 3D rendering I made using Sketchup and Kerkythea

Start to Finish_WM
The case being plasma cut over at http://mint-design.ca

Once cut the flat sheets still required bending, all the holes needed to be drilled. PEM nuts were installed rather than using sheet metal screws so it could be taken apart and reassembled repeatedly. Once bent and all of the holes drilled it needed to be sanded to remove all of the tooling marks.

For speaker grills I used 50mm fan grills, later once everything was together I thought of adding metal handles to further add to the look as well as provide a little more protection.

The USB ports presented a problem, since the case was metal I couldn't have the wifi dongle inside because all of the signal would be blocked. I also wanted to be able to plug in a thumb drive with music on it. I was eventually able to find panel mount USB cables on ebay which suited the task perfectly.

IMG_20130429_210308
It still a bit of a jumble of wires but it's about as good as I could get it.

IMG_20130501_001228

Its never really finished is it?
With the hardware side pretty much done I set about refining the software a bit. I used some CSS to make the webUI look quite a bit nicer. I put my graphic design skills to work and created what I think is a nice sleek logo and branded it PiFi as a play on words for HiFi. I even went so far as to create a full user manual which is stored on the PiFi Mini and is available via the webUI.

Pi Boombox Web UI

If you want to check out the user manual here is a link to it. Keep in mind that the hardware description is for my design and the LCD stuff would only pertain to those choosing to do part 2 of the tutorial as well but general use info still applies. This manual is bundled in a zip file in part 1 of my tutorial that contains all the files needed for the web interface.

Moving forward I may add software features and tweak things here or there. I've picked up two usb DAC's that I've yet to try out with the PiFi mini, for the audio that MPD handles it should be a matter of simply adding another audio output in the mpd.conf file, as for Airplay (Shairport) I'm not so sure.

Acknowledgements:

I would like to thank the following people for their help while building this project:

Jason who posted his LCD tutorial over at Techfruits and took the time to email me back about some questions I had regarding talking to LCDProc.

James Laird who gifted the world with his airplay emulator shairport and was nice enough to try and help me troubleshoot some issues I was having getting shairport to work over ad-hoc (which ultimtely I never did get to work unfortunately).

Lee Dolsen who put together the phpmpreloaded package, unfortunately I didn't wind up using it due to php5 compatibility issues but he was very helpful with figuring out my issues. 
Conrad from Mint Design who not only cut out the box design but helped me with basically every stage up to the final bent drilled and sanded case.

If I've missed anyone I'm sorry,  I appreciate your help.

Resources and tutorials I've used:
Crackle free audio in MPD http://dbader.org/blog/crackle-free-audio-on-the-raspberry-pi-with-mpd-and-pulseaudio
Ad-hoc fail safe mode http://lcdev.dk/2012/11/18/raspberry-pi-tutorial-connect-to-wifi-or-create-an-encrypted-dhcp-enabled-ad-hoc-network-as-fallback/#comment-640
Shairport on Pi http://pi-raspberry.blogspot.ca/2012/08/shairport-raspberry-pi.html?showComment=1362968121371
MPD on Pi http://lesbonscomptes.com/pages/raspmpd.html and other google searches
Webserver using Lighttpd and php http://www.penguintutor.com/linux/light-webserver
Wiring up an HD44780 display - http://learn.adafruit.com/drive-a-16x2-lcd-directly-with-a-raspberry-pi/
Installing lcdproc and writing to it - http://www.tech-fruits.com/hardware/setting-up-lcd-via-gpio-on-raspi-part-1/
lcdproc developer guide - http://lcdproc.sourceforge.net/docs/current-dev.html
mpdlcd - https://github.com/rbarrois/mpdlcd
Audio glitch fix replacing start.elf and fixup.dat files https://github.com/raspberrypi/linux/issues/128
rtl8192 AP mode - http://blog.sip2serve.com/post/38010690 ... -rtl8192cu
Revised LCD proc drivers for Pi that support rev 2 http://www.raspberrypi.org/phpBB3/viewtopic.php?f=35&t=15967&start=50