This tutorial guides you through the fundamental process of controlling a hardware component, an LED, using Windows IoT Core. You'll learn how to set up your hardware, write a simple C# application, and deploy it to your Raspberry Pi or other compatible device.
Connect the components as follows:
A typical setup showing an LED connected to a GPIO pin via a resistor.
Follow these steps to create your C# Universal Windows Platform (UWP) application:
Open Visual Studio and create a new project. Select the Blank App (Universal Windows) template using C#.
Name your project something like BlinkyLED and click Create.
Right-click on your project in the Solution Explorer and select Manage NuGet Packages.... Search for and install the WindowsIoT.Device` package. This package provides essential APIs for interacting with hardware.
Open the MainPage.xaml.cs file and replace its contents with the following C# code:
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Devices.Gpio;
using System;
namespace BlinkyLED
{
public sealed partial class MainPage : Page
{
private GpioController gpioController;
private GpioPin pin;
private DispatcherTimer timer;
private const int LED_PIN = 5; // GPIO pin number
public MainPage()
{
this.InitializeComponent();
InitializeGpio();
}
private void InitializeGpio()
{
gpioController = GpioController.GetDefault();
if (gpioController == null)
{
// Handle error: no GPIO controller found
return;
}
pin = gpioController.OpenPin(LED_PIN);
pin.SetDriveMode(GpioPinDriveMode.Output);
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(500); // Blink every 500ms
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, object e)
{
if (pin.Read() == GpioPinValue.Low)
{
pin.Write(GpioPinValue.High); // Turn LED on
}
else
{
pin.Write(GpioPinValue.Low); // Turn LED off
}
}
// It's good practice to release GPIO resources when the app closes
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
if (pin != null)
{
timer.Stop();
pin.Dispose();
pin = null;
}
base.OnNavigatedFrom(e);
}
}
}
GpioController.GetDefault(): Gets the default GPIO controller.gpioController.OpenPin(LED_PIN): Opens the specified GPIO pin.pin.SetDriveMode(GpioPinDriveMode.Output): Configures the pin as an output.DispatcherTimer: Used to create a timed event that toggles the LED state.pin.Write(): Sets the output state of the pin (High for on, Low for off).pin.Dispose(): Releases the GPIO pin resources when the application is closing.Configure your project for deployment:
Make sure your Windows IoT Core device is discoverable on your network. You can find its IP address using tools like the IoT Dashboard or by connecting a monitor and keyboard.
Once the application is running on your device, the LED connected to GPIO pin 5 should start blinking on and off at approximately one-second intervals.