如何在 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)。安装可以参考这个
<https://blog.csdn.net/sD7O95O/article/details/812952862>。(不管是 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
<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
<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 的操作。
热门工具 换一换