Categories
Uncategorized

Run .NET programs on Raspberry Pi

What was once unthinkable has now happened: you can run software written for Microsoft’s .NET framework on Linux. This means you can now write code in Visual Studio on a PC that can be executed on a pi running Linux.

The process is pretty simple. Let’s start by assuming you have Visual Studio (at least the 2017 version) and a current version of the .NET SDK on your host computer. You can download that from Microsoft here.

Open a new command shell and create a directory called blinky.

Go to the directory: cd blinky.

Type the command dotnet new console

This creates a Visual Studio project called blinky. Replace the Program.cs file with our sample code (TBD) to blink an LED.

Build the program for Linux with the command dotnet publish -r linux-arm

We now have an application package in the publish subdirectory that we can load onto a Raspberry Pi running Linux. Let’s get the pi setup to run .NET Core. We’re going to assume that it’s running Raspbian Debian 9 Jessie since that’s current as this is written.

sudo apt-get install curl libunwind8 gettext apt-transport-https

sudo apt-get update

After the .NET Core framework has been installed, copy the publish directory from your PC to the pi and execute the blinky.exe program to run it. Enjoy your blinking LED!

Here is the source code of the blinky Program.cs

using System;
using System.Threading;
using System.Device.Gpio;

namespace blinky
{
    // Blinks an LED on GPIO pin 16 on a Raspberry pi
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            int pin = 16;
            GpioController controller = new GpioController();
            controller.OpenPin(pin, PinMode.Output);

            int lightTimeInMilliseconds = 1000;
            int dimTimeInMilliseconds = 200;

            while (true)
            {
                Console.WriteLine($"Light for {lightTimeInMilliseconds}ms");
                controller.Write(pin, PinValue.High);
                Thread.Sleep(lightTimeInMilliseconds);
                Console.WriteLine($"Dim for {dimTimeInMilliseconds}ms");
                controller.Write(pin, PinValue.Low);
                Thread.Sleep(dimTimeInMilliseconds);
            }
        }
    }
}



If you'd like to subscribe to this blog, please click here.