如何在 Raspberry Pi 的 Raspbian 上構建使用 GPIO 引腳的 IoT 程序?你可能會回答使用 C++ 或 Python 去訪問 Raspberry Pi 的引腳。現在,C# 程序員可以使用 .NET Core 在 Raspbian(Linux) 上構建 IoT 應用程序。只需要引入 System.Device.GPIO NuGet 包即可。
注意
System.Device.GPIO 仍處於早期預覽狀態。並且目前僅支持部分 Raspberry Pi 、 Pine64 和 Hummingboard 的板子。
若要繼續閱讀下面的內容,你需要準備:
- 安裝有 Linux 的 Raspberry Pi 2B/3B/3B+
- Visual Studio 2017
- 用於構建程序的 .NET Core SDK (版本大於 2.1)
環境配置
首先在 Raspbian 的 Terminal 上運行如下命令,以安裝運行程序所依賴的程序包。
sudo apt-get update sudo apt-get install curl libunwind8 gettext apt-transport-https
提示
① 遠程訪問 Raspbian 可以使用 putty 通過 SSH 進行訪問,也可以使用 apt 安裝 xrdp ,通過 Windows 遠程桌面進行訪問。
② 運行 ASP.NET Core 程序還需要安裝運行時(Runtime)。安裝可以參考這個。(不管是 3B 還是 3B+ ,Raspbian 的內核都爲 32 位,部分 ASP.NET Core 常用的 NuGet 包並不支持 arm32)
打開菜單中的 Raspberry Pi 配置,獲取必要的硬件接口的訪問權限。
打開 Visual Studio 的設置,在 NuGet 包管理器設置下,添加 .NET Core Lab 的程序包源:https://dotnet.myget.org/F/dotnet-corefxlab/api/v3/index.json
Blink
熟悉 Arduino 的朋友都知道,Blink 是默認燒寫進 Arduino 的初始程序,控制板載連接 13 號引腳的 LED 閃爍。是一種類似於“Hello World”的存在。這裏我們將 LED 小燈連接至 Raspberry Pi 的 GPIO 17 引腳。
硬件
- 一顆 LED 小燈
- 一個 220 Ω 電阻
- 若干杜邦線
電路
圖源:https://github.com/dotnet/iot/tree/master/samples/led-blink
代碼
打開 Visual Studio ,新建一個 .NET Core 控制檯應用程序,項目名稱爲“Blink”。
打開 “工具”——“NuGet包管理器”——“程序包管理器控制檯”,運行如下命令,以獲取程序包。
Install-Package System.Devices.Gpio -Version 0.1.0-preview2-181222-2
在 Program.cs 中,替換如下代碼:
using System; using System.Devices.Gpio; using System.Threading; namespace Blink { class Program { static void Main(string[] args) { // get the GPIO controller // 獲取 GPIO 控制器 GpioController controller = new GpioController(PinNumberingScheme.Gpio); // open PIN 17 // 打開引腳 17 GpioPin ledPin = controller.OpenPin(17, PinMode.Output); // define delay time // 設置延遲時間 int time = 1000; // loop // 循環 while (true) { Console.WriteLine($"Light for {time}ms"); // turn the LED on // 打開 LED ledPin.Write(PinValue.High); // wait for a second // 等待 1s Thread.Sleep(time); Console.WriteLine($"Dim for {time}ms"); // turn the LED off // 關閉 LED ledPin.Write(PinValue.Low); // wait for a second // 等待 1s Thread.Sleep(time); } } } }
部署
在“程序包管理器控制檯”運行發佈命令:
dotnet publish -c release -r linux-arm
提示
默認的發佈路徑是在 “\Blink\bin\Release\netcoreappXXX\win10-arm\publish”。你也可以使用 -o 來指定發佈路徑,如:-o D:\BlinkPublish ,這將會發布在 D 盤的 BlinkPublish 文件夾下。
使用 FTP 工具將生成的發佈文件夾複製到 Raspberry Pi 上,這裏使用的是 WinSCP 。
提示
Raspbian 使用 FTP 服務,請使用 apt 安裝 vsftpd 。
更改程序權限。使用 cd 命令切換到發佈的文件夾,運行:
chmod 755 ./Blink
或使用 FTP 工具進行變更
執行 ./Blink 運行程序,此時 LED 小燈應該一閃一閃的了。
備註
下一篇文章將使用紅外傳感器進一步熟悉 GPIO 的操作。