Skip to content

Latest commit

 

History

History
91 lines (60 loc) · 3.38 KB

File metadata and controls

91 lines (60 loc) · 3.38 KB
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

Blink an LED

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.

[!VIDEO https://learn-video.azurefd.net/vod/player?show=dotnet-iot-for-beginners&ep=general-purpose-inputoutput-use-gpio-output-to-control-devices-with-dotnet-dotnet-iot-for-beginners]

Prerequisites

  • [!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]

Prepare the hardware

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]

Create the app

Complete the following steps in your preferred development environment:

  1. Create a new .NET Console App using either the .NET CLI or Visual Studio. Name it BlinkTutorial.

    dotnet new console -o BlinkTutorial
    cd BlinkTutorial
    
  2. [!INCLUDE tutorial-add-packages]

  3. 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. 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:
      1. Writes a value to GPIO pin 18. If ledOn is true, it writes PinValue.High (on). Otherwise, it writes PinValue.Low.
      2. Sleeps 1000 ms.
      3. Toggles the value of ledOn.
  4. [!INCLUDE tutorial-build]

  5. [!INCLUDE tutorial-deploy]

  6. 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.

  7. Terminate the program by pressing Ctrl+C.

Congratulations! You've used GPIO to blink an LED.

Get the source code

The source for this tutorial is available on GitHub.

Next steps

[!div class="nextstepaction"] Learn how to read binary input using GPIO