Extending GPIO with an Arduino connected to the PINE64 using I2C

Although the PINE64 provides quite a decent number of GPIO pins, there are several reasons that you may want to have access to more pins. For example, the Arduino can provide an extra number of native PWM pins, or you may want to implement low-level control of a robot using the Arduino, with high-level operations being handled by the PINE. This post will cover how this can be achieved with the PINE64 and an Arduino Mega. We’ll also create a sketch for the Mega which for handling I2C communication. In the next post, we will write some C and C# code which will show how to send and receive data between the PINE and the Mega. Note that this can be done with any single board computer that supports I2C including any of the Raspberry Pis, the Beagleboard and others.

PINE64 connected to Arduino Mega over I2C

I2C stands for Inter-Integrated Circuit and it is a serial computer bus that enables communication between multiple devices that support the protocol. Every board that supports I2C will have 2 pins called SDA (serial data line) and SCL (serial clock line).

Pins 3 and 5 of the Pi 2 pinout on the PINE64 are the SDA and SCL pins respectively. On the Mega, they are pins 20 and 21. Connect the SDA and SCL pins from the PINE64 to the SDA and SCL pins respectively on the Arduino. I have also connected the 5V from the PINE to the Mega in order for the Mega to be powered by the PINE. If you decide to take this approach, one of the ground pins also has to be connected between both boards.

A closer look at the I2C connection between the PINE64 and the Arduino Mega

Before connecting the Mega, we’ll need to create and upload a sketch that will assign an I2C address which will be used to access the device. The sketch will make use of the Wire library which will be used for I2C communication. We will be making use of byte arrays to send and receive data over the I2C bus. You can come up with a fancy protocol for this, but I came up with the following simple rules.

  • Maximum length of 16 bytes.
  • First byte will always be the length (inclusive of the first byte) of the data sent or received.
  • Second byte is the command. We’ll support 3 simple commands, digital write (0x01 or 1), digital read (0x02 or 2) and analog write (0x03 or 3).
  • Third byte is the pin number.
  • For digital write only, fourth byte be a value of either 1 (for high) or 0 (for low).
  • For analog write only, the next four bytes after the third byte will store an integer value between 0 and 255 inclusive.

With that out of the way, let’s take a look at the sketch. First things first, define our constants and variables.

The code is straightforward. We define 0x08 as the I2C address that we want the Mega to use. We also define our commands, pin states (for digital read / write), buffers for storing data to be sent and received and other variables that will be used. The ioPins array is a list of all the pins available on the Mega. This will need to be changed to match the board that the sketch will be uploaded to. The ioPinStates is a pseudo hashmap which will map the pin number (used as the array index) to one of the defined pin states (IO_PIN_STATE_INPUT or IO_PIN_STATE_OUTPUT). We’re keeping track of the pin states so that we can activate the pins on demand, instead of activating them all at once in the setup() function.

The setup function simply initialises the Wire library using the specified I2C address, and enables Serial output which will be used to output debug messages. Wire.onReceive registers the onDataReceived function which will be called when data is sent from the PINE64, while Wire.onRequest registers the onDataRequested function which will be called when the PINE64 requests data from the Mega. The isPinValid function is a helper method which checks if the pin specified as the parameter is valid for the board. It checks the pin against the ioPins array that we defined earlier.

Next is the onDataReceived function which handles most of the work. It accepts an argument which represents the number of bytes that were received.

The while loop checks if there is data available from the Wire library. If there is, the absolute minimum number of bytes received that can be considered valid based on the rules we defined earlier is 3 (length, command, pin). If the number of bytes received is less than 3, then the function ends at that point and output is written to the Serial console. The next step is to use a switch statement to check and handle the command that was received. The second byte (index 1) contains this data.

For digital write, the minimum number of bytes to be considered valid is 4 (length, command, pin, value). The function is terminated if we received less than 4 bytes for the command. The isPinValid is called to check if the pin received is valid, and if it isn’t, the function ends at that point. Next thing to be done is to check if the pin has been activated. We make use of the ioPinStates array to do this making use of the pin number as the index. If the pin has not yet been activated (IO_PIN_STATE_OUTPUT), then we activate the pin using pinMode. Once this check is complete, we can call digitalWrite using the pin and the value specified.

Digital read also follows the same set of steps as digital write (validate date length, validate pin, check pin state) but we will call the actual digitalRead function in onDataRequested. What we do here is store the command and the pin in variables (lastReadCommand and lastReadPin respectively) which we can then make use of in onDataRequested.

Similar to digital write, analog write follows a couple of steps (validate data length and validate pin). We don’t need to check or set the pin state before calling the analogWrite function. We check that the value is between 0 and 255 inclusive before calling analogWrite with the pin and the value as the arguments.

If the data sent did not match any of the defined commands, the code falls back to the default statement which outputs Unrecognised command. to the serial command, and then the onDataReceived function will be called again when new data is received.

Finally, we have the onDataRequested function which makes use of lastReadCommand and lastReadPin. The function is straightforward, as it uses the Wire library to send data back to the PINE following our simple rules.

