Book Image

Raspberry Pi for Python Programmers Cookbook - Second Edition

Book Image

Raspberry Pi for Python Programmers Cookbook - Second Edition

Overview of this book

Raspberry Pi cookbook for Python Programmers is a practical guide for getting the most out of this little computer. This book begins by guiding you through setting up the Raspberry Pi, performing tasks using Python 3 and introduces the first steps to interface with electronics. As you work through each chapter you will build up your skills and knowledge and apply them as you progress throughout the book, delving further and further into the unique abilities and features of the Raspberry Pi. Later, you will learn how to automate tasks by accessing files, build applications using the popular Tkinter library and create games by controlling graphics on screen. You will harness the power of the built-in graphics processor by using Pi3D to generate your own high quality 3D graphics and environments. Connect directly to the Raspberry Pi’s hardware pins to control electronics from switching on LEDs and responding to push buttons right through to driving motors and servos. Learn how to monitor sensors to gather real life data and to use it to control other devices, and view the results over the Internet. Apply what you have learnt by creating your own Pi-Rover or Pi-Hexipod robots. Finally, we will explore using many of the purpose built add-ons available for the Raspberry Pi, as well as interfacing with common household devices in new ways.
Table of Contents (18 chapters)
Raspberry Pi for Python Programmers Cookbook - Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Hardware and Software List
Index

Networking and connecting your Raspberry Pi to the Internet via a USB Wi-Fi dongle


By adding a USB Wi-Fi dongle to the Raspberry Pi's USB port, even models without built-in Wi-Fi can connect to and use the Wi-Fi network.

Getting ready

You will need to obtain a suitable USB Wi-Fi dongle; and in some cases, you may require a powered USB hub (this will depend on the hardware version of the Raspberry Pi you have and the quality of your power supply). General suitability of USB Wi-Fi dongles will vary depending on the chipset that is used inside and the level of Linux support available. You may find that some USB Wi-Fi dongles will work without installing additional drivers (in which case you can jump to configuring it for the wireless network).

A list of supported Wi-Fi adapters is available at http://elinux.org/RPi_USB_Wi-Fi_Adapters.

You will need to ensure that your Wi-Fi adapter is also compatible with your intended network; for example, it supports the same types of signals 802.11bgn and the encryptions WEP, WPA, and WPA2 (although most networks are backward compatible).

You will also need the following details of your network:

  • Service set identifier (SSID): This is the name of your Wi-Fi network and should be visible if you use the following command:

    sudo iwlist scan | grep SSID
    
  • Encryption type and key: This value will be None, WEP, WPA, or WPA2, and the key will be the code you normally enter when you connect your phone or laptop to the wireless network (sometimes, it is printed on the router).

You will require a working internet connection (that is, wired Ethernet) in order to download the required drivers. Otherwise, you may be able to locate the required firmware files (they will be the .deb files), and copy them to the Raspberry Pi (that is, via a USB flash drive; the drive should be automatically mounted if you are running in desktop mode). Copy the file to a suitable location and install it with the following command:

sudo apt-get install firmware_file.deb

How to do it…

This task has two stages; first, we identify and install firmware for the Wi-Fi adapter, and then we need to configure it for the wireless network.

We will try to identify the chipset of your Wi-Fi adapter (the part that handles the connection); this may not match the actual manufacturer of the device.

An approximate list of supported firmware can be found with this command:

sudo apt-cache search wireless firmware

This will produce results similar to the following output (disregarding any results without firmware in the package title):

atmel-firmware - Firmware for Atmel at76c50x wireless networking chips.
firmware-atheros - Binary firmware for Atheros wireless cards
firmware-brcm80211 - Binary firmware for Broadcom 802.11 wireless cards
firmware-ipw2x00 - Binary firmware for Intel Pro Wireless 2100, 2200 and 2915
firmware-iwlwifi - Binary firmware for Intel PRO/Wireless 3945 and 802.11n cards
firmware-libertas - Binary firmware for Marvell Libertas 8xxx wireless cards
firmware-ralink - Binary firmware for Ralink wireless cards
firmware-realtek - Binary firmware for Realtek wired and wireless network adapters
libertas-firmware - Firmware for Marvell's libertas wireless chip series (dummy package)
zd1211-firmware - Firmware images for the zd1211rw wireless driver

To find out the chipset of your wireless adapter, plug the Wi-Fi-adapter into Raspberry Pi, and from the terminal, run the following command:

dmesg | grep 'Product:\|Manufacturer:'

Note

This command stitches together two commands into one. First, dmesg displays the message buffer of the kernel (this is an internal record of system events that have occurred since power on, such as detected USB devices). You can try the command on its own to observe the complete output.

The | (pipe) sends the output to the grep command, grep 'Product:\|Manuf' checks it and only returns lines that contain Product or Manuf (so we should get a summary of any items that are listed as Product and Manufacturer). If you don't find anything or want to see all your USB devices, try grep 'usb' instead.

