Controlling an Arduino connected to the PINE64 over I2C with C and C#

In a previous post, we connected an Arduino Mega to the PINE64 and wrote a sketch for the Mega for data communication. The data to be sent and received will follow the simple rules which were listed in the post. Next, we’re going to write a shared library with some C code to interface with I2C natively, and then a C# class which will call the shared library and bring everything together. Just a quick recap of the data rules:

  • Maximum length: 16 bytes.
  • First byte: Number of bytes sent/received.
  • Second byte: Control command. CMD_DIGITAL_WRITE (0x01 or 1), CMD_DIGITAL_READ (0x02 or 2) and CMD_ANALOG_WRITE (0x03 or 3).
  • Third byte: Pin number.
  • Fourth byte: Value of either 1 (for high) or 0 (for low) for CMD_DIGITAL_WRITE, or
  • Fourth to seventh bytes: Integer value for CMD_ANALOG_WRITE.

Linux has native I2C support which lets us communicate directly with any device connected to the bus. Since native communication is possible, we create a shared library with methods which can be invoked from our C# code. Since we can open the connection to a device on the I2C bus as a file descriptor, we will be making use of fcntl.h for the descriptor. Let’s take a look at the C library.

#include 
#include 
#include 

#define MAX_BYTES 16

/**
 * Open an I2C connection using the specified file descriptor.
 */
int nanite_i2c_open(const char *filename, int slave_address)
{
    int fd;

    if ((fd = open(filename, O_RDWR)) < 0)
    {
        return -1;
    }

    if (ioctl(fd, I2C_SLAVE, slave_address) < 0)
    {
        return -1;
    }

    return fd;
}

The first thing we do is include required headers and define a constant specifying the maximum number of bytes, which is 16. Then we create the nanite_i2c_open function try to open the specified device file (usually /dev/i2c-1). Next we call ioctl so that we will be able to control the device using a reference to the file descriptor, and the specified slave address. The file descriptor is returned for reference in other function calls. If any of the steps in the function fails, -1 is returned to indicate an error condition. Other functions in the library will handle the failure the same way.

The nanite_i2c_close function is fairly simple. It takes the file descriptor as an argument and checks if it is open in order to close it.

/**
 * Close the I2C connection using the specified file descriptor.
 */
int nanite_i2c_close(int fd)
{
    if (fd > 0)
    {
        close(fd);
    }

    return 0;
}

Next is the nanite_i2c_send function which takes the file descriptor and the data to be sent as arguments. The bytes are written to the open file descriptor, and the number of bytes written is verified. If it does not match the length defined in the first byte, -1 is returned to indicate an error condition.

/**
 * Send up to the maximum number of bytes over I2C using the specified file descriptor.
 */
int nanite_i2c_send(int fd, const char bytes[MAX_BYTES])
{
    if (fd <= 0 || !bytes)
    {
        return -1;
    }

    int num_bytes;
    num_bytes = write(fd, bytes, bytes[0]);
    if (num_bytes != bytes[0])
    {
        return -1;
    }

    return num_bytes;
}

The nanite_i2c_read function will be used to read data over I2C. The first byte is retrieved in order to determine how many more bytes to read. Then we validate the number of bytes that were received with the expected length. 0 is returned if the operation was successful.

/**
 * Read the byte data from I2C.
 */
int nanite_i2c_read(int fd, char bytes_read[MAX_BYTES])
{
    if (fd <= 0)
    {
        return -1;
    }

    char fbyte[1];
    // Read the first byte to get the total number of bytes to read
    if (read(fd, fbyte, 1) != 1)
    {
        return -1;
    }

    if (read(fd, bytes_read, fbyte[0]) != fbyte[0])
    {
        return -1;
    }

    return 0;
}

The final function in the library is nanite_i2c_max_bytes() which returns MAX_BYTES. This gives us a complete library that we can use for I2C data communication. You can create the shared library using gcc -shared -o libnanitei2c.so -fPIC main.c. The full code listing for the library is available at https://gitlab.com/akinwale/nanitei2c/blob/master/main.c.

Using DllImport, we can call functions from the shared library in the C# code which we're going to look at next. We create our class, define the supported commands as an enumeration and specify the private members. We also define a couple of constructors with the default constructor using the default I2C device file which is /dev/i2c-1 on the PINE.