And that’s it! Compile the sketch using the Arduino IDE and then upload it to your board. Connect your Arduino to the PINE after the sketch is successfully uploaded, and boot up the PINE. You can obtain the full code listing for the sketch at https://gitlab.com/akinwale/nanitei2c/blob/master/nanitei2c_mega.ino.

Install i2c-tools using sudo apt-get install i2c-tools. By default, only root can use the I2C commands, but you can add the user account with useradd -G i2c ubuntu (replace ubuntu with the username that you want to use to access I2C). Reboot the PINE and then scan the I2C bus with the command, i2cdetect -y 1. You should get output should be similar to the following:

Based on this output, we can see that the Mega was recognised over the I2C bus with the configured address in our sketch (0x08 or 8). With this, we have access to the extra pins which we will be able to control directly from the PINE. That’s pretty neat. In the next post, we will write the C and C# code for the PINE for handling I2C communication.

Getting started with the Raspberry Pi 3

It’s taken quite a while for my PINE64 to arrive. Apparently, the shipping was delayed because the addon camera module was not ready yet. Quite disappointing, but I guess it’s to be expected since it’s a Kickstarter project. In the mean time, I decided to grab a Raspberry Pi 3 so that I could start off with my autonomous robot project.

I started off with the Raspbian Jessie Lite image which is a 292MB download (May 2016 version). Got it set up on a Sandisk 32GB microSD card and booted it up. I was planning to connect to it using a USB to TTL serial cable as I don’t have any USB peripherals available, nor an Ethernet cable. The plan was to configure the wireless connection so that I could SSH into it (and use X forwarding for GUI applications) once it booted. This did not go smoothly, and it took quite some time to figure out since a lot of the information online only applies to the earlier Pi models.

It turns out the default Raspbian image for the Pi 3 does not support serial connections out of the box due to the in-built Bluetooth module, so I had to make some adjustments to get this to work. Hence, this is sort of a beginner’s mini guide to working with a headless Raspberry Pi 3. The following instructions will require a Linux box.

So how do you get Pi 3 serial to work?
Note that these instructions are based on the May 2016 Raspbian Jessie Lite image. I mounted the SD card on my laptop’s Ubuntu installation, and had to chroot into it (following instructions at https://hblok.net/blog/posts/2014/02/06/chroot-to-arm/) to run a few updates. Inserting the SD card will create 2 mount points: the /mnt/boot/ partition and the main partition which we’ll refer to as /mnt/main/ (note that the path to the mount points may be different depending on your Linux distribution, so verify). After mounting, run the following commands.

Before you can chroot, you need to be able to run ARM binaries using qemu.

Next, register the ARM executable format with the QEMU static binary.

Now, you can chroot into /mnt/main

If you get an error stating that ‘/bin/bash’ was not found, you may have to run

Once you’ve chrooted in, update the system.

If you get an error along the lines of qemu: uncaught target signal 4 (Illegal instruction) - core dumped, edit /etc/ld.so.preload and comment out the lines in the file.

Next, you’ll need to install and run rpi-update.

Once the update is completed, edit the /boot/config.txt file. Add these lines to the end of the file and save.

Unmount the microSD card and insert it into your Pi. Connect the appropriate pins for your Pi using your USB-to-TTL serial cable and plug it into your host. Instructions for this can be found at http://workshop.raspberrypiaustralia.com/usb/ttl/connecting/2014/08/31/01-connecting-to-raspberry-pi-via-usb/. Note that if you’re going to use an external power source, you do not need to connect the 5V pin from the serial cable. Connecting to the 5V pin while an external power source is connected may damage your Pi, so be careful!

You should then be able to access your Pi using screen (or your preferred serial client). Note that /dev/ttyUSB0 is the port attached after the cable was connected. To find out what port your USB cable is attached to, you can run dmesg | tail after you connect the cable.

If you see a blank screen, your Pi has probably already finished booting up, so just type your login username and press Enter. Alternatively, you can reboot your Pi (without disconnecting the USB cable from your host) and then you should be able to see the boot messages in the serial console before the login prompt is displayed.

Configure Pi 3 WiFi from the command line
After you’re logged in, you’ll need to configure your WLAN connection. Just edit /etc/wpa_supplicant/wpa_supplicant.conf and add the following lines replacing [networkssid] and [key] with the WiFi SSID and the access key respectively:

Save the file and then run the following commands

Next, check if the connection was successfully established. If you see inet addr after running the ifconfig command, then you’re connected to the network and you can SSH in (after raspi-config) from a different device on the network.

Enable I2C and SSH with raspi-config
With raspi-config, you can make a number of configuration changes to your Pi 3. Enabling SSH is required for remote access and I plan to use I2C to connect to an Arduino Mega in order to control the pins, so I2C has to be enabled as well. To enable both, launch raspi-config.

Then select Advanced Options, and then enable the SSH and I2C options. You can also explore the other configuration settings and modify them to suit your needs.

What now?
That’s it! I will be writing about the software I’m installing on the Pi 3 relating to my autonomous robot project over the next few posts. I will also create posts related to the PINE64 once I have the board in my hands. Hopefully, very soon!