Raspberry Pi For Embedded Systems

Compiled by
Frank W. Miller, Ph.D.
University of Colorado

Copyright © Frank W. Miller

INTRODUCTION

This booklet brings together a variety of sources to provide a primer for using the Raspberry Pi single board computer in embedded environments. The material was compiled for a short course taught at the University of Colorado Boulder in the Fall of 2015.

The material is organized in three major sections. This first section contains an introduction to the Raspberry Pi 2 Model B (RPi2). The material will assist you in getting your basic RPi2 system up and running. The second section focuses on the RPi2 GPIO connector. There are a variety of digital I/O lines that are available through this connector that can be used to do kewl embedded control applications. The third section discusses the use of networking to allow your embedded RPi2 to communicate with the rest of the world via Internet connections.

The flow of the material designed to provide the reader with ability to use the RPis as a network controllable embedded system. This means that the RPi2 is assumed to be connected to various real-world sensing and control elements and that access/control of those elements is accomplished using a web or remote command line interface.

Hardware Specifications

This description is focused on one specific hardware version of the Raspberry Pi used in a class taught at the University of Colorado in the Fall of 2015, the Raspberry Pi 2 Model B.

Broadcom BCM2836 ARM7 Quad Core Processor powered Single Board Computer running at 900MHz

1GB RAM

40pin extended GPIO

4 x USB 2 ports

4 pole Stereo output and Composite video port

Full size HDMI

CSI camera port for connecting the Raspberry Pi camera

DSI display port for connecting the Raspberry Pi touch screen display

Micro SD port for loading your operating system and storing data

Micro USB power source

Figure 1: Top View of Raspberry Pi 2 Model B (circa. 2015).

Creating a Raspbian SD Card

The first thing to do is to create a bootable SD card that holds the software your RPi2 will be running. This booklet makes us of the Raspbian variant of the Debian Linux operating system that has been prepared for the RPi2

Needed: ≥4 GB microSD card, USB (micro)SD card adapter

Figure 2 illustrates a typical USB to SD adapter. The main case provides a slot for an SD card. Most microSD cards are delivered with an SD to microSD adapter. You should insert your microSD card into the SD card adapter and then insert the SD card adapter into the SD Card Slot on the USB to SD adapter. This USB to SD adapter is then inserted into your computer and probably shows up as a drive (if it has been formatted).

Figure 2: An Example microSD to USB adapter.

You'll also need a version of the operating system itself. You can download the most recent images at:

https://www.raspberrypi.org/downloads/raspbian/

This description assumes the use of the image file:

2015-05-05-debian-wheezy.zip

Once you have downloaded the .zip file, you can extract the image file:

2015-05-05-debian-wheezy.img

Insert the SD card into the USB adapter and insert the USB adapter into a USB port. Write the image to the SD card. This must be done using special utilities.

Windows:

Use Win32DiskImager to write the .img file to the SD card

Linux:

Determine the USB adapter device name in /dev Under most Linux distros that use udev, there should be an additional disk named for example /dev/sdb if your system has only one internal disk and no other storage devices inserted. You can check the dmesg logs for recent device and/or file system activity to determine the specific device name.

There should be two associated devices, e.g. /dev/sdb and the associated /dev/sdb1. The first device name is used when you need to deal with the storage device as a whole unit. The second is used to access the partition on the storage device that contains the Linux filesystem.

dd the Raspbian image file onto the SD card. An example dd command:

dd if=2015-05-05-raspbian-wheezy.img of=/dev/sdb bs=4096

The device name specified for the output file (of=) should be the device in which your microSD card has been inserted. DISCLAIMER: You must be extremely careful here. If you use the wrong device you have the potential to wipe out your host system!! I am not responsible in any way for any lost data as a result of your use of the description. USE AT YOUR OWN RISK!!

Initial Hardware Setup

This description allows you to boot your RPi2 as a workstation using a monitor, keyboard, and mouse.

Needed:

USB keyboard

USB mouse

HDMI/DVI monitor and HDMI/DVI cable

microSD card with operating system loaded

Micro USB power adapter

To assemble your workstation:

Insert the microSD card containing the OS into the microSD slot on the bottom of the RPi2

Connect the monitor to the HDMI port on your RPi2. If your monitor has an HDMI cable, use a straight HDMI cable. This will provide sound through the monitor speakers if they are present. If the monitor your are using has only a DVI input, you can use an HDMI to DVI cable. You will have to provide sound by connecting to the sound port.

Connect the keyboard and mouse to USB ports

Apply power using the MicroUSB power adapter