using System;
using System.Runtime.InteropServices;
using Nanite.Exceptions;

namespace Nanite.IO
{
    /// 
    /// 
    /// 
    public class I2CExtendedIO : IDisposable
    {
        public enum Commands
        {
            DigitalWrite = 1,
            DigitalRead = 2,
            AnalogWrite = 3
        }

        private const string DefaultI2CFilename = "/dev/i2c-1";

        private Object lockObject = new Object();

        private int fileDescriptor;

        private string i2cFilename;

        public I2CExtendedIO(string i2cFilename)
        {
            this.i2cFilename = i2cFilename;
        }

        public I2CExtendedIO()
            : this(DefaultI2CFilename)
        {

        }

The DllImport calls are defined within the class and are used to map the functions from the library to functions that we can call in the I2CExtendedIO class. For instance, to call the nanite_i2c_send in the class, we'll make use of I2CSendBytes.

        [DllImport("libnanitei2c.so", EntryPoint="nanite_i2c_open")]
        internal static extern int OpenI2C(string filename, int slaveAddress);

        [DllImport("libnanitei2c.so", EntryPoint = "nanite_i2c_close")]
        internal static extern int CloseI2C(int fileDescriptor);

        [DllImport("libnanitei2c.so", EntryPoint = "nanite_i2c_send")]
        internal static extern int I2CSendBytes(int fileDescriptor, byte[] bytes);

        [DllImport("libnanitei2c.so", EntryPoint = "nanite_i2c_read")]
        internal static extern int I2CReadBytes(int fileDescriptor, byte[] bytesRead);

        [DllImport("libnanitei2c.so", EntryPoint = "nanite_i2c_max_bytes")]
        internal static extern int MaxByteCount();

Here, we've defined our class dispose function which closes the file descriptor if it is open. We also have a bunch of simple helper functions which will be called within the class.

        private void ValidateDigitalReadData(int pin, byte[] bytesReceived)
        {
            if (bytesReceived[0] < 3)
            {
                throw new ExtendedIOException("Invalid response data received over the I2C connection.");
            }

            if (bytesReceived[1] != pin)
            {
                throw new ExtendedIOException(string.Format("Pin mismatch for the DigitalRead command. Expected {0} but got {1}.", pin, bytesReceived[1]));
            }

            if (!IsGPIOValueValid(bytesReceived[2]))
            {
                throw new ExtendedIOException("The returned pin value is not valid.");
            }
        }


        private static bool IsGPIOValueValid(int value)
        {
            return ( (value == (int) GPIO.Value.Low) || (value == (int) GPIO.Value.High) );
        }

