Toggle Raspberry Pi GPIO Pins with ASP.NET Core 2.0
Categories:
2 minute read
Today I’ll show you how to Toggle Raspberry Pi GPIO Pins with ASP.NET Core 2.0.
First be aware of the following prerequisites:
- .NET Core 2.0 SDK
- A Raspberry Pi 3 Running Raspbian
- Install linux dependencies: sudo apt-get install curl libunwind8 gettext
Now let’s start:
Create a folder for your new project
Open a command prompt an run:
mkdir aspnet.webapi.rpi.gpio
cd aspnet.webapi.rpi.gpio
Create an ASP.NET Core Web API project
Create an ASP.NET Core Web API project with the following command:
dotnet new webapi
Add a reference to Unosquare.Raspberry.IO
dotnet add package Unosquare.Raspberry.IO
Now restore the packages:
dotnet restore
Create BlinkyController.cs
In the Controllers folder, create a BlinkyController.cs file with the following contents:
using Microsoft.AspNetCore.Mvc;
using Unosquare.RaspberryIO;
using Unosquare.RaspberryIO.Gpio;
namespace aspnet.webapi.rpi.gpio.Controllers
{
[Route("api/[controller]")]
public class BlinkyController : Controller
{
[HttpPost]
public void Post([FromBody]bool isOn)
{
// Control GPIO pin 5
var pin = Pi.Gpio.Pin05;
pin.PinMode = GpioPinDriveMode.Output;
pin.Write(!isOn);
}
}
}
Note: The sample toggles GPIO pin 5.
Publish the application
Publish the application with the following commands:
dotnet publish -c Release -r linux-arm
Copy the files to your Raspberry
Copy the contents of the folder \aspnet.on.rpi\bin\Release\netcoreapp2.0\linux-arm\publish to the Raspberry (i.e. /home/pi/publish)
Note: For this task I connect to the Raspberry via SFTP using WinSCP
Run the application
Connect to Raspberry using ssh and then run the following commands:
sudo -i
cd /home/pi/publish
chmod +x aspnet.webapi.rpi.gpio
export ASPNETCORE_URLS="http://*:5000"
./aspnet.webapi.rpi.gpio
Note: Unosquare.Raspberry.IO must be run with elevated privileges.
Call the Web API to Toggle the GPIO pin
Post data to the Web API to toggle the GPIO pin.
To turn it on:
curl -H "Content-Type: application/json" -d 'true' http://[ip of your raspberry]:5000/api/blinky
To Turn it off:
curl -H "Content-Type: application/json" -d 'false' http://[ip of your raspberry]:5000/api/blinky
Get the code here.
Hope it helps!