General-purpose I/O (GPIO) pins can be controlled individually. This is useful for controlling LEDs, relays, and other stateful devices. In this topic, you will use .NET and your Raspberry Pi's GPIO pins to power an LED and blink it repeatedly.
Prerequisites
ARM-based (ARMv7 or greater) single-board computer (SBC)
5 mm LED
330 Ω resistor
Breadboard
Jumper wires
Raspberry Pi GPIO breakout board (optional/recommended)
This tutorial is written assuming the target device is Raspberry Pi. However, this tutorial can be used for any Linux-based SBC that supports .NET, such as Orange Pi, ODROID, and more.
Replace the contents of Program.cs with the following code:
C#
using System;
using System.Device.Gpio;
using System.Threading;
Console.WriteLine("Blinking LED. Press Ctrl+C to end.");
int pin = 18;
usingvar controller = new GpioController();
controller.OpenPin(pin, PinMode.Output);
bool ledOn = true;
while (true)
{
controller.Write(pin, ((ledOn) ? PinValue.High : PinValue.Low));
Thread.Sleep(1000);
ledOn = !ledOn;
}
In the preceding code:
A using declaration creates an instance of GpioController. The using declaration ensures the object is disposed and hardware resources are released properly.
GPIO pin 18 is opened for output
A while loop runs indefinitely. Each iteration:
Writes a value to GPIO pin 18. If ledOn is true, it writes PinValue.High (on). Otherwise, it writes PinValue.Low.
Sleeps 1000 ms.
Toggles the value of ledOn.
Build the app. If using the .NET CLI, run dotnet build. To build in Visual Studio, press Ctrl+Shift+B.
Deploy the app to the SBC as a self-contained app. For instructions, see Deploy .NET apps to Raspberry Pi. Make sure to give the executable execute permission using chmod +x.
Run the app on the Raspberry Pi by switching to the deployment directory and running the executable.
Bash
./BlinkTutorial
The LED blinks off and on every second.
Terminate the program by pressing Ctrl+C.
Congratulations! You've used GPIO to blink an LED.
Izvor za ovaj sadržaj možete pronaći na GitHubu, gdje možete stvarati i pregledavati probleme i zahtjeve za povlačenjem. Dodatne informacije potražite u našem vodiču za suradnike.
Povratne informacije o proizvodu .NET
.NET je projekt otvorenog koda. Odaberite vezu za slanje povratnih informacija:
Pridružite se seriji susreta kako biste s kolegama programerima i stručnjacima izgradili skalabilna rješenja umjetne inteligencije temeljena na stvarnim slučajevima upotrebe.