        private void CheckFileDescriptor()
        {
            if (fileDescriptor <= 0)
            {
                throw new ExtendedIOException("I2C connection is not open.");
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~I2CExtendedIO()
        {
            // Finalizer calls Dispose(false)
            Dispose(false);
        }

        protected virtual void Dispose(bool disposing)
        {
            // Close the file descriptor if it's open
            if (fileDescriptor > 0)
            {
                CloseI2C(fileDescriptor);
                fileDescriptor = -1;
            }
        }

The Open function is simple as it delegates to the OpenI2C function with the specified device filename and the slave address, and assigns the returned file descriptor to a private member.

        public void Open(int slaveAddress)
        {
            fileDescriptor = OpenI2C(i2cFilename, slaveAddress);
            if (fileDescriptor <= 0)
            {
                throw new ExtendedIOException(string.Format("Unable to open the I2C connection to slave address: {0}", slaveAddress));
            }
        }

With DigitalWrite, we build the data to be sent based on the specified rules. Then we delegate to I2CSendBytes using the specified arguments, which calls the corresponding library function.

        public void DigitalWrite(int pin, GPIO.Value value)
        {
            CheckFileDescriptor();

            // Build the command to send
            byte[] bytes = new byte[4];
            bytes[0] = (byte) bytes.Length;
            bytes[1] = (byte) Commands.DigitalWrite;
            bytes[2] = (byte) pin;
            bytes[3] = (byte) value;

            int numBytes = I2CSendBytes(fileDescriptor, bytes);
            if (numBytes != bytes.Length)
            {
                throw new ExtendedIOException(string.Format("Could not send {0} bytes over the I2C connection.", bytes.Length));
            }
        }

AnalogWrite is similar to DigitalWrite, except that we convert the integer value to 4 bytes instead of the single byte for low (0) or high (1). Valid values are between 0 and 255 inclusive.

        public void AnalogWrite(int pin, int value)
        {
            CheckFileDescriptor();

            // Build the command to send
            byte[] bytes = new byte[7];
            bytes[0] = (byte) bytes.Length;
            bytes[1] = (byte) Commands.AnalogWrite;
            bytes[2] = (byte) pin;
            bytes[3] = (byte) (value >> 24);
            bytes[4] = (byte) (value >> 16);
            bytes[5] = (byte) (value >> 8);
            bytes[6] = (byte) value;

            int numBytes = I2CSendBytes(fileDescriptor, bytes);
            if (numBytes != bytes.Length)
            {
                throw new ExtendedIOException(string.Format("Could not send {0} bytes over the I2C connection.", bytes.Length));
            }
        }

To wrap it all up, we have the DigitalRead function which is a little different because we have to send data and then immediately receive a response. We obtain a mutual-exclusion lock so that the send and receive process completes before any subsequent operations are run. Then we validate the received data and return the value for the pin that was read.

        /// 
        /// Reads the pin value
        /// 
        /// Expected byte data always has a length of 3
        ///     bytesReceived[0] - the number of bytes
        ///     bytesReceived[1] - the pin number
        ///     bytesReceived[2] - the pin value
        /// 
        /// GPIO.Value.High if the specified pin is HIGH, or GPIO.Value.Low if the specified pin is LOW.
        /// Pin.
        public GPIO.Value DigitalRead(int pin)
        {
            CheckFileDescriptor();

            // Build the command to send
            byte[] bytes = new byte[3];
            bytes[0] = (byte) bytes.Length;
            bytes[1] = (byte) Commands.DigitalRead;
            bytes[2] = (byte) pin;

            // The array to store received byte data
            byte[] bytesRecvd = new byte[MaxByteCount()];

            // Obtain lock for send/receive
            lock (lockObject)
            {
                // Send the DigitalRead command
                int numBytes = I2CSendBytes(fileDescriptor, bytes);
                if (numBytes != bytes.Length)
                {
                    throw new ExtendedIOException(string.Format("Could not send {0} bytes over the I2C connection.", bytes.Length));
                }

                // Read the response immediately after the command
                I2CReadBytes(fileDescriptor, bytesRecvd);
            }

            ValidateDigitalReadData(pin, bytesRecvd);

            return (GPIO.Value) bytesRecvd[2];
        }

You can obtain the full code listing for the C# class at https://gitlab.com/akinwale/NaniteIo/blob/master/Nanite/IO/I2CExtendedIO.cs.

We can put this all together and test with a simple interactive console application.

public static void Main (string[] args)
{
    // Extended IO via I2C
    using (I2CExtendedIO eio = new I2CExtendedIO())
    {
        try
        {
            eio.Open(0x08);

            string input;
            do
            {
                Console.Write("Enter PIN and value: ");
                input = Console.ReadLine();

                if (input == "-1")
                {
                    break;
                }

                string[] inputParts = input.Split(new char[] { ' ' });
                if (inputParts.Length != 2 && inputParts.Length != 3)
                {
                    Console.WriteLine("Invalid PIN and value. Try again.");
                    continue;
                }

                try
                {
                    int pin = int.Parse(inputParts[0].Trim());
                    string value = inputParts[1];
                    if (value != "off" && value != "on" && inputParts.Length == 2)
                    {
                        Console.WriteLine("Invalid PIN and value. Try again.");
                        continue;
                    }

                    if (inputParts.Length == 3)
                    {
                        int analogValue = int.Parse(inputParts[2].Trim());
                        if (value != "analog")
                        {
                            Console.WriteLine("Invalid PIN and value. Try again.");
                            continue;
                        }

                        eio.AnalogWrite(pin, analogValue);
                    }
                    else
                    {
                        eio.DigitalWrite(pin, "on" == value ? GPIO.Value.High : GPIO.Value.Low);
                    }
                }
                catch (FormatException)
                {
                    Console.WriteLine("Invalid PIN and value. Try again.");
                    continue;
                }
            } while (input != "-1");
        }
        catch (ExtendedIOException ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

The console application accepts inputs like 13 on, 18 off or 9 analog 172 which makes it easy to test the Arduino pins. Although this is practically a complete solution for most requirements with respect to controlling an Arduino connected to the PINE (or Pi or any other SBC) over I2C using C#, you could choose to implement an additional command for analogRead. All you would have to do is follow the logic for digitalRead and add the necessary code to the sketch and the C# class.

Control GPIO pins on the PINE64 with C#

Similar to the Raspberry Pi, GPIO pins on the PINE64 can be controlled through sysfs. You can refer to my previous post which goes into the concept in detail, and the C# code remains the same for the PINE64. However, with the longsleep Ubuntu image, root access is required to control the GPIO pins. You will need to grant the necessary permissions in order to be able to control GPIO pins as a normal user.

Granting user permissions
We’ll assume that we want to be able to control the pins as the default ubuntu user. Follow these steps to grant the necessary permissions.

  1. Create a user group called gpio.
    groupadd gpio
  2. Add the ubuntu user to the gpio group.
    useradd -G gpio ubuntu
  3. Add a udev rule to run chown on the sysfs files. The chown command will set group ownership to the gpio group. Adding the udev rule will run the chown command automatically whenever you export a pin. Create a file called 99-com.rules in /etc/dev/rules.d and paste the following contents.
    SUBSYSTEM=="gpio*", PROGRAM="/bin/sh -c 'chown -R root:gpio /sys/class/gpio && chmod -R 770 /sys/class/gpio; chown -R root:gpio /sys/devices/soc.0/1c20800.pinctrl/gpio && chmod -R 770 /sys/devices/soc.0/1c20800.pinctrl/gpio; chown -R root:gpio /sys/devices/soc.0/1f02c00.pinctrl/gpio && chmod -R 770 /sys/devices/soc.0/1f02c00.pinctrl/gpio'"

    Physical pin to GPIO number mapping
    I took some time to test the physical pins on the PINE in order to determine the sysfs gpio numbers and came up with this table. As an example, physical pin 22 on the Pi 2 pinout corresponds to /sys/class/gpio/gpio79.

    Pin #GPIO #
    Pi 2 pinout
    3227
    5226
    832
    1033
    1171
    1272
    13233
    1576
    1677
    1878
    1964
    2165
    2279
    2366
    2467
    26231
    27361
    28360
    29229
    31230
    3268
    3369
    3573
    3670
    3780
    3874
    4075
    Euler pinout
    7363
    10232
    1135
    1236
    1337
    1538
    1639
    18100
    1998
    2199
    22101
    2397
    2496
    26102
    2734
    28103
    2940
    3041
    Exp pinout
    2359
    740
    841

Building MonoDevelop for the PINE64

MonoDevelop running on the PINE64 using SSH X11 forwarding

4 Dec 2017 Update
These instructions will not work with the latest versions of Mono and MonoDevelop from github. I tried compiling from scratch on a new image, and they will work with the following versions listed below. You can checkout the specific tags immediately after cloning the corresponding repositories before you start building.
Mono 4.8.1.0 – git checkout tags/mono-4.8.1.0
MonoDevelop 6.1.0.5441 – git checkout tags/monodevelop-6.1.0.5441

My PINE64 is here and the first thing I decided to do was build MonoDevelop which I’ll use to manage C# projects, since most of the code I’ll be writing for my autonomous project will be in C#. I’m using the longsleep Ubuntu Xenial image as a base, so these instructions assume that this is what you have installed. You can adapt as required based on your distro.

Of course, the easiest way to get MonoDevelop installed is by using the package manager. The version is also fairly recent (4.2.1.102), so you can choose skip the rest of this post if you prefer. Simply run the apt-get install command and all required dependencies will also be automatically installed.

sudo apt-get install monodevelop

Most of the steps will be similar to the MonoDevelop for Raspberry Pi build post, but we’ll be skipping fsharp altogether. I cloned the fsharp repository but the make process failed due to the following error:

* Assertion at mini-arm64.c:936, condition `arm_is_bl_disp ((code), (target))' not met

F# is only required for the fsharpbindings extension and I don’t plan on using that. There appears to be an fsharp package which you can install using apt, but this will also install the mono 4.2.1 dependencies. If you’re fine with using an older version of mono and would still like to build MonoDevelop, then you can also skip the steps up till Build MonoDevelop.

So let’s get started!

Install all prerequisites
Git is required to clone the source repositories for Mono, MonoDevelop and dependencies. The other packages are required for building MonoDevelop dependencies from source.

sudo apt-get install autoconf automake build-essential cmake gettext git libgdiplus libglade2-dev libgnome2-dev libgnomecanvas2-dev libgnomeui-dev libgtk2.0-dev libssh2-1-dev libtool libtool-bin

 

Pre-build: NuGet certificates
The MonoDevelop build process makes use of NuGet at certain points. You will need to import certificates into your certificate store using the following commands.

sudo mozroots --import --sync
sudo certmgr -ssl -m https://nuget.org

 

Build Mono
This step is fairly straightforward. Clone the mono source repository and run the build process.

git clone https://github.com/mono/mono
./autogen.sh --prefix=/usr
make get-monolite-latest
make -j 4
sudo make install

This build will take a while. If you wish to run the mono and mcs test suites, you can do a make check before make install.
 

Build MonoDevelop dependencies
MonoDevelop requires gtk-sharp and gnome-sharp to be installed on the system. To build gtk-sharp.

git clone -b gtk-sharp-2-12-branch --single-branch https://github.com/mono/gtk-sharp
cd gtk-sharp
./bootstrap-2.12 --prefix=/usr
make -j 4
sudo make install

gnome-sharp follows a similar process.

git clone https://github.com/mono/gnome-sharp
cd gnome-sharp
./bootstrap-2.24 --prefix=/usr
make -j 4
sudo make install

Some reference PCL Assemblies are required for the build to complete. You will need to build a deb package and install following the instructions below.

git clone http://github.com/directhex/xamarin-referenceassemblies-pcl
cd xamarin-referenceassemblies-pcl/debian
nano control

Remove mono-xbuild from the list of dependencies in the control file, save and close. Then proceed with the following commands.

cd ..
debuild -i -us -uc -b
cd ..
sudo dpkg -i referenceassemblies-pcl_2014.04.14-1_all.deb

 

Build MonoDevelop
First, we clone the monodevelop repository and initialise the submodules using git.

git clone https://github.com/mono/monodevelop
cd monodevelop
git submodule update --init --recursive

Next, we remove references to fsharp. The assumed working directory for these steps is the top-level monodevelop source directory.

cd main
nano Makefile.am

Remove the external/fsharpbinding/MonoDevelop.FSharpBinding/FSharpBinding.addin.xml \ line, save the file and close.

rm -r external/fsharpbinding
nano configure.in

Comment out or remove the following lines in the file and save your changes. To comment out the lines, simply prefix each line with the # character.

if test "x$FSHARPC" = "x" ; then
  AC_MSG_ERROR([Can't find "fsharpc" in your PATH])
fi

Then we can go on to build the IDE.

cd ..
./configure --prefix=/usr --profile=stable
make -j 4
sudo make install

You can run mono main/.nuget/NuGet.exe update -self if you get the following error after running make.

Unable to find version '2.8.2' of package 'NuGet.CommandLine'.
Unable to find version '2.6.4' of package 'NUnit.Runners'.

Once the build is successfully completed, you can run the application using monodevelop. If you have X11 forwarding enabled for your SSH session, you should see the MonoDevelop IDE on your screen after a couple of seconds.

MonoDevelop running on the PINE64 using SSH X11 forwarding

MonoDevelop running on the PINE64 using SSH X11 forwarding

How to control GPIO pins on the Raspberry Pi 3 using C#

GPIO pins on the Raspberry Pi can be controlled using the sysfs interface, which is a virtual filesystem that the Linux kernel provides. In this guide, we will write a basic C# class to control available pins on the Pi through sysfs.

Understanding the sysfs interface
sysfs provides access to the GPIO pins at the path /sys/class/gpio. You can cd into this path and ls to list files in the directory. There are two special files here which are export and unexport. You write to the export file to activate a particular pin, while writing to unexport deactivates the pin. The following example activates GPIO pin 18.

echo 18 > /sys/class/gpio/export

You can verify that the pin is activated by listing the files in the /sys/class/gpio directory. You should see a gpio18 folder in the directory listing. After the pin has been activated, you should specify whether the pin should be an input or output pin before you can read or write values. You do this for input like so:

echo in > /sys/class/gpio/gpio18/direction

Or for output:

echo out > /sys/class/gpio/gpio18/direction

If the pin is specified as an output pin, you can write a value of either 0 (low) or 1 (high) for the pin. If a LED is connected to the pin for this example, a value of 0 will turn the LED off, while a value of 1 will turn the LED on. To specify the pin value, you can do this:

echo 1 > /sys/class/gpio/gpio18/value
echo 0 > /sys/class/gpio/gpio18/value

Once you are done with the pin, you can deactivate it using:

echo 18 > /sys/class/gpio/unexport

Writing the C# class
Now that we have an idea of how sysfs works, we can create a class to implement the necessary steps. The sysfs approach basically requires writing values to the file, so we can use simple file I/O operations to achieve the desired result. The full listing for the GPIO class can be found at https://gitlab.com/akinwale/NaniteIo/blob/master/Nanite/IO/GPIO.cs.

The first thing we’ll do is add the using statements for the namespaces. System.IO is required for FileStream, StreamReader and StreamWriter which are used for file I/O. System.Threading is required for the Thread class, while Nanite.Exceptions contains the custom exceptions defined for our project. We’ll also define enumerations for the GPIO direction and value, and a few constants for strings like the GPIO path and other special files. The class will be defined as static, because we do not need to create an instance of the class.

using System.IO;
using System.Threading;
using Nanite.Exceptions;

namespace Nanite.IO
{
    public static class GPIO
    {
        public enum Direction
        {
            Input = 0,
            Output = 1
        };

        public enum Value
        {
            Low = 0,
            High = 1
        };

        private const string GPIOPath = "/sys/class/gpio";

        private const string GPIODirection = "direction";

        private const string GPIOExport = "export";

        private const string GPIOUnexport = "unexport";

        private const string GPIOValue = "value";

Pretty straightforward so far. The first method we’re going to define is the PinMode method, which will take the pin number and direction as parameters. This method will activate the pin and then set the direction to either in or out depending on the specified parameter value.

public static void PinMode(int pin, Direction direction)
{
    ClosePin(pin);

    string pinPath = Path.Combine(GPIOPath, string.Format("gpio{0}", pin));
    if (!Directory.Exists(pinPath))
    {
        try
        {
            using (StreamWriter writer = new StreamWriter(new FileStream(
                Path.Combine(GPIOPath, GPIOExport), FileMode.Open, FileAccess.Write, FileShare.ReadWrite)))
            {
                writer.Write(pin);
            }
        }
        catch (IOException ex)
        {
            throw new GPIOException("Unable to export the pin.", ex);
        }
    }

    do
    {
        // Wait until the pin has been initialised properly before setting the direction
        Thread.Sleep(500);
    } while (!Directory.Exists(pinPath));

    try
    {
        using (StreamWriter writer = new StreamWriter(new FileStream(
            Path.Combine(pinPath, GPIODirection), FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite)))
        {
            writer.Write(direction == Direction.Input ? "in" : "out");
        }
    }
    catch (IOException ex)
    {
        throw new GPIOException("Unable to set the pin direction.", ex);
    }
}

We build the pinPath string making use of Path.Combine(GPIOPath, string.Format("gpio{0}", pin));. If the value specified for the pin parameter is 18, pinPath will contain the string, "/sys/class/gpio/gpio18". The ClosePin method call is optional, but the idea behind this is that the pin should be deactivated first before activating. We also check if the gpio pin directory exists using if (!Directory.Exists(pinPath)) before activating to make sure we are not activating a pin that has already been activated.

After the request for pin activation, there may be a small delay which is why we have a while loop which waits until the corresponding gpio pin directory has been created before we set the pin direction. Thread.Sleep(500) makes the program wait 500 milliseconds before proceeding to the next statement. Note that this while loop is completely optional, but it acts as a safeguard against setting the pin direction before the gpio pin directory has been created by the system. One thing to take note of is if the gpio pin directory never gets created (for instance, if the pin is invalid), the loop may end up running forever. To fix this, we can set a maximum number of times the loop should run before ending the loop.

int loopCount = 1;
do
{
    if (loopCount > 5)
    {
        // Exit the loop after it has been run 5 times (waited for 2.5s)
        break;
    }

    // Wait until the pin has been initialised properly before setting the direction
    Thread.Sleep(500);
    loopCount++;
} while (!Directory.Exists(pinPath));

The next method is the ClosePin method which takes the pin number as a parameter. This method checks if the pin directory exists before it writes the pin number to the /sys/class/gpio/unexport file.

public static void ClosePin(int pin)
{
    string pinPath = Path.Combine(GPIOPath, string.Format("gpio{0}", pin));
    if (Directory.Exists(pinPath))
    {
        try
        {
            using (StreamWriter writer = new StreamWriter(new FileStream(
                Path.Combine(GPIOPath, GPIOUnexport), FileMode.Open, FileAccess.Write, FileShare.ReadWrite)))
            {
                writer.Write(pin);
            }
        }
        catch (IOException ex)
        {
            throw new GPIOException("Unable to close the pin.", ex);
        }
    }
}

We create the Write method to write a value to a pin. It takes two parameters, the pin number and the value which is of the Value enumerator type with possible values Value.Low or Value.High. In this method, we make use Path.Combine to create the full path to the value file in the gpio pin directory. For pin 18, this will be "/sys/class/gpio/gpio18/value". If value for the value parameter is Value.Low, we write 0 to the file, otherwise if it’s Value.High, we write 1 to the file.

public static void Write(int pin, Value value)
{
    try
    {
        string pinPath = Path.Combine(GPIOPath, string.Format("gpio{0}", pin));
        using (StreamWriter writer = new StreamWriter(new FileStream(
            Path.Combine(pinPath, GPIOValue), FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite)))
        {
            writer.Write(value == Value.Low ? 0 : 1);
        }
    }
    catch (IOException ex)
    {
        throw new GPIOException("Unable to write the pin value.", ex);
    }
}

Finally, we have our Read method to read a value from a pin. It will return either Value.Low or Value.High depending on what the pin has been set to. The question mark at the end of the method return type indicates that we can return null for the method if the value retrieved is invalid.

public static Value? Read(int pin)
{
    int pinValue = -1;

    try
    {
        string pinPath = Path.Combine(GPIOPath, string.Format("gpio{0}", pin));
        using (StreamReader reader = new StreamReader(new FileStream(
            Path.Combine(pinPath, GPIOValue), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
        {
            int.TryParse(reader.ReadToEnd(), out pinValue);
        }
    }
    catch (IOException ex)
    {
        throw new GPIOException("Unable to read the pin value.", ex);
    }

    if (pinValue != 0 && pinValue != 1)
    {
        return null;
    }

    return (Value) pinValue;
}

To determine if the retrieved value is valid, we add a couple of checks in the method. The first is the int.TryParse method, which returns false if the retrieved value is not a valid integer. Then verify that the value is either 0 or 1 using if (pinValue != 0 && pinValue != 1). If it’s neither 0 nor 1, null is returned. Otherwise, the corresponding enumeration value is returned by casting the integer to GPIO.Value.

Finally, we can put this all together in a sample program. If a LED is connected to pin 18, the LED will light up when the value is set to High and turn off when the value is set to Low.

using System;
using System.Threading;
using Nanite.IO;
using Nanite.Exceptions;

namespace NaniteIoSample
{
    class Program
    {
        public static void Main(string[] args)
        {
            // Activate the pin and set the direction as Output
            GPIO.PinMode(18, GPIO.Direction.Output);

            // Blink a LED connected to pin 18 up to 50 times
            for (int i = 0; i < 50; i++)
            {
                GPIO.Write(18, GPIO.Value.High);
                Thread.Sleep(200);

                GPIO.Write(18, GPIO.Value.Low);
                Thread.Sleep(200);
            }

            // Close the pin after we're done
            GPIO.ClosePin(18);
        }
    }
}

Source Code
The full code listing for the GPIO class can be obtained from https://gitlab.com/akinwale/NaniteIo/blob/master/Nanite/IO/GPIO.cs.

Building MonoDevelop for the Raspberry Pi 3

4 Dec 2017 Update
I ran into some issues building the latest github versions of Mono and MonoDevelop on the PINE64, and I guess the same may apply here. If you encounter any difficulty building either Mono or MonoDevelop, you can try using the specific versions listed below. You can checkout the specific tags immediately after cloning the corresponding repositories before you start building.
Mono 4.8.1.0 – git checkout tags/mono-4.8.1.0
MonoDevelop 6.1.0.5441 – git checkout tags/monodevelop-6.1.0.5441

Since I will be using C# for most of my development (with a combination of C for some native system functionality), I decided to go with Mono. This guide is based on the assumption that you’re running the May 2016 Raspbian Jessie Lite image. The easiest way to get MonoDevelop up and running would be to run sudo apt-get install monodevelop which would also handle all the necessary dependencies including the Mono runtime. However, the versions in the repository are pretty old, and I want to be able to make use of .NET 4 features.

Another option for .NET development on Linux is .NET Core. Version 1.0 was officially announced by Microsoft a few days ago, but there aren’t ARM binaries available and I haven’t been able to successfully build it for the Pi, yet.

Git
The Mono project code is hosted on Github, so the first thing to be done is to install git.

sudo apt-get install git

Build Mono
Obtain the source code from the Github repository using the command

git clone https://github.com/mono/mono

Then install the Mono build process prerequisites.

sudo apt-get install autoconf autotool libtool libtool-bin

You can follow the build instructions in the README.md for the repository at https://github.com/mono/mono/blob/master/README.md. To summarise, change to the source root directory (cd mono) and run the following commands.

./autogen.sh --prefix=/usr
make get-monolite-latest
make
sudo make install

If you wish to run the mono and mcs test suites, you can do a make check before make install. The build will take quite a while, so you have to be patient. I didn't time my build, but my best guess would be about 3 to 4 hours.

Build FSharp
MonoDevelop apparently requires the F# compiler to be installed. First thing to do is to import trusted root certificates required by the NuGet package manager into the machine store. The NuGet package manager retrieves certain required packages as part of the build process, so this is required.

sudo mozroots --import --sync
sudo certmgr -ssl -m https://nuget.org

Next, we clone the FSharp git repository and build.

git clone https://github.com/fsharp/fsharp
cd fsharp
./autogen.sh --prefix=/usr
make
sudo make install

Build additional MonoDevelop dependencies
MonoDevelop also requires gtk-sharp and gnome-sharp to be installed on the system. The first step is to install the rest of the apt dependencies for all three packages.

sudo apt-get install cmake libgtk2.0-dev libglade2-dev libgnomecanvas2-dev libgnome2-dev libgnomeui-dev libssh2-1-dev devscripts

devscripts will be used to create a package of PCL Assemblies which is required for the MonoDevelop build process.

Once the dependencies have been installed, gtk-sharp should be built first and then gnome-sharp.

To build gtk-sharp

git clone -b gtk-sharp-2-12-branch --single-branch https://github.com/mono/gtk-sharp
cd gtk-sharp
./bootstrap-2.12 --prefix=/usr
make
sudo make install

And gnome-sharp

git clone https://github.com/mono/gnome-sharp
cd gnome-sharp
./bootstrap-2.24 --prefix=/usr
make
sudo make install

Build MonoDevelop
If you made it through all of that, you can finally proceed to build MonoDevelop. But there are a few caveats which we'll cover in a bit.

git clone https://github.com/mono/monodevelop
cd monodevelop
git submodule update --init --recursive
./configure --prefix=/usr --profile=stable --disable-nls

The first error I encountered after I running make was an issue with NuGet not finding a number of packages. To fix this while your current directory is the monodevelop directory, run the following commands and then run make again (if you've run it previously).

cd main/.nuget
mono NuGet.exe update -self
cd ../../

The next error stated that certain PCL Assemblies were missing. To sort this out

git clone http://github.com/directhex/xamarin-referenceassemblies-pcl
cd xamarin-referenceassemblies-pcl/debian
nano control

Remove mono-xbuild from the list of dependencies in the control file, save and close. Then continue with the following commands.

cd ..
debuild -i -us -uc -b
cd ..
sudo dpkg -i referenceassemblies-pcl_2014.04.14-1_all.deb

The final error had to do with the fsharpbinding regarding missing references in a particular assembly. Since I don't need the F# bindings, and it's not a required feature, I removed it from the build process using the following steps (assuming the monodevelop source directory is the working directory).

cd main
nano Makefile.am

Remove the external/fsharpbinding/MonoDevelop.FSharpBinding/FSharpBinding.addin.xml \ line, save the file and close.

rm -r external/fsharpbinding
cd ../

Finally, you can build and install.

make
sudo make install

This build will also take a bit of time, so sit back, relax and rest easy. Once the installation is complete, you can simply run it by typing monodevelop at the command line (assuming you have X11 forwarding enabled in your SSH session).