My Universal Translator (PiTranslate) Featured on Make Magazine

This is a prototype I completed last year, but have been working closely with Make Magazine and Radioshack to create this great step by step guide for their Weekend Project Campaign. Check out the guide here, and the amazingly awesome video below:

Read More

Turn your Raspberry Pi into a Translator with Speech Recognition and Playback (60+ languages)

UPDATE
This project has been picked up by Make Magazine and Radioshack to create this great step by step guide for their Weekend Project Campaign. Check out the guide here, and the amazingly awesome video below:


I get many requests from people who are still looking for cheap, easy, and fun project ideas for their Raspberry Pi’s, so I wanted to share this translator project I’ve been working on. With very little effort, we can turn this 35$ mini-computer into a feature rich language translator that not only supports voice recognition and native speaker playback, but also is capable of dynamically translating between 1000’s of language pairs, FREE! Even if you are not interested in building this exact translational tool, there are still many parts of this tutorial that might be interesting to you (speech recognition, text to speech, Microsoft/Google translation APIs). Just like the rest of my posts, this one starts with our shopping list. Most of my readers will probably already have most of these items around the house:

Shopping List

QTY Required Items Price(USD)*
1 Raspberry PI $35.00
1 Micro USB cable $5.49
1 Logitech USB Headset $28.53
1 SD Card (class 4 and 4gb minimum) $13.10
Total: $82.12
Optional Items
1 Power Supply $9.95
1 HDMI Cable $2.28
1 Case $12.75

*There are definitely cheaper options available for USB Headsets, I chose the logitech as it is plug and play. For alternatives, check this list for verified Raspberry Pi supported sound cards

Assumptions

This tutorial assumes your Raspberry Pi has:
-the latest version of Raspian installed
-an internet connection
-the correct sound card drivers for your headset

Configuring and Testing Your Headset

Before we start writing any code, lets ensure that we can record and playback sound using our USB Headset. The easiest way to do this is with the built in linux commands ‘arecord’ and ‘aplay’. But first lets make sure our file system is up to date.

sudo apt-get update
sudo apt-get upgrade

Now, plug in your USB Headset and run the following commands

cat /proc/asound/cards
cat /proc/asound/modules

You should see that the Logitech Headset is listed as card 1. Additionally, the second command should show that the driver for card 0 (the default raspberry pi output) is snd_bcm2835 and the driver for card 1 (our logitech headset) is snd_usb_audio.

alsa cards module usb headset

This is a problem because it shows that Raspberry Pi defaults to transmitting sound over its built in hardware, and does not have an audio input device configured. To solve this, we need to update ALSA (Advanced Linux Sound Architecture) to use our Headset as default for audio input and output. This can be done by a quick change to the ALSA config file located in /etc/modprobe.d/alsa-base.conf:

sudo nano /etc/modprobe.d/alsa-base.conf

Near the end of this file, change the line that says

options snd-usb-audio index=-2

to

options snd-usb-audio index=0

Save and close the file and reboot the Raspberry Pi using the following command:

sudo reboot

After the system comes back online, the sound system should be reloaded so that when we rerun the above commands…

cat /proc/asound/cards
cat /proc/asound/modules

…we should see the USB Headset is now the default input/output device (card 0) as shown below.

alsa after update

We can now test this out by recording a 5 second clip from the microphone:

arecord -d 5 -r 48000 daveconroy.wav

and play it back through the headphone speakers:

aplay daveconroy.wav

To adjust the levels you can use the built in utility alsamixer. This tool handles both audio input and output levels.

sudo alsamixer

Now that our headset is configured, we can move onto the next step of converting from Speech to Text.

Speech to Text or Speech Recognition with a Raspberry Pi

There are a few options for speech recognition with rPi’s, but I thought the best solution for this tutorial was to use Google’s Speech to Text service. This service allows us to upload the file we just recorded and convert it to text (which we will later use to translate).

Let’s create a shell script to handle this process for us.

sudo nano stt.sh

with the following contents

echo "Recording your Speech (Ctrl+C to Transcribe)"
arecord -D plughw:0,0 -q -f cd -t wav -d 0 -r 16000 | flac - -f --best --sample-rate 16000 -s -o daveconroy.flac;
 
