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:
1mkdir aspnet.webapi.rpi.gpio
2cd aspnet.webapi.rpi.gpio
Create an ASP.NET Core Web API project
Create an ASP.NET Core Web API project with the following command:
1dotnet new webapi
Add a reference to Unosquare.Raspberry.IO
1dotnet add package Unosquare.Raspberry.IO
Now restore the packages:
1dotnet restore
Create BlinkyController.cs
In the Controllers folder, create a BlinkyController.cs file with the following contents:
1using Microsoft.AspNetCore.Mvc;
2using Unosquare.RaspberryIO;
3using Unosquare.RaspberryIO.Gpio;
4
5namespace aspnet.webapi.rpi.gpio.Controllers
6{
7 [Route("api/[controller]")]
8 public class BlinkyController : Controller
9 {
10 [HttpPost]
11 public void Post([FromBody]bool isOn)
12 {
13 // Control GPIO pin 5
14 var pin = Pi.Gpio.Pin05;
15 pin.PinMode = GpioPinDriveMode.Output;
16 pin.Write(!isOn);
17 }
18 }
19}
Note: The sample toggles GPIO pin 5.
Publish the application
Publish the application with the following commands:
1dotnet 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:
1sudo -i
2cd /home/pi/publish
3chmod +x aspnet.webapi.rpi.gpio
4export ASPNETCORE_URLS="http://*:5000"
5./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:
1curl -H "Content-Type: application/json" -d 'true' http://[ip of your raspberry]:5000/api/blinky
To Turn it off:
1curl -H "Content-Type: application/json" -d 'false' http://[ip of your raspberry]:5000/api/blinky
Get the code here.
Hope it helps!
Comments