You should be presented with the first time boot screen, which is actually a program called raspi-config. Your hardware configuration should look like Figure 3.

Figure 3: Configuration of a Raspberry Pi 2 setup as a workstation.

Initial Configuration

The first time you boot your system, you will be presented with a text based menu.

Figure 4: raspi-config top level menu.

This menu is displayed by a program that can be run anytime; its called raspi-config

You should execute the following selections on this menu:

Expand Filesystem: This item will fix the filesystem to take advantage of all the storage available on your microSD card. This item is mandatory!

Advanced Options → SSH: This item under the Advanced Options will enable the use of ssh that is discussed later. While this can be done later, its a good idea to just do it now.

Once you exit raspi-config you should boot into a full Linux desktop on your attached monitor!

GPIO CONNECTOR

The RPi2 and all other Raspberry Pi models contain a large Dual Inline Package (DIP) connector. The RPi2 has a 40-pin version of this connector. The connector has a variety of hardware interfaces that are assigned to various pins. This booklet discusses the Serial Console pins, the GPIO pins, and the I2C and SPI bus interfaces.

Remote Serial Console

Portions of this section were used from Adafruit's excellent tutorial on the RPi serial port.

Another way to access your RPi2 remotely is over a serial connection. It is possible to connect your RPi2 serial port to a USB port on your PC and use a terminal emulator to access your RPi2.

Needed: A special 4-pin to USB serial cable

Figure 7: Adafruit RPi2 to USB serial cable.

You should connect the dangling wires to your RPi2 as shown in Table 1. Figure 8 illustrates how these wires should look when connected (color screen required). The red wire is connected to the 5V input on the 40-pin connector. When this wire is connected, you should not have your Micro USB power supply connected!

Color | Signal | Pin
Red | VCC or 5V | 2
Black | GND | 6
White | TXD | 8
Green | RXD | 10

Table 1: Serial cable wire descriptions.

Figure 8: Serial cable connected to the RPi2 40-pin header.

Depending on where your serial cable was manufactured, the white and green wires may need to be reversed. They are connected to the the transmit and receive pins on the 40-pin connector.

Once you have the dangling wires connected properly to the RPi2, connect the USB side to your computer. You will need a terminal emulator program that runs on your host computer. For Windows, a good option is the terminal emulator program, putty. For Linux, minicom or screen are good options.

Once you determine which device in your system represents the USB serial connection, use that to start your terminal emulator. The connection settings should be 115200 baud, 8-N-1 size, parity, and stop bits, respectively. The terminal emulator should give you a Linux login prompt for your RPi2.

GPIO Connector

Portions of this section were used from Adafruit's excellent tutorial on the RPi GPIO connector.

The GPIO connector actually has a number of different types of connection on them. There are:

True GPIO (General Purpose Input Output) pins that you can use to turn LEDs on and off etc.

I2C interface pins that allow you to connect hardware modules with just two control pins

SPI interface with SPI devices, a similar concept to I2C but a different standard

Serial Rx and Tx pins for communication with serial peripherals

In addition, some of the pins can be used for PWM (Pulse Width Modulation) for power control and another type of pulse generation for controlling servo motors called PPM (Pulse Position Modulation).

Figure 8 shows the pins on the GPIO connector for a Raspberry Pi Version 1 (which is what existed when this tutorial [by Adafruit] was released) Version 2 has pin 27 replacing pin 21 but it otherwise the same.

Figure 9: GPIO connector pinout.

As well as supplying power (GND, 3.3V and 5V) all the GPIO pins can be used as either digital inputs or outputs. The pins labelled SCL and SDA can be used for I2C. The pins labelled MOSI, MISO and SCKL can be used to connect to high speed SPI devices.

All the pins have 3.3V logic levels and are not 5V-safe so the output levels are 0-3.3V and the inputs should not be higher than 3.3V. If you want to connect a 5V output to a Pi input, use a level shifter

A popular way to actually make the connections to the Raspberry Pi is to use a breakout breadboard like the one shown in Figure 10.

Figure 10: Adafruit Pi Cobbler breakout and breadboard.

I2C Bus

Portions of this section were used from the I2C bus specifications described at i2c.info.

The I2C bus uses two wires: serial data (SDA) and serial clock (SCL). All I2C master and slave devices are connected with only those two wires. Each device can be a transmitter, a receiver or both. Some devices are masters – they generate bus clock and initiate communication on the bus, other devices are slaves and respond to the commands on the bus. In order to communicate with specific device, each slave device must have an address which is unique on the bus. I2C master devices (usually microcontrollers) don't need an address since no other (slave) device sends commands to the master.