echo "Converting Speech to Text..."
wget -q -U "Mozilla/5.0" --post-file daveconroy.flac --header "Content-Type: audio/x-flac; rate=16000" -O - "http://www.google.com/speech-api/v1/recognize?lang=en-us&client=chromium" | cut -d\" -f12  > stt.txt
 
echo "You Said:"
value=`cat stt.txt`
echo "$value"

Make it executable

sudo chmod +x stt.sh

The last step before we can run the script is to install the FLAC Codec that is not included in the standard Raspian image.

sudo apt-get install flac

Now we can run the Script

./stt.sh

This will automatically start recording your voice, just press Ctrl+C when you are done speaking. At that point the script uploads the sound file to Google, they transcribe it and return it so it can be displayed on our screen. Pretty impressive for only a few lines of code! Sample output below:
here is an example speech recognition raspberry pi

Microsoft Translation and Google Text to Speech

Now that we can record our voice and convert it into text, we need to translate it to our desired foreign language. I would love to be able to use Google’s Translate tool for this, but unfortunately there is a 20$ sign up fee for use of this API. I plan on purchasing this for myself, but I wanted to make this project free so every one had an opportunity to try it.

As an alternative, we will be using Microsoft’s translate service which currently is still free for public use. The list of supported languages and their corresponding codes can be found here. In our previous example we used a simple shell script, but for the translation and playback process – I’ve written a more powerful python script.

All of this code can be found on my github repository (contributions welcome!).

Lets first create the file:

sudo nano PiTranslate.py

and add the following contents

import json
import requests
import urllib
import subprocess
import argparse
 
parser = argparse.ArgumentParser(description='This is a demo script by DaveConroy.com.')
parser.add_argument('-o','--origin_language', help='Origin Language',required=True)
parser.add_argument('-d','--destination_language', help='Destination Language', required=True)
parser.add_argument('-t','--text_to_translate', help='Text to Translate', required=True)
args = parser.parse_args()
 
## show values ##
print ("Origin: %s" % args.origin_language )
print ("Destination: %s" % args.destination_language )
print ("Text: %s" % args.text_to_translate )
 
