| title | Blink an LED |
|---|---|
| description | Learn how to blink an LED with the .NET IoT Libraries. |
| author | camsoper |
| ms.date | 07/31/2024 |
| ms.topic | tutorial |
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.
- [!INCLUDE prereq-sbc]
- 5 mm LED
- 330 Ω resistor
- Breadboard
- Jumper wires
- Raspberry Pi GPIO breakout board (optional/recommended)
- [!INCLUDE tutorial-prereq-dotnet]
[!INCLUDE rpi-note]
[!INCLUDE ensure-ssh]
Use the hardware components to build the circuit as depicted in the following diagram:
:::image type="content" source="../media/rpi-led_bb-thumb.png" alt-text="A Fritzing diagram showing a circuit with an LED and a resistor" lightbox="../media/rpi-led_bb.png":::
The image above depicts the following connections:
- GPIO 18 to LED anode (longer, positive lead)
- LED cathode (shorter, negative lead) to 330 Ω resistor (either end)
- 330 Ω resistor (other end) to ground
[!INCLUDE tutorial-rpi-gpio]
[!INCLUDE gpio-breakout]
Complete the following steps in your preferred development environment:
-
Create a new .NET Console App using either the .NET CLI or Visual Studio. Name it BlinkTutorial.
dotnet new console -o BlinkTutorial cd BlinkTutorial -
[!INCLUDE tutorial-add-packages]
-
Replace the contents of Program.cs with the following code:
:::code language="csharp" source="~/iot-samples/tutorials/BlinkTutorial/Program.cs" :::
In the preceding code:
- A using declaration creates an instance of
GpioController. Theusingdeclaration ensures the object is disposed and hardware resources are released properly. - GPIO pin 18 is opened for output
- A
whileloop runs indefinitely. Each iteration:- Writes a value to GPIO pin 18. If
ledOnis true, it writesPinValue.High(on). Otherwise, it writesPinValue.Low. - Sleeps 1000 ms.
- Toggles the value of
ledOn.
- Writes a value to GPIO pin 18. If
- A using declaration creates an instance of
-
[!INCLUDE tutorial-build]
-
[!INCLUDE tutorial-deploy]
-
Run the app on the Raspberry Pi by switching to the deployment directory and running the executable.
./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.
The source for this tutorial is available on GitHub.
[!div class="nextstepaction"] Learn how to read binary input using GPIO