I2C terminology

Transmitter: This is the device that transmits data to the bus

Receiver: This is the device that receives data from the bus

Master: This is the device that generates clock, starts communication, sends I2C commands and stops communication

Slave: This is the device that listens to the bus and is addressed by the master

Multi-master: I2C can have more than one master and each can send commands

Arbitration: A process to determine which of the masters on the bus can use it when more masters need to use the bus

Synchronization A process to synchronize clocks of two or more devices

Bus Signals

Both signals (SCL and SDA) are bidirectional. They are connected via resistors to a positive power supply voltage. This means that when the bus is free, both lines are high. All devices on the bus must have open-collector or open-drain pins. Activating the line means pulling it down (wired AND). The number of the devices on a single bus is almost unlimited – the only requirement is that the bus capacitance does not exceed 400 pF. Because logical 1 level depends on the supply voltage, there is no standard bus voltage.

Line | Pin #
SDA | 3
SCL | 5

Table 2: RPi2 I2C bus pinout on the 40-pin connector.

Serial Data Transfer

For each clock pulse one bit of data is transferred. The SDA signal can only change when the SCL signal is low – when the clock is high the data should be stable.

Figure 11: i2c bit transfer.

Start and Stop Condition

Each I2C command initiated by master device starts with a START condition and ends with a STOP condition. For both conditions SCL has to be high. A high to low transition of SDA is considered as START and a low to high transition as STOP.

Figure 12: i2c start & stop conditions.

After the Start condition the bus is considered as busy and can be used by another master only after a Stop condition is detected. After the Start condition the master can generate a repeated Start. This is equivalent to a normal Start and is usually followed by the slave I2C address.

Microcontrollers that have dedicated I2C hardware can easily detect bus changes and behave also as I2C slave devices. However, if the I2C communication is implemented in software, the bus signals must be sampled at least two times per clock cycle in order to detect necessary changes.

I2C Data Transfer

Figure 13: i2c data transfer.

Data on the I2C bus is transferred in 8-bit packets (bytes). There is no limitation on the number of bytes, however, each byte must be followed by an Acknowledge bit. This bit signals whether the device is ready to proceed with the next byte. For all data bits including the Acknowledge bit, the master must generate clock pulses. If the slave device does not acknowledges transfer this means that there is no more data or the device is not ready for the transfer yet. The master device must either generate Stop or Repeated Start condition.

Figure 14: i2c acknowledge.

Synchronization

Each master must generate its own clock signal and the data can change only when the clock is low. For successful bus arbitration a synchronized clock is needed. Once a master pulls the clock low it stays low until all masters put the clock into high state. Similarly, the clock is in the high state until the first master pulls it low. This way by observing the SCL signal, master devices can synchronize their clocks.

Arbitration

For normal data transfer on the I2C bus only one master can be active. If for some reason two masters initiate I2C command at the same time, the arbitration procedure determines which master wins and can continue with the command. Arbitration is performed on the SDA signal while the SCL signal is high. Each master checks if the SDA signal on the bus corresponds to the generated SDA signal. If the SDA signal on the bus is low but it should be high, then this master has lost arbitration. Master I2C device that has lost arbitration can generate SCL pulses until the byte ends and must then release the bus and go into slave mode. The arbitration procedure can continue until all the data is transferred. This means that in multi-master system each I2C master must monitor the I2C bus for collisions and act accordingly.

Clock Synchronization and Handshaking

Slave devices that need some time to process received byte or are not ready yet to send the next byte, can pull the clock low to signal to the master that it should wait. Once the clock is released the master can proceed with the next byte.

Communication With 7-bit I2C Addresses

Figure 15: i2c command.

Each slave device on the bus should have a unique 7-bit address. The communication starts with the Start condition, followed by the 7-bit slave address and the data direction bit. If this bit is 0 then the master will write to the slave device. Otherwise, if the data direction bit is 1, the master will read from slave device. After the slave address and the data direction is sent, the master can continue with reading or writing. The communication is ended with the Stop condition which also signals that the I2C bus is free. If the master needs to communicate with other slaves it can generate a repeated start with another slave address without generation Stop condition. All the bytes are transferred with the MSB bit shifted first.

If the master only writes to the slave device then the data transfer direction is not changed.

Figure 16: i2c writing using 7-bit address.

If the master only needs to read from the slave device then it simply sends the I2C address with the R/W bit set to read. After this the master device starts reading the data.

Figure 17: i2c reading using 7-bit address.