text = args.text_to_translate
origin_language=args.origin_language
destination_language=args.destination_language
 
 
def speakOriginText(phrase):
    googleSpeechURL = "http://translate.google.com/translate_tts?tl="+ origin_language +"&q=" + phrase
    subprocess.call(["mplayer",googleSpeechURL], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
def speakDestinationText(phrase):
    googleSpeechURL = "http://translate.google.com/translate_tts?tl=" + destination_language +"&q=" + phrase
    print googleSpeechURL
    subprocess.call(["mplayer",googleSpeechURL], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
args = {
        'client_id': '',#your client id here
        'client_secret': '',#your azure secret here
        'scope': 'http://api.microsofttranslator.com',
        'grant_type': 'client_credentials'
    }
 
oauth_url = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13'
oauth_junk = json.loads(requests.post(oauth_url,data=urllib.urlencode(args)).content)
translation_args = {
        'text': text,
        'to': destination_language,
        'from': origin_language
        }
 
headers={'Authorization': 'Bearer '+oauth_junk['access_token']}
translation_url = 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate?'
translation_result = requests.get(translation_url+urllib.urlencode(translation_args),headers=headers)
translation=translation_result.text[2:-1]
 
speakOriginText('Translating ' + translation_args["text"])
speakDestinationText(translation)

For the script to run we need to import a few python libraries and a media player.

sudo apt-get install python-pip mplayer
sudo pip install requests

The last thing we need to do before we can run the script is sign up for a Microsoft Azure Marketplace API key. To do so, simply visit the marketplace, register an application, and then enter your client id and secret passcode into the script above.

Now we can run the script:

sudo python PiTranslate.py -o en -d es -t "hello my name is david conroy"

The script has 3 required inputs:
-o orignation language
-d destination language
-t “text to translate”

hola me nombre david conroy

The above command starts in English and translates to Spanish. My favorite part about the whole tutorial is how quickly you can change between languages you are translating, and how the returned voice changes according to the destination language.

Putting it all Together

It is actually very easy to combine the two scripts we created in this tutorial. In fact, it only takes one line of code to be added to the bottom of stt.sh shell script we created earlier (assuming PiTranslate.py and stt.sh are in the same directory).

sudo nano stt.sh

python PiTranslate.py -o en -d es -t "$value"

For those of you who skipped around in this tutorial, here is the entire script again with that line added:

echo "Recording your Speech (Ctrl+C to Transcribe)"
arecord -D plughw:0,0 -f cd -t wav -d 0 -q -r 16000 | flac - -s -f --best --sample-rate 16000 -o daveconroy.flac;
 
echo "Converting Speech to Text..."
wget -q -U "Mozilla/5.0" --post-file daveconroy.flac --header "Content-Type: audio/x-flac; rate=16000" -O - "http://www.google.com/speech-api/v1/recognize?lang=en-us&client=chromium" | cut -d\" -f12  > stt.txt
 
echo "You Said:"
value=`cat stt.txt`
echo "$value"
 
#translate from English to Spanish and play over speakers
python PiTranslate.py -o en -d es -t "$value"

Now, run the Speech To Text script again, and it will translate it from English to Spanish by default.

./stt.sh

Change your origin and destination languages in the last line as desired, and the PiTranslate.py script will do the rest! There are literally 1000’s of language pairs supported here. Here is a screenshot:

PiTranslate

Video Demo

I apologize this video is a little shaky, it was difficult holding the headset to the phone while running the scripts.

Known Limitations and Additional Resources

Both the origin and destination languages have to be supported by Microsoft Translate and Google Translate in order for this script to work.

Language Codes:
Microsoft
Google

Some special characters in certain languages will also cause trouble with the translation services, but I am working on a fix for that.

Conclusion

I really enjoyed working on this project as it incorporates a wide range of technology and tools to create something immediately useful and fun to play with. Plus, its all FREE. If you have any questions at all regarding this project, just leave a comment below or on github and I’d be happy to help you!

Read More

Beginners Guide To Turn Your Raspberry Pi into an Affordable Bitcoin Mining Rig

raspberry pi bitcoin rig
First off, I know this post is a little late in the game as it is becoming less profitable for amateurs to mine Bitcoins, and that there are more efficient ways to go about this. But I am writing this anyways for posterity’s sake as I know for a fact there are people out there who have idle Raspberry Pis and are looking for a project. I’m sure there are also others like myself who are just looking to learn more about cryptocurrencies. To get started, here is our shopping list (if you are reading this, you probably already own some of these items):

Shopping List

QTY Required Items Price(USD)*
1 Raspberry PI $35.00
1 Micro USB cable $5.49
1 ASICMiner Erupter USB 336MH/s Sapphire Bitcoin Miner $10.99
1 Powered USB Hub** $25.00
1 SD Card (class 4 and 2gb minimum) $7.49
Total: $83.97
Optional Items
1 Power Supply $9.95
1 HDMI Cable $2.28
1 Case $12.75
1 USB Fan (The mining devices run hot) $8.43

*Prices are subject to change
**The Pi alone can not power one of these miners, a Powered USB HUB is mandatory to mine bitcoin.

Bitcoin Wallets

Before we setup the Mining software on the Pi we need to setup a bitcoin wallet where we will store the credit from the mining. There are countless options(Software, Web, Mobile) when it comes to setting up a bitcoin wallet. I’ve listed a few below but there are many more and each method has its own risks, luckily bitcoin.org has a great writeup on how to choose a wallet.

Windows/MAC/Linux
Multi-Bit – Quick and Lightweight Bitcoin Wallet
Bitcoin-QT – Takes a day or two to download ~6gigs of Bitcoin Transactional Data
Armory – Desktop Add-on Application

Web/Hosted
Coinbase
Blockchain.info

Android
Bitcoin Wallet

iOS
Currently the app store does not allow any bitcoin wallet applications.

Mining Pools

Bitcoin Pooled Mining is the best way to get started mining. Pooled Mining allows multiple users to work together to “crack” a single bitcoin and then share the benefits fairly. Due to the competitive nature of mining, if you tried to mine on your own it could be a long time before you successfully mined anything. Pooled Mining is a nice way to receive smaller and more regular payouts instead. For people with slower rigs, pooled mining might be the only way you ever earn bitcoins.

Two Mining pools I recommend and have verified are:
Slush’s Pool
BTC Guild

The setup for both pools is straight forward. You create a username, password, and then worker credentials(for each mining device). You also add the bitcoin wallet address you created above to your pool so you receive bitcoin payments when you hit the pool’s payout thresholds (usually around .01 BTC). It’s also recommended you sign up for multiple pools in case one experiences technical difficulties, the software we are about to install will switch if one goes down.

Installing Mine Peon the rPi

Now that we have a bitcoin wallet and have joined a mining pool, Neil Fincham and his project Mine Peon makes getting the software running on the rPi quite easy. Mine Peon is an ARM Mining Platform that is built specifically for Raspberry Pi. It is built on Arch Linux and uses the popular cgminer and bfgminer for the heavy lifting. To get started, you simply download the latest image here and burn it to your SD card.
If you are using Windows to flash your SD Card, I recommend using Win32DiskImager. This tool can also be used after our initial setup to create an image of our finalized implementation(very useful as a backup).

mine-peon

For other operating systems, you can find a handy guide on flashing SD cards from eLinux.org here.

After the image is flashed, you can boot your device. The first boot takes about a minute as it needs to generate the SSH keys, but future boots take only about 10 seconds. Use your router or keyboard/video/mouse to find out the IP address of the rPi. The default username and password for SSH and for the WebUI are:

Username: minepeon
Password: peon

After the rPi has booted, you can navigate to Mine Peon’s handy WebUI by opening your browser and entering the Raspberry Pi’s IP address. There you can insert the mining pool and worker information.
mine peon pools

The best part about Mine Peon is that it automatically supports the USB mining devices, so you can be up and running in a few minutes without having to worry about drivers/compatability issues. There are even handy graphs to check your stats!
mine peon stats

For Further information on Mine Peon check out their installation guide here.

Closing Remarks

Are you going to get rich quick using the Raspberry Pi for bitcoin mining? Of course not. This tutorial was never meant to give that impression. But, could you potential recoup your investment costs and perhaps end up a couple bucks ahead after 6-12 months? Definitely possible!

PS – If you have any questions about earning potential, profitability, or just basic setup, just add a comment below and I’d be happy to help! And if you get your rPi working and mining Bitcoin – Feel free to send a tip to my blog’s BTC address:

1Q9ASkZFAHXLvpPAzAVipcKUH5Vy2xmsA6

Donate Bitcoins

Thanks for reading!

Read More

Using your Raspberry Pi as a Wireless Router and Web Server

I got an email earlier in the week from some students at SoonChunHyang University, about 100km from Seoul, Korea. They are working on a project where they are using Raspberry Pi’s as a web server, but also wanted to be able to control the Pi’s via their smart phones and desktops. They ran into issues because they were using the (previously) unsupported WiFi Adapter (RTL8188CUS chipset) that I wrote about in this Raspberry Pi WiFi Hotspot post.

A computer science graduate myself, I offered to write a tutorial for them to help them out. This entire tutorial might not be relevant for everyone, but I cover a lot of issues that people struggle with.

  • -Setting up a DHCP Server
  • -Setting up a Wireless Access Point
  • -Setting up an rPi as a Router
  • -Enabling IP Forwarding

I’ll begin with a fresh image of the Raspbian and just a regular ethernet cable to configure it. I’ve always recommended Raspbian because it is an optimized version of Debian built specifically for Raspberry Pi’s. The last stable downloads can be found here.

To flash your SD Card, you will need to unzip the image and write it your SD card using Win32DiskImager. This tool can also be used to after our initial setup to create an image of our finalized implementation(very useful as a backup).

windiskimager

After the image is flashed, you can boot your device. At this point you can use your HDMI Cable/Mouse/Keyboard for your initial configuration, or you can use an SSH Client like Putty to connect. The default hostname, login, and password are as follows:

host:raspberrypi
Username: pi
Password: raspberry

raspberry pi putty

For this tutorial, I will be using putty. On first boot, you will be prompted with a configuration tool called Raspi-Config. If the raspi-config doesnt load automatically, just enter the following command from the shell to get started.

sudo raspi-config

raspi-config-screenshot

The settings I recommend you update are

update
expand_rootfs
change_pass
change_timezone
memory_split

The usual distribution images are 2 GB. When you copy the image to a larger SD card you have a portion of that card unused. expand_rootfs expands the initial image to expand to fill the rest of the SD card, giving you more space. By default, 64mb is reserved for the Graphical UI. Since we plan on using this as a web server, I reduce this to 32mb with the memory_split command.

After you finish your changes to the raspi-config, you should reboot your pi using the following command:

sudo shutdown -r now

At this point we have a fully functional linux server, but we still need to install apache and get the hotspot/routing functions working. The first part is pretty easy. Run the following commands from the shell to install Apache.

sudo apt-get update
sudo apt-get install apache2

The location of the Apache configuration file is

/etc/apache2/apache2.conf

After this is completed, give it a try! Navigate to the IP or Hostname of your Rasberry Pi in your browser, and you should see the Apache Splash “It works!” Screen.

it works apache

I believe this is what the students at SoonChunHyang already have working. But, they want to be able to access this web server over a WiFi Hotspot running on the same Raspberry Pi. In order to do this, we need to install hostapd.

sudo apt-get install hostapd

The following steps are only for people who have WiFi adapters with the RTL8188CUS Chipset, if you don’t, please skip ahead to the section titled configuring Hostapd.
I believe the whole crux of their problem so far is that it is the apt hosted copy of hostapd is not compatible with the RTL8188CUS chipset they are using. But, thanks to the Edimax team, I’ve got a replacement hostapd binary to resolve this issue. I don’t think they will be able to get this working without it.

To download and replace the installed binary version of hostapd we just installed, they need to issue the following commands:

wget http://www.daveconroy.com/wp3/wp-content/uploads/2013/07/hostapd.zip
unzip hostapd.zip 
sudo mv /usr/sbin/hostapd /usr/sbin/hostapd.bak
sudo mv hostapd /usr/sbin/hostapd.edimax 
sudo ln -sf /usr/sbin/hostapd.edimax /usr/sbin/hostapd 
sudo chown root.root /usr/sbin/hostapd 
sudo chmod 755 /usr/sbin/hostapd

Configuring Hostapd

Now that we’ve updated the binary copy of hostapd, we need to configure it. To do so, create the following file

sudo nano /etc/hostapd/hostapd.conf

with the following contents:

interface=wlan0
driver=rtl871xdrv
ssid=DaveConroyPi
channel=6
wmm_enabled=1
wpa=1
wpa_passphrase=0000000000
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
auth_algs=1
macaddr_acl=0

 

In previous tutorials, I have used bridge-utils here to help bridge the connection between the interfaces wlan0 and eth0, but in this case we want the wireless card and rPi to handle the routing and dhcp. So , we may be able to connect to the access point, but we won’t get an IP just yet. To do that, we need to define a subnet for our wireless card.

sudo nano /etc/network/interfaces

and add the following 3 lines

iface wlan0 inet static
address 10.10.0.1
netmask 255.255.255.0

 

Then we have to enable dhcp on the pi for this network so that any devices that connect can get an IP addresss

sudo apt-get install isc-dhcp-server
sudo nano /etc/dhcp/dhcpd.conf

and make sure you have the following contents:


authoritative; #be careful with this setting
ddns-update-style none;
default-lease-time 600;
max-lease-time 7200;
log-facility local7;


#for the wireless network on wlan0
subnet 10.10.0.0 netmask 255.255.255.0 {
range 10.10.0.25 10.10.0.50;
option domain-name-servers 8.8.8.8, 8.8.4.4;
option routers 10.10.0.1;
interface wlan0;
}

 

At this point we should reboot to test HostAPD and DHCP.

sudo reboot

After the rPi comes back up, start hostapd in the background, then reboot the dhcp server

sudo hostapd -B /etc/hostapd/hostapd.conf
sudo /etc/init.d/isc-dhcp-server restart

At this point you should be able to join the wireless network, get an IP, and also hit the local apache web server. If it connects, we will want to start this wireless access point on boot with the following commands

sudo nano /etc/default/hostapd

and uncommenting and updating the following line

DAEMON_CONF="/etc/hostapd/hostapd.conf"

So, if you have followed these steps correctly, you can now provide DHCP servers to any clients, and also allow serve those clients your Apache web pages.

it works apache raspberry pi

There is only one problem remaining. The clients who have connected to your access point can not get further than your Raspberry Pi, therefore have no internet access.

To solve this, we need to enable IP forwarding on the rPi. You can not reboot at this point forward or all future changes will be lost. To save time, we are going to run the final commands as root.

sudo su
echo 1 > /proc/sys/net/ipv4/ip_forward

Then, update /etc/sysctl.conf and uncomment this line

nano /etc/sysctl.conf

net.ipv4.ip_forward=1

Save the file.

The final step is to insert an iptables rule to allow NAT. (eth0 being the interface which is connected to the internet)

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

We also need to save these IP Table settings so they are enabled every time you boot the rPi. To save these settings to a file, use the following command.

iptables-save > /etc/iptables.up.rules

To load them at boot, we need to create a script in /etc/network/if-pre-up.d/

nano /etc/network/if-pre-up.d/iptables

with the following contents:

#!/bin/sh
#This script restores iptables upon reboot

iptables-restore < /etc/iptables.up.rules exit 0

Then, verify the permissions so that it will start on boot.

chown root:root /etc/network/if-pre-up.d/iptables 
chmod +x /etc/network/if-pre-up.d/iptables
chmod 755 /etc/network/if-pre-up.d/iptables

And we are done! When you reboot your Raspberry Pi should be working as an Access Point, a Web Server, a DHCP Server, and an Internet Ready Router!

internet working raspberry pi

Read More

Ditch Your Cable Modem/ISP With a Tethered iPhone and Raspberry Pi

Last month, I wrote a blog post about tethering your iPhone to your Raspberry Pi. I got a lot of emails regarding this post, and one in particular caught my eye. It was from a fellow tech-enthusiast/cord cutter who wanted to save the ~60$ a month that he was paying for his cable modem, and instead tether his iPhone which already has a data plan.

Before getting started I realize this setup is not for power users, but instead for people who may

  • -travel often for work
  • -own a second residence and don’t want to pay two internet bills
  • -have tethering paid for by their employer
  • -have light internet usage or unlimited data plans
  • -cord cutters on a budget

 

Intrigued by this idea, I started testing it myself and got it working fairly easily. I already covered the full operating system setup in the Raspberry Pi/iPhone Tethering post, so I will just start with the tethering portion for this tutorial.

Prerequisites

Make sure your iPhone is disconnected and proceed to install the following iPhone and file system utilities on the Pi. Open up a terminal or SSH into your Pi and run the following commands:

sudo apt-get update
sudo apt-get install gvfs ipheth-utils
sudo apt-get install libimobiledevice-utils ifuse 
sudo apt-get install gvfs-backends gvfs-bin gvfs-fuse

After these are installed, and with your iPhone still not plugged in, lets take a look at our available interfaces. Run the following commands:

ifconfig -s

If you have a standard installation, you should see two interfaces, eth0 and lo.

tether iphone 5 raspberry pi

The reason we did this step was to make sure we correctly identified the name of the iPhone’s network interface. Now that you have this list you can turn on your iPhone’s Personal Hotspot and then plug it into your Raspberry Pi’s USB port, and issue the same command.

ifconfig -s

iphone raspberry pi

Your Pi should now recognize your iPhone is plugged in and assign its network interface a name, usually eth1.

Hot Swapping

So now we have our Raspberry Pi Recognizing our iPhone, but in the scenario we are trying to account for – we need to be able to hotswap our phone on and off our networks for it to be truly useful. To do so, unplug your iPhone and then open up your network interfaces file.

sudo nano /etc/network/interfaces

and add the following lines, where eth1 is the name identified above.

allow-hotplug eth1
iface eth1 inet dhcp

Save and close the interfaces file.

In my testing, tethering with only worked when the iPhone is mounted. To do this, we need to implement the ifuse package we downloaded earlier. First, create a mount directory for the iPhone

sudo mkdir /media/iPhone

Now we can disconnect the ethernet of the Pi, turn on the iPhone’s Hotspot , and plug in then mount the iPhone.

sudo ifuse /media/iPhone

The Internet should now be tethered from your iPhone. Remember, at this point the iPhone must manually be mounted each time it is plugged using the ifuse command.

Finishing the iPhone Portion

Having the Raspberry Pi connected to the internet via the iPhone is an important step, but it is a hassle to have to mount the iPhone everytime.

To automate the process, we need to create the following script named iphoneconnect in /lib/udev/:

sudo nano /lib/udev/iphoneconnect

#!/bin/bash
umount /media/iPhone #when the iPhone is unplugged, it is not automatically unmounted.
ifuse /media/iPhone
/etc/init.d/networking restart #this may not be necessary, but just a safe guard to rebridge the connection
ipheth_pair

Remember to make the script executable

sudo chmod 755 /lib/udev/iphoneconnect

The final step is to edit the file ’90-iphone-tether.rules’ in the ‘/lib/udev/rules.d’ directory.

sudo nano /lib/udev/rules.d/90-iphone-tether.rules

This is the script that runs automatically when ever we plug in the iPhone, and we want to edit it to call the script we created (/lib/udev/iphoneconnect) instead of what it currently calls (/lib/udev/ipheth_pair). To do this, we just edit the 5th line of the file replacing ipheth_pair with iphoneconnect.

The file should look like this


# udev rules for setting correct configuration and pairing on tethered iPhones
ATTR{idVendor}!="05ac", GOTO="ipheth_rules_end"

# Execute pairing program when appropriate
ACTION==”add”, SUBSYSTEM==”net”, ENV{ID_USB_DRIVER}==”ipheth”, SYMLINK+=”iphone”, RUN+=”iphoneconnect”

LABEL=”ipheth_rules_end”

 

Success!

iPhone Tethered Raspberry Pi

Replacing your Cable Modem with the Raspberry Pi

This is the part of this tutorial I found the most fascinating. I’m sure most of my readers already have their Wireless Router and Firewall configured exactly how they want, and don’t want to have to change any of those settings. The goal here is to just take the uplink ethernet cable from the router out of the cable modem and into the Raspberry Pi and then practice business as usual.

Bridging the Gap

In order to do this, we just need to bridge the connection from the iPhone interface (eth1) with the built in ethernet interface (eth0). To do so, we first need to install the bridge utilities,

sudo apt-get install bridge-utils

and then edit our network interfaces file again

sudo nano /etc/network/interfaces

and add the following lines

auto br0
iface br0 inet dhcp
bridge_ports eth1 eth0

Save and close the interfaces file, and reboot the rPi

sudo reboot

At this point, I logged into my Wireless Router and gave it a static IP, and used google’s public DNS. I am sure this step could be skipped if we setup a simple dhcp server on the rPi. When I have that working I will update this post with the optional step.

router ss

Results

Here is just a quick picture of my demo environment.
iphone-router-setup
I also did some speed tests and got some remarkable results. 10mb/s over Verizon’s 4G LTE. I am willing to bet that is faster than many home WiFi networks. Upload speeds were a less impressive, but still useful .25 mb/s.

downloadspeed

Troubleshooting

I noticed that because of the boot order of the network interfaces, and mounting of the iPhone, it worked best if I did a quick network reset after the device had fully booted. To do so, edit the rc.local file

sudo nano /etc/rc.local

and add the following line before the exit 0

/etc/init.d/networking restart

This will reestablish the bridge if the iPhone wasn’t tethered in time on boot.

If you have any other questions, just comment on this post.

Read More

Turn Your Raspberry Pi Into a WiFi Hotspot with Edimax Nano USB EW-7811Un (RTL8188CUS chipset)

I’m writing this blog to help anyone with an Edimax Nano USB WiFi adapter (EW-7811Un) configure a Wireless Accesss Point. The main reason I wrote this post is because the Edimax was the first wireless adapter I ever recommended(turning a Raspberry Pi into a fully functional web server). I chose this adapter because it works out of the box, is cheap, and has a really low profile. But when I started the process of trying to turn my rPi into a WiFi hotspot, it seemed that every tutorial out there claimed that the Edimax card I had recommended “doesn’t support Access Point”.

Luckily for you and me, this is not the case.

edimax-dime-ss

Given the varied level of experience of my readers, this tutorial will start from scratch. If you already have your operating system running, skip forward as needed.

For this tutorial I am using Raspbian. I recommend it because it is an optimized version of Debian built specifically for Raspberry Pi’s. The last stable downloads can be found here.

To flash your SD Card, you will need to unzip the image and write it your SD card using Win32DiskImager. This tool can also be used to after our initial setup to create an image of our finalized implementation(very useful as a backup).

windiskimager

After the image is flashed, you can boot your device. At this point you can use your HDMI Cable/Mouse/Keyboard for your initial configuration, or you can use an SSH Client like Putty to connect. The default hostname, login, and password are as follows:

host:raspberrypi
Username: pi
Password: raspberry

raspberry pi putty

For this tutorial, I will be using putty. On first boot, you will be prompted with a configuration tool called Raspi-Config. If the raspi-config doesnt load automatically, just enter the following command from the shell to get started.

sudo raspi-config

raspi-config-screenshot

The settings I recommend you update are

update
expand_rootfs
change_pass
change_timezone
memory_split

The usual distribution images are 2 GB. When you copy the image to a larger SD card you have a portion of that card unused. expand_rootfs expands the initial image to expand to fill the rest of the SD card, giving you more space. By default, 64mb is reserved for the Graphical UI. Since we plan on using this as a WiFi Hotspot, we can reduce this to 32mb with the memory_split command.

After you finish your changes to the raspi-config, you should reboot your pi using the following command:

sudo shutdown -r now

At this point you have a fully functional linux server, but we still need to check our network card and setup our WiFi hotspot.

Prerequisites

The first thing you need to do is make sure you have an existing wired connection to your rPi. After that, you need to install the following packages.

sudo apt-get install bridge-utils hostapd

The whole crux of the issue is that it is the apt hosted copy of hostapd that is not compatible with the RTL8188CUS chipset. But, thanks to the Edimax team, I’ve got a replacement hostapd binary to resolve this issue. This tutorial will not work without it.

To download and replace the installed binary version of hostapd we just installed, issue the following commands:

wget http://www.daveconroy.com/wp3/wp-content/uploads/2013/07/hostapd.zip
unzip hostapd.zip 
sudo mv /usr/sbin/hostapd /usr/sbin/hostapd.bak
sudo mv hostapd /usr/sbin/hostapd.edimax 
sudo ln -sf /usr/sbin/hostapd.edimax /usr/sbin/hostapd 
sudo chown root.root /usr/sbin/hostapd 
sudo chmod 755 /usr/sbin/hostapd

*Note, some people don’t like the idea of installing from untrusted 3rd parties, so if If would rather compile your own binary, you can download the realtek driver here . You will have to navigate to the ~/RTL8188C_8192C_USB_linux_v3.4.4_4749.20121105/wpa_supplicant_hostapd/wpa_supplicant_hostapd-0.8/hostapd and run a make, make install, then hostapd like i did above.

Bridge the Network Connections

Now that we have the proper hostapd installed, we need to create a bridge between our ethernet connection and our Edimax Wireless card. To do this, we need to edit our network interfaces:

sudo nano /etc/network/interfaces

To avoid any conflicts, you need to delete or comment out(#) any lines conatining wlan0 and then add the following text to bridge the connections, assuming your ethernet and wireless adapters are named eth0 and wlan0( use ifconfig -a to check)

auto br0
iface br0 inet dhcp
bridge_ports eth0 wlan0

The resulting file should look like this:

#loopback adapter
auto lo
iface lo inet loopback

#wired adapter
iface eth0 inet dhcp

#bridge
auto br0
iface br0 inet dhcp
bridge_ports eth0 wlan0

Configuring Hostapd

Now that our interfaces are setup, we need to configure hostapd. To do so, create the following file

sudo nano /etc/hostapd/hostapd.conf

with the following contents:

interface=wlan0
driver=rtl871xdrv
bridge=br0
ssid=DaveConroyPi
channel=1
wmm_enabled=0
wpa=1
wpa_passphrase=ConroyPi
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
auth_algs=1
macaddr_acl=0

Wrapping Up

We should be finished now, and afer a reboot

sudo reboot

you can test your configuration using the following command

sudo hostapd -dd /etc/hostapd/hostapd.conf

If it runs as expected, you can add it to startup by editing

sudo nano /etc/default/hostapd

and uncommenting and updating the following line

DAEMON_CONF="/etc/hostapd/hostapd.conf"

That should do it! I’m happy to answer any questions, just comment on this post. Thanks for reading!Raspberry Pi as WiFi Hotspot

Read More