Saturday, 16 January 2016

UART for Pi Zero

Pi Zero In and Out

The Zero misses out on the usual network port and has to cope with one USB for all accessories including wireless dongles. The good news is it has all the usual 40 pins found on later + models of the Pi and the Pi 2 including the good old UART (Universal Asynchronous Receiver Transmitter) transmit and receive pins. 

On-the-Go USB allows the Pi Zero to act as a host or a gadget so it can do funky stuff like bridge networks and become a serial device. Unfortunately this requires changes in the OS and isn't out of the box with the latest Raspbian (when writing this). Hopefully it will become standard in future distribution updates.

USB to UART

My goal here is a mini project to build a USB to UART converter using the Tx/Rx pins exposed in the 40 pin breakout. I think this is a great way to plug into a Zero which is running as part of another project. Access is available by default in Raspbian with a console running off the transmit and receive pins so there's little else to setup and configure. 
The other great thing is the 5v from the USB can still be used to power a Raspberry Pi. 
The project here is based on another blog entry. Credit goes to the post on Element 14s community blog from Shabaz. I've tweaked this a little for a Raspberry Pi.

Components

Pre-built cables to do USB to UART exist for a reasonable price and a build like this isn't essential to connect up to a Pi. My main driver and plan is to have this built into a project housing and customize connectivity to other breakouts. 

The heart of this build is the MCP2221 IC from Microchip. A 3.3 voltage regulator is needed to step down the 5v from the USB as this will fry your Pi. Different sizes of USB type B connectors are available and this build uses the standard large size. A few capacitors and a resistor are finally required to complete the components.

The MCP2221 is an interesting chip. Not only will it convert to UART but it can also be an I2C master, provide ADC/DAC conversion or present 4 GPIO input/outputs. 

Prototyping


Confirming all the components work as expected and that the wiring will work requires a push pin breadboard. The USB B connector will not sit on this type of board so extending wires from the output pins is required to connect.

I was careful that the wires are not touching. I'm not sure what the damage will be to the 2221 or a connected PC if this were to happen.

Hooking up LEDs is possible from the GP0 and GP1 connectors to see receive and transmit activity. At high transfer rates this just dims the LEDs as communication is far too fast to see an on/off effect. I left these off the build in the end. 

Build

I'm no design expert so don't shoot me for the bad diagram. This is my top down version of the build on the strip board. The USB type B connector is mounted into the blue circles and also acts as a connection to the shielding. 10 nf and 10M Ohm resistor connected to the shield prevent EMI radiation. USB standards provide more information on this.

Most of the holes were cut out to isolate the MCP2221 and required connections were jumped across the gap. It's important to cut the copper between the USB pins 4 & 1 and 3 & 2. I soldered out across the = signs to create a couple of ground lines and to route D+ to a strip on the copper board. 

Finally, connector pins are soldered in along GND, Rx, Tx and 5v lines at the bottom of the board. 

Final build looks fairly tight on the strip board. It's a bit of a solder mess underneath. 

Improvements

Creating an etched board would be the ultimate goal to remove the wires. The 3.3v regulator I used is over-specified for the current drawn. 500mA is the max drawn over the USB so a smaller 3.3v could be added. 
Following this photo of the build I did add some female headers to allow jumping with male pins to a Pi board. 
The 5v from USB has been kept as an output pin which allows the board to power a Pi. Reading up on how the Pi manages power, the 5v pin on the header pins bypasses the 700mA ployfuse. This is bad news if something goes wrong over the USB power. For peace-of-mind a polyfuse between 500mA to 700mA can be used to ensure the same protection is available. 
A reset switch for the chip could be nice feature if switching between HID modes and UART. 

Hooking up

Windows

Starting up with a connection to a Windows PC is good to check everything works as expected because Microchip provide some easy to use software for configuration.
The drivers and utility software can all be downloaded from the Microchip website. Install the driver and the utility. DLLs are not necessary and seem to be library interfaces for building your own code. 

Connection between the Pi and the USB UART crosses the receive and transmit lines, which means UTx connects to RXD and URx connects to TXD.

Windows will attempt to locate the driver and install. I'm not entirely sure if these were fetched from Windows update or used the installed driver on my Windows 7 machine. Either way it worked and was successful. 

Initial connection throws an Error Encountered message and configuration is only read after pressing the Read Device Settings button.
Settings are written back using the Configure Device button