Sometimes the master needs to write some data and then read from the slave device. In such cases it must first write to the slave device, change the data transfer direction and then read the device. This means sending the I2C address with the R/W bit set to write and then sending some additional data like register address. After writing is finished the master device generates repeated start condition and sends the I2C address with the R/W bit set to read. After this the data transfer direction is changed and the master device starts reading the data.

Figure 18: i2c writing & reading using 7-bit address.

SPI Bus

Portions of this section were used from the Serial Peripheral Interface (SPI) Bus information on Wikipedia.

Portions of this section were used from the Raspberry Pi SPI documentation.

The Serial Peripheral Interface (SPI) bus is a synchronous serial communication interface specification used for short distance communication, primarily in embedded systems. The interface was developed by Motorola and has become a de facto standard. Typical applications include sensors, Secure Digital cards, and liquid crystal displays.

SPI devices communicate in full duplex mode using a master-slave architecture with a single master. The master device originates the frame for reading and writing. Multiple slave devices are supported through selection with individual slave select (SS) lines.

Sometimes SPI is called a four-wire serial bus, contrasting with three-, two-, and one-wire serial buses. The SPI may be accurately described as a synchronous serial interface,[1] but it is different from the Synchronous Serial Interface (SSI) protocol, which is also a four-wire synchronous serial communication protocol, but employs differential signaling and provides only a single simplex communication channel.

Interface

The SPI bus specifies four logic signals:

SCLK: Serial Clock (output from master).

MOSI: Master Output, Slave Input (output from master).

MISO: Master Input, Slave Output (output from slave).

SS: Slave Select (active low, output from master).

The MOSI/MISO convention requires that, on devices using the alternate names, SDI on the master be connected to SDO on the slave, and vice versa. Chip select polarity is rarely active high, although some notations (such as SS or CS instead of nSS or nCS) suggest otherwise. Slave select is used instead of an addressing concept.

The Broadcom processor upon which the RPi2 is based does not use the SS line. Instead, it uses two slave select lines. Table 2 lists how the BCM processor implementation is exported by the RPi2 40-pin connector:

Line | Pin #
MOSI | 19
MISO | 21
SCLK | 23
GND | 25
CE0 | 24
CE1 | 26

Table 2: RPi2 SPI bus pinout on the 40-pin connector.

Operation

The SPI bus can operate with a single master device and with one or more slave devices. The RPi2 is limited by the number of chip selects to two slave devices.

If a single slave device is used, the SS pin may be fixed to logic low if the slave permits it. Some slaves require a falling edge of the chip select signal to initiate an action, an example is the Maxim MAX1242 ADC, which starts conversion on a high→low transition. With multiple slave devices, an independent SS signal is required from the master for each slave device.

Most slave devices have tri-state outputs so their MISO signal becomes high impedance (logically disconnected) when the device is not selected. Devices without tri-state outputs cannot share SPI bus segments with other devices; only one such slave could talk to the master.

Data transmission

To begin communication, the bus master configures the clock, using a frequency supported by the slave device, typically up to a few MHz. The master then selects the slave device with a logic level 0 on the select line. If a waiting period is required, such as for analog-to-digital conversion, the master must wait for at least that period of time before issuing clock cycles.

During each SPI clock cycle, a full duplex data transmission occurs. The master sends a bit on the MOSI line and the slave reads it, while the slave sends a bit on the MISO line and the master reads it. This sequence is maintained even when only one-directional data transfer is intended.

Transmissions normally involve two shift registers of some given word size, such as eight bits, one in the master and one in the slave; they are connected in a virtual ring topology. Data is usually shifted out with the most-significant bit first, while shifting a new less-significant bit into the same register. At the same time, Data from the counterpart is shifted into the least-significant bit register. After the register bits have been shifted out and in, the master and slave have exchanged register values. If more data needs to be exchanged, the shift registers are reloaded and the process repeats. Transmission may continue for any number of clock cycles. When complete, the master stops toggling the clock signal, and typically deselects the slave.

Transmissions often consist of 8-bit words. However, other word sizes are also common, for example, 16-bit words for touchscreen controllers or audio codecs, such as the TSC2101 by Texas Instruments, or 12-bit words for many digital-to-analog or analog-to-digital converters.

Every slave on the bus that has not been activated using its chip select line must disregard the input clock and MOSI signals, and must not drive MISO. The master must select only one slave at a time.

Standards

The SPI bus is a de facto standard. However, the lack of a formal standard is reflected in a wide variety of protocol options. Different word sizes are common. Every device defines its own protocol, including whether it supports commands at all. Some devices are transmit-only; others are receive-only. Chip selects are sometimes active-high rather than active-low. Some protocols send the least significant bit first.

Some devices even have minor variances from the CPOL/CPHA modes described above. Sending data from slave to master may use the opposite clock edge as master to slave. Devices often require extra clock idle time before the first clock or after the last one, or between a command and its response. Some devices have two clocks, one to read data, and another to transmit it into the device. Many of the read clocks run from the chip select line.

Some devices require an additional flow control signal from slave to master, indicating when data are ready. This leads to a 5-wire protocol instead of the usual 4. Such a ready or enable signal is often active-low, and needs to be enabled at key points such as after commands or between words. Without such a signal, data transfer rates may need to be slowed down significantly, or protocols may need to have dummy bytes inserted, to accommodate the worst case for the slave response time. Examples include initiating an ADC conversion, addressing the right page of flash memory, and processing enough of a command that device firmware can load the first word of the response. (Many SPI masters do not support that signal directly, and instead rely on fixed delays.)

Many SPI chips only support messages that are multiples of 8 bits. Such chips can not interoperate with the JTAG or SGPIO protocols, or any other protocol that requires messages that are not multiples of 8 bits.

There are also hardware-level differences. Some chips combine MOSI and MISO into a single data line (SI/SO); this is sometimes called 'three-wire' signaling (in contrast to normal 'four-wire' SPI). Another variation of SPI removes the chip select line, managing protocol state machine entry/exit using other methods. Anyone needing an external connector for SPI defines their own: UEXT, JTAG connector, Secure Digital card socket, etc. Signal levels depend entirely on the chips involved.

SafeSPI is an industry standard for SPI in automotive applications. Its main focus is the transmission of sensor data between different devices

Networking

Wired Networking

Needed: An Ethernet cable (Cat5 or better), an Ethernet switch to plug into

Connect the Ethernet cable to your RPi2

Connect the other end to an Ethernet switch that leads to the Internet

Start a terminal

Execute the command: ifconfig -a This command lists the network interfaces on your RPi2. You should see an interface called eth0. The IP address listed for eth0 is the address of your RPi2 on your local Ethernet segment.

Execute the command: ping google.com If all goes well, this command should return a sequence of responses indicating the round trip packet transmission and reception time between your RPi2 and Google's servers.

Figure 5: A networked workstation configuration.

Wireless Networking

This description will focus on setting up wireless networking. The first thing to be done is to acquire a USB wifi adapter. Linux and RPi2 support specific chipsets for wifi adapters. You should consult the following page to determine which adapter best suits your needs: http://elinux.org/RPi_USB_Wi-Fi_Adapters

Boot your RPi2

Insert your wifi adapter into a USB port

Run dmesg to see if your adpater is recognized

Run ifconfig -a You should see a wlan0 or equivalent interface appear

Run wpa-gui

Scan for SSIDs

A window will popup with all the available base stations, select your desired base station and add it

Once you see the interface acquire an IP address, start your web browser. You will be redirected to a page that requires you to enter your Identikey. Once you do this, you should be on the network.

Figure 6: A wireless networked workstation configuration.

Remote Login using SSH

It is very often the case that when using the RPi2 as an embedded system, you will not connect a monitor, keyboard, and mouse. You can still access the RPi2 remotely over a network connection using ssh (Secure SHell). The functionality is available both to login from the RPi2 to another machine (Client side) and to login from another machine to the RPi2 (Server side).

Client side:

You can connect to another host from your RPi2 using the ssh client program.

Execute the command: ssh host

Server side:

You need to enable and configure the sshd server daemon on your RPi to allow users to login remotely to your RPi from other machines.

Fortunately, we already did this when we enabled sshd using raspi-config.

If you didn't, start raspi-config. Execute the command: sudo raspi-config

Navigate to the option for ssh under Advanced Options and enable it

Execute ifconfig -a and note the IP address of your RPi2

On another machine, try to remotely login to the RPi2

Finding the IP Address of a Remote Pi

This description uses the tool nmap to search for candidate IP addresses. If you network subnet is densely populated, you may have to try a number of candidate IP addresses to determine which is the Raspberry Pi you are looking for.

nmap produces network traffic which can be considered suspicious in many network environments. Port scans of machines are a traditional first tool used by hackers to attack a system. You may find that using this tool for discovery results in network adminstrators taking notice. Its a good idea to notify your administrators of your use of this tool before starting any scans.

Windows:

https://nmap.org/book/inst-windows.html

http://www.cyberciti.biz/networking/nmap-command-examples-tutorials/

Linux:

Find your Raspberry Pi

To use it, from the command line, tell it to scan your network for machines with port 22 open (the SSH port):

$ nmap -p 22 --open -sV 192.168.0.* -Pn

The above says scan my network, specifically all IPs on 192.168.0.any that have port 22 open. The last argument isn't required but I had to do it.

You are looking for a response that includes OpenSSH 6.0p1 Debian... that's Raspbian Wheezy so it's likely our Pi. Near that line, a few lines above it, it should say the actual IP it was scanning when it got that. Here's what mine said:

$ nmap -p 22 --open -sV 192.168.0.* -Pn

Starting Nmap 6.47 ( http://nmap.org ) at 2015-02-28 09:47 EST
Nmap scan report for 192.168.0.104
Host is up (0.0056s latency).
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 6.0p1 Debian 4+deb7u2 (protocol 2.0)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 255 IP addresses (3 hosts up) scanned in 3.39 seconds

Now you know your IP... mine is 192.168.0.104.

Read more at http://www.andrewconnell.com/blog/setup-node-js-on-raspberry-pi-2-b#BBaQTLCTz3eMdwFp.99

Avahi/Zeroconf/Bonjour

From: http://elinux.org/RPi_Advanced_Setup

Zeroconf is 'a set of techniques that automatically creates a usable Internet Protocol (IP) network without manual operator intervention or special configuration servers.'[3]. Avahi is an implementation of zeroconf which 'ships with most Linux and *BSD distributions'[4], but not the Pi's Debian distro. Zeroconf will be familiar to Apple users as Bonjour, and is pretty clever tech which means that things Just Work when sharing stuff across computers on a network. In this context, it means that once we've set it up on the Pi, we'll be able to address it as:

raspberrypi.local

regardless of what IP address it's been assigned on your local network. This is handy if its IP is likely to change regularly, and even means we'll continue to be able to address it if we're on a different network (say, shuffling between home & work networks).

Information in this section largely gathered from 4dc5.

Install avahi with the following commands on the Pi:

sudo apt-get install avahi-daemon

and then on older Debian installs:

sudo update-rc.d avahi-daemon defaults

or on newer Raspbian installs:

sudo insserv avahi-daemon

(if in doubt, you're probably on the newer one).

Create a configfile for Avahi at /etc/avahi/services/multiple.service. I did this with the following command:

sudo pico /etc/avahi/services/multiple.service

The contents of this file should be something like the following, courtesy of aXon on the Rasperry Pi forums:

<?xml version="1.0" standalone='no'?>
  <!DOCTYPE service-group SYSTEM "avahi-service.dtd">
    <service-group>
            <name replace-wildcards="yes">%h</name>
            <service>
                    <type>_device-info._tcp</type>
                    <port>0</port>
                    <txt-record>model=RackMac</txt-record>
            </service>
            <service>
                    <type>_ssh._tcp</type>
                    <port>22</port>
            </service>
    </service-group>

Apply the new configuration with:

sudo /etc/init.d/avahi-daemon restart

The Pi should now be addressable from other machines as raspberrypi.local, for example:

ssh pi@raspberrypi.local

Get Windows to play nice with avahi

If you've done the first steps correctly and you open up Putty and you try to address your pi as raspberrypi.local, it will tell you "Unable to open connection to raspberrypi.local" This happens for a very good reason: your Windows PC can't interpret the udp-datagrams avahi sends and most firewalls don't even allow them to get read. So you'll have to do a couple of things extra to get it working.

Get Bonjour for Windows

http://support.apple.com/kb/DL999

Just install it, quick next next next next procedure will suffice. Now your computer is able to interpret the UDP datagrams which are multicasted by the pi. But we're not out of the woods just yet, if you try to ping to your raspberry pi:

    C:\Windows\System32>ping raspberrypi.local
    Ping-request cannot find host raspberrypi.local.
    Check the name and try again.

Tell your firewall: trust me, I'm an engineer.

Stereotypically, the firewall forbids us to have some fun. First of all, the 5353 UDP port is blocked on most firewalls, so you have to add an exception for it. Also, you'll have to grant internet access to the mDNSresponder.exe, this way, whenever your computer tries to connect with a host *.local, mDNS sends a multicast over the local subnet to ask whether anyone calls himself *.local. If mDNS isn't granted network access, nothing gets multicasted and nobody answers the phone.

Note: If you have the McAfee firewall, you'll also have to enable UDP control. If it isn't enabled, all UDP datagrams are ignored.

Enjoy the pleasure of typing raspberrypi.local in Putty

After these steps, you should be able to ping to raspberrypi.local and even address it that way in putty. YMMV, if you're still having troubles at this point, try to ping to raspberrypi.local with the firewall turned off. If it works: hey presto, you've got your culprit and you can start an educated Google search.

SCP

SCP (or Secure CoPy) is a utility that allows quick transfer of files between machines. The scp utility is installed and enabled along with ssh. You must enable remote machines to allow them to have SCP access.

Server:

SCP is enabled when you allow for remote SSH connections.

Client:

Windows WinSCP client: https://en.wikipedia.org/wiki/WinSCP

Linux: the client program scp should be installed with your distro.

Using SCP

From: http://www.hypexr.org/linux_scp_help.php

This description provides a set of example command lines to address several common problems:

Copy the file "foobar.txt" from a remote host to the local host

$ scp your_username@remotehost.edu:foobar.txt /some/local/directory

Copy the file "foobar.txt" from the local host to a remote host

$ scp foobar.txt your_username@remotehost.edu:/some/remote/directory

Copy the directory "foo" from the local host to a remote host's directory "bar"

$ scp -r foo your_username@remotehost.edu:/some/remote/directory/bar

Copy the file "foobar.txt" from remote host "rh1.edu" to remote host "rh2.edu"

$ scp your_username@rh1.edu:/some/remote/directory/foobar.txt your_username@rh2.edu:/some/remote/directory/

Copying the files "foo.txt" and "bar.txt" from the local host to your home directory on the remote host

$ scp foo.txt bar.txt your_username@remotehost.edu:~

Copy the file "foobar.txt" from the local host to a remote host using port 2264

$ scp -P 2264 foobar.txt your_username@remotehost.edu:/some/remote/directory

Copy multiple files from the remote host to your current directory on the local host

$ scp your_username@remotehost.edu:/some/remote/directory/\{a,b,c\} .

$ scp your_username@remotehost.edu:~/\{foo.txt,bar.txt\} .

SCP Performance

By default scp uses the Triple-DES cipher to encrypt the data being sent. Using the Blowfish cipher has been shown to increase speed. This can be done by using option -c blowfish in the command line.

$ scp -c blowfish some_file your_username@remotehost.edu:~

It is often suggested that the -C option for compression should also be used to increase speed. The effect of compression, however, will only significantly increase speed if your connection is very slow. Otherwise it may just be adding extra burden to the CPU. An example of using blowfish and compression:

$ scp -c blowfish -C local_file your_username@remotehost.edu:~

FTP Server

From: http://www.ducky-pond.com/posts/2013/Aug/install-an-ftp-server-on-rpi/

We will make use of a popular FTP server package called vsftpd. To install the vsftpd package:

$ sudo apt-get install vsftpd

By default vsftpd is configured for anonymous access with read-only permissions. We're going to change things so that it requires you to authenticate with a local user. Let's open the configuration file.

$ sudo nano /etc/vsftpd.conf

We want to change or uncomment the following values.

anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
chroot_local_user=YES
user_sub_token=$USER
local_root=/home/$USER/ftp

After that restart the vsftpd service. Now we need to create a couple folders in your local user's home folder. The ftp folder will be the root when you connect. The way vsftpd works, the root is not allowed to have write permissions on it, so we'll create a sub-folder inside the root called files which our local user will be allowed to write to. This is where you'd upload/download files from with an FTP client.

$ mkdir /home/<user>/ftp
$ mkdir /home/<user>/ftp/files
$ chmod a-w /home/<user>/ftp

Now you should be able to connect to your from any FTP client and start uploading/downloading files.

LAMP Server

From: http://www.geothread.net/building-a-lamp-server-on-the-raspberry-pi-computer

Apache Web Server and PHP

To install the Apache web server and PHP (find out more here http://www.apache.org and here http://php.net), type:

$ sudo apt-get install apache2 php5 libapache2-mod-php5

To ‘restart’, ‘stop’ or ‘start’ apache, use the following command (varying the last word)

$ sudo service apache2 restart

Note the Apache webroot location for your webfiles is /var/www

The Apache log files are put in /var/log/apache2

MySQL Database Server

$ sudo apt-get install mysql-server mysql-client php5-mysql

You need to enter in a database system password, such as ‘raspberry’! Once installed restart and you can hopefully access the MySQL command line prompt thus:

$ sudo service mysql restart
$ mysql  -u pi –p

Check the interactive logon works as user pi. Try and ‘use’ a database and select records:

mysql> use mysql
mysql> select * from users;

Use ctrl+c to quit

For logging, see http://serverfault.com/questions/71071/how-to-enable-mysql-logging

PHP

PHP should have been installed also. In the /var/www webroot, create a new file called testphp.php with the ‘nano’ editor, and enter the following. Once created, run the file in the your laptop/pc browser to see the Pi PHP status:

$ sudo nano /var/www/testphp.php

Enter the text oneliner below into the file.

<?php phpinfo(); ?>

Your laptop/pc web browser ‘should be able to see this web page served up. Enter the IP address we set earlier, plus this file, thus:

In web browser, enter the URL http://192.168.1.100/testphp.php

Hopefully you should see the PHP status page appear.

Mysqli

In PHP you should use the recommended MySQLi command extension to access the MySQL database. It ‘should’ be installed already – but look down the phpinfo() web page above to find it and ensure it is shown as ‘enabled’.

To learn more, see http://codular.com/php-mysqli (but do check the phpinfo() output above first)

Phpmyadmin

To manage the MySQL database, we recommend the excellent ‘phpmyadmin’ MySQL web management console. All the MySQL administration can then be undertaken through a web page.

See http://www.dingleberrypi.com/2012/09/tutorial-install-phpmyadmin-on-your-raspberry-pi/

$ apt-get install phpmyadmin

Select ‘apache2’ as the web server.

Create a phpmyadmin password, such as ‘raspberry’ (or whatever – but don’t forget it!)

You should now be able to call up the phpmyadmion home page at:

http://192.168.1.100/phpmyadmin – login as root/raspberry

Note user privileges to the MySQL database are all managed via phpmyadmin. Each user account needs to have specified the host from which the user will come to access the database. The ‘%’ (all servers) option didn’t work for us and so we needed to repeat a configuration for servers: ‘127.0.0.1’, ‘192.168.1.100’, ‘localhost’ and ‘raspberry pi’. A bit fiddly – essentially you open up the privileges for the user and duplicate the settings varying the host each time. To help with this, note that once phpmyadmin is installed, one can see the various options the phpmyadmin user has pre-assigned. Note that connecting to MySQL from the SSH terminal uses ‘localhost’, whereas connecting from a webserver can use ‘127.0.0.1’ – so the source varies according to source. One needs to experiment – hmm!

Remember later that if you ever receive a ‘500’ error on the webserver when trying to access the database, it is likely due to the incorrect privileges. You may need to look at the webserver apache logfiles in a new window (/var/log/apache2) to actually see the error:

$ sudo more /var/log/apache

or better still, to see only new lines as they appear in the logfile:

$ sudo tail –f /var/log/apache2

LAMP Server Access to GPIOs

By combining the GPIO connector to monitor and control external elements and providing access to those function using a standard web interface, the RPi2 provide for remote access from any where in the world. In this section we discuss a simple way to hook the GPIO functions to a standard web server.

Portions of this description were excerpted from http://wiringpi.com/

WiringPi is a GPIO access library written in C for the BCM2835 used in the Raspberry Pi. It’s released under the GNU LGPLv3 license and is usable from C and C++ and many other languages with suitable wrappers (See below) It’s designed to be familiar to people who have used the Arduino “wiring” system

WiringPi includes a command-line utility gpio which can be used to program and setup the GPIO pins. You can use this to read and write the pins and even use it to control them from shell scripts.

WiringPi is extendable and modules are provided to extend wiringPi to use analog interface devices on the Gertboard, and to use the popular MCP23x17/MCP23x08 (I2C 7 SPI) GPIO expansion chips, as well as module that will allow blocks of up to 4 74×595 shift registers to be daisy-chained together for an additional 32-bits worth of output as a single unit. (You can have several blocks of 4 74x595s if needed) One of the extension modules allows you to use an ATmega (e.g. Arduino, or the Gertboard) as more GPIO expansion too – via the Pi’s serial port.

Additionally, you can easily write your own expansion modules to integrate your own peripheral devices with wiringPi as required.

WiringPi supports analog reading and writing, and while there is no native analog hardware on a Pi by default, modules are provided to support the Gertboards analog chips and other A/D and D/A devices can be implemented relatively easily.

The wiringPi devLib is a set of library routines implemented using wiringPi to give you easy access to some popular peripherals. Devices supported include character LCD displays (based on the Hitachi HD44780U chips), and graphical ones – e.g. the common 128×64 pixel displays with the generic 12864H driver chip. The DS1302 RTC clock chip, sensors based on the Maxdetect chips (e.g. RHT003) the Gertboard and PiFace interface boards and so on.