This should return something similar to the following output (in this case, I've got a ZyXEL device, which has a ZyDAS chipset (a quick Google search reveals that zd1211-firmware is for ZyDAS devices):

[    1.893367] usb usb1: Product: DWC OTG Controller
[    1.900217] usb usb1: Manufacturer: Linux 3.6.11+ dwc_otg_hcd
[    3.348259] usb 1-1.2: Product: ZyXEL G-202
[    3.355062] usb 1-1.2: Manufacturer: ZyDAS

Once you have identified your device and the correct firmware, you can install it, as you would for any other package available through apt-get (where zd1211-firmware can be replaced with your required firmware). This is shown in the following command:

sudo apt-get install zd1211-firmware

Remove and reinsert the USB Wi-Fi dongle to allow it to be detected and the drivers loaded. We can now test if the new adapter is correctly installed with ifconfig. The output is shown as follows:

wlan0     IEEE 802.11bg  ESSID:off/any
          Mode:Managed  Access Point: Not-Associated   Tx-Power=20 dBm
          Retry  long limit:7   RTS thr:off   Fragment thr:off
          Power Management:off

The command will show the network adapters present on the system. For Wi-Fi, this is usually as wlan0, or wlan1, or so on if you have installed more than one. If not, double-check the selected firmware, and perhaps try an alternative or check on the site for troubleshooting tips.

Once we have the firmware installed for the Wi-Fi adapter, we will need to configure it for the network we wish to connect. We can use the GUI as shown in the previous recipe, or we can manually configure it through the terminal as shown in the following steps:

  1. We will need to add the wireless adapter to the list of network interfaces, which is set in /etc/network/interfaces, as follows:

    sudo nano -c /etc/network/interfaces 
    

    Using the previous wlan# value in place of wlan0 if required, add the following command:

    allow-hotplug wlan0
    iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
    

    When the changes have been made, save and exit by pressing Ctrl + X, Y, and Enter.

  2. We will now store the Wi-Fi network settings of our network in the wpa_supplicant.conf file (don't worry if your network doesn't use the wpa encryption; it is just the default name for the file):

    sudo nano -c /etc/wpa_supplicant/wpa_supplicant.conf
    

    It should include the following:

    ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
    update_config=1
    country=GB

    The network settings can be written within this file as follows (that is, if the SSID is set as theSSID):

    • If no encryption is used, use this code:

      network={
        ssid="theSSID"
        key_mgmt=NONE
      }
    • With the WEP encryption (that is, if the WEP key is set as theWEPkey), use the following code:

      network={
        ssid="theSSID"
        key_mgmt=NONE
        wep_key0="theWEPkey"
      }
    • For the WPA or WPA2 encryption (that is, if the WPA key is set as theWPAkey), use the following code:

      network={
        ssid="theSSID"
        key_mgmt=WPA-PSK
        psk="theWPAkey"	
      }
  3. You can enable the adapter with the following command (again, replace wlan0 if required):

    sudo ifup wlan0
    

    Use the following command to list the wireless network connections:

    iwconfig
    

    You should see your wireless network connected with your SSID listed as follows:

    wlan0     IEEE 802.11bg  ESSID:"theSSID"
              Mode:Managed  Frequency:2.442 GHz  Access Point: 00:24:BB:FF:FF:FF
              Bit Rate=48 Mb/s   Tx-Power=20 dBm
              Retry  long limit:7   RTS thr:off   Fragment thr:off
              Power Management:off
              Link Quality=32/100  Signal level=32/100
              Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
              Tx excessive retries:0  Invalid misc:15   Missed beacon:0
    

    If not, adjust your settings and use sudo ifdown wlan0 to switch off the network interface, and then sudo ifup wlan0 to switch it back on.

    This will confirm that you have successfully connected to your Wi-Fi network.

  4. Finally, we will need to check whether we have access to the Internet. Here, we have assumed that the network is automatically configured with DHCP and no proxy server is used. If not, refer to the Connecting to the Internet through a proxy server recipe.

    Unplug the wired network cable, if still connected, and see if you can ping the Raspberry Pi website, as follows:

    sudo ping www.raspberrypi.org
    

Tip

If you want to quickly know the IP address currently in use by the Raspberry Pi, you can use hostname -I. Or to find out which adapter is connected to which IP address, use ifconfig.

There's more…

The Model A version of the Raspberry Pi does not have a built-in network port; so in order to get a network connection, a USB network adapter will have to be added (either a Wi-Fi dongle, as explained in the preceding section, or a LAN-to-USB adapter, as described in the following section).

Using USB wired network adapters

Just like USB Wi-Fi, the adapter support will depend on the chipset used and the drivers available. Unless the device comes with Linux drivers, you may have to search the Internet to obtain the suitable Debian Linux drivers.

If you find a suitable .deb file, you can install it with the following command:

sudo apt-get install firmware_file.deb

Also check using ifconfig, as some devices will be supported automatically, appear as eth1 (or eth0 on Model A), and be ready for use immediately.