From the utility window the entire chip can be configured. Serial numbers are not enabled by default so if the device is plugged into another USB a new COM port will be allocated.  

The 2221 should be reset after using this utility as the UART and HID modes interrupt each other. 
COM3 was allocated first for the device so connecting up was simple using PuTTY. 
The 2221 chip sets the transfer speed on first connection. Once set and connected for the first time, altering the serial speed again will create garbage on the screen. Rest the Pi to alter the speed.

Power up the Pi and give time to boot up. 

Connect over serial, set the speed and type in the name of the COM device allocated to the USB. Press Open should connect up. Text may appear. Entering the username to login with will tend to get it all going

Linux

Linux requires the CDC driver. Wire up the Pi to the USB/UART board and plug into the Linux machine. Checking dmesg and run
> lsmod | grep cdc 
should confirm there's a valid driver and a connection.

With Minicom installed the connection is as easy as
> sudo minicom -b 115200 -o -D /dev/ttyACM0

Power up the Pi and Minicom will show the entire boot sequence. Powering the Pi first seems to set the serial speed.

Using a Pi over serial

Connections over serial remain open all the time regardless of having PuTTY or Minicom open. I found I could kill the terminal process over the serial link with a CTRL-D and the only recourse was to pull the power. Using logout returns the serial console to the login prompt. 

Powering down a Pi over serial gives a clean shutdown instead of pulling the plug
> sudo shutdown -h now

A Zero will turn off its LED when shutdown.

Powering the Pi over USB

Essentially this already happens with a micro USB cable connection to a Pi. For the USB/UART device it's a 2 in 1 deal allowing connection and power. 

The Windows utility from Microchip allows some tweaking of the power options for USB.
A quick search on the Internet reveals the different current draws for each Pi
  • A+ and B+ up to 240mA running idle
  • 2 B up to 420mA running idle
  • Zero up to 70mA idle and reported to be around 140mA booting up
The bullets above will need adjusting depending on what the Pis are running off USB or header pins.

A Pi 2 will need all the USB power to run so the configuration will need changing to 500mA. I tested booting up a Zero and it worked fine with the 100mA default.
 



Differences over reference build

This was based on the blog posting from Element 14s community site. Definitely go and visit that post if you plan to do a similar build.  

I changed this build and removed the jumper pins knowing that I would only be using these with my Raspberry Pi(s). Without the 5v power to the 2221, the internal LDO isn't used. This also meant one less capacitor on the 2221 VUSB output.
I have read in Simon Monks Raspberry Pi Cookbook that the Arduino can work with 3.3v on the transmit and receive lines. This could mean my 3.3v build works on Arduino, but check out the facts before attempting it as it may not be reliable or good for the Arduino over long term use. 

Saturday, 9 January 2016

Size Zero Pi




Bare Raspberry Pi Zero

Going Zero

I'm a happy Raspberry Pi 2 owner, but the size of the Pi 2 always means it trails patch, jumper or ribbon leads to external electronics.

The Zero is small enough to be embedded away and can be the beating heart of an electronics project. The price also means that it's not too bad if it becomes a permanent feature with solder, glue and screws. 

What's in the Package?

I still have to put it though its paces to see what it can do but the specs are more than good enough to do the job of the original Pi A. The Zero comes with a Broadcom BCM2835 running a single core up to 1GHz and 512MB of memory. There's no network port and in reality there's just the one USB port for connecting devices as the other is for powering the Zero. 

The USB is an On-The-Go (OTG) port which means it can be a gadget or host connected gadgets. I'll be playing around with this feature in the future. 

HDMI is still on board and this allows the Zero to work like the rest of the Pi range, allowing it to hook straight up to a display in no time and get results. 

Zero Connection

You will need some adapters for the zero unless you have micro USB input devices and mini HDMI display devices. Adapters can be found online. I sourced mine from The Pi Hut which also came with the header pins.

SD Card Setup

First things first is the SD card with the latest Jessie image. I went with the lite image since an X-Windows server isn't needed for the projects I have in mind. You can also go for NOOBs if you want to try out other images and have a recovery tool. 

The following steps are for Windows which I used in my setup.

Whilst you are downloading the image you can also get hold of SDFormatter V4.0 to prepare the SD card. I have had a few problems in the past getting images to work but these steps seem to work every time for me.

1. Enable Full Format and Size Adjustment to On
2. Ensure that the drive letter correctly matches your SD card!
3. Double check the drive letter!
4. Press format and wait for it to complete

Quick format may also do the job but if you can't get it working with that option try the Full Overwrite. 

Extract the IMG file from the ZIP. In theory the zip can be used, but again this is the formula that seems to work.

Fedora ARM image installer works to get the image correctly written to the card. Download and install. Run the application (it may need administration permissions to run).  
1. Select image from your hard drive (select the IMG file)
2. Check the destination drive and double check it really is your SD card
3. Press Install

Eject the SD card from the task bar. This ensures the image data is fully written and not corrupted when you pull out the SD card. 

So now your Zero has an operating system to get it running.

Hooking Up To Keyboard and Monitor

Plug in the newly created SD card into the SD card slot. A USB keyboard or USB wireless dongle can be used. I'm using a wireless Logitech to avoid long leads. 

Use the adapter for the HDMI to connect up to your monitor. You may want to support the mini HDMI socket as the adapter can need a bit of wiggling to slot in.

Add power from a micro USB wall adapter. Depending on the type of USB devices you want to plug into the Zero you will need a wall power adapter which can provide the correct power. I'm reusing the 2A power supply used by the Pi 2 in my setup and this is more than enough.

Power Up

Turn on the power and the Zero should indicate with a flashing light that it's working. 

All being well the Zero should output to the monitor with output from Jessie.

This is the most basic setup you can have for the Zero. From here you can login:
User: pi
Pass: raspberry

From the login prompt run
> sudo raspi-config

This should open up a menu. Select the first option to Expand the file system. This will then prompt you to restart to complete. 









The next section discusses how to drop the need for keyboard and monitor and use remote connections to manage the Pi Zero.

Zero HDMI & Keyboard

With a monitor and keyboard attached all the extra wires seem to miss the point of having the Zero Pi in the first place.

The following steps take away the HDMI connection and replace with a remote SSH over wireless. 

To do this a hub is required because only one USB device can be attached and you will need a keyboard and wireless USB device. Once complete the hub isn't required so it's only temporary for the setup.


Enable SSH

Start up the Zero again and login. Run raspi-config as before.

From the initial menu go to 9. Advanced Options. This will take you to another menu
Select the option to enable SSH. Restart to enable.

To shutdown from the command prompt you can type:
> sudo shutdown -h now

Plug the Pi Zero back in to restart. 

Configure Wireless

This is a little trickier using the command line and should be done after restarting following enabling SSH. 

From the command line run:
> sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

This will open the editor. Scroll to the bottom of the file and add the following

network={
    ssid="Your wireless SSID"
    psk="Your_wifi_password"
}

Replace the text in quotes with your network SSID and your password. 

Save the file (Ctrl-X and press y to save when prompted). In theory the wireless should connect but I found it required some additional work. 

Take down the interface from the command prompt:
> sudo ifdown wlan0

Then bring it back up with:
> sudo ifup wlan0

Wait a while for the DHCP to configure an address and run
> ifconfig

You should see wlan0 configured with a valid IP address. It may be slow so keep trying until you see an address. Check your wireless router if it's not providing an address. Alternatively run 
> dmesg

and see if there's any errors enabling your wireless USB device. 

One final step to prevent the need to guess or require the HDMI to check IP every time is to 
1. Assign a permanent IP to the MAC address for the wireless dongle
2. Disable DHCP and set a fixed IP for the wireless LAN connection

Item 1. depends on your wireless router config. Consult documentation for how to do this.
Item 2. requires some more configuration which is well documented from the Pi Hut website

Going Headless


Linux and Mac

Once the wireless is working test out the SSH connection. SSH packages can be installed to the command prompt for Linux fairly easily and are likely to be enabled in most distributions. Macs also come with SSH that can be run from the terminal. Execute something like
> SSH pi@192.168.0.101

Replace the IP with the address given to your Zero.

Windows

Windows OS users can use PuTTY to access the Pi Zero. 

PuTTY doesn't even need a formal install to run. Just run the binary and the interface will work. 

You will need to know the IP address to login. Username and password will be prompted after selecting Open and a successful connection has been made. 

Removing the hub

Once the connection has been verified issue a shutdown with
> sudo shutdown -h now

Wait for the LED on the Zero to turn off and it's shutdown.
Unplug the HDMI and USB hub. Plug the wireless dongle back in and power the Pi Zero back up.

Try the SSH connection again after the Zero has had time to complete the boot sequence.