Automated Irrigation System Using Windows IoT

Posted by Alex Green on

Managing water resources efficiently is crucial for modern agriculture. This project demonstrates how to build a low‑cost, remotely controlled irrigation system using a Windows IoT device (Raspberry Pi 4) and Azure IoT Hub.

Hardware Overview

  • Windows IoT Core on Raspberry Pi 4
  • Soil‑moisture sensors (capacitive)
  • 4‑channel relay module for pump control
  • Azure IoT Hub for cloud‑to‑device messaging

Sample Code (C#)

// Program.cs
using System;
using Windows.Devices.Gpio;
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;

class IrrigationController
{
    static GpioPin moisturePin, relayPin;
    static DeviceClient client;

    static async Task Main()
    {
        InitGpio();
        client = DeviceClient.CreateFromConnectionString(
            "HostName=your-iot-hub.azure-devices.net;DeviceId=raspi01;SharedAccessKey=...", TransportType.Mqtt);
        await client.SetMethodHandlerAsync("SetIrrigation", SetIrrigationAsync, null);
        Console.WriteLine("IoT Hub ready.");
        while (true)
        {
            var moisture = moisturePin.Read();
            await client.SendEventAsync(new Message(
                System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { moisture }))));
            await Task.Delay(30000);
        }
    }

    static void InitGpio()
    {
        var gpio = GpioController.GetDefault();
        moisturePin = gpio.OpenPin(5);
        relayPin = gpio.OpenPin(6);
        relayPin.SetDriveMode(GpioPinDriveMode.Output);
        relayPin.Write(GpioPinValue.Low);
    }

    static async Task SetIrrigationAsync(MethodRequest request, object userContext)
    {
        var payload = JsonConvert.DeserializeObject<dynamic>(request.DataAsString);
        bool on = payload?.on ?? false;
        relayPin.Write(on ? GpioPinValue.High : GpioPinValue.Low);
        return new MethodResponse(0);
    }
}

Deploying the Application

  1. Flash the Windows IoT image to the SD card.
  2. Enable Developer Mode on the device.
  3. Install Visual Studio with the Windows IoT workload.
  4. Deploy the project via Remote Machine debugging.
  5. Configure the Azure IoT Hub connection string in appsettings.json.
#WindowsIoT#AzureIoTHub#Agriculture#CSharp

Comments (3)

User avatar
Maria L.
Sep 12, 2025 at 09:42 AM
Great walkthrough! I integrated a weather API to pause irrigation when rain is forecasted—works beautifully.
User avatar
Tom R.
Sep 13, 2025 at 02:15 PM
Any tips for reducing power consumption? The Pi runs hot when the relay is on.
User avatar
Jenny K.
Sep 14, 2025 at 11:08 AM
Consider using the GPIO power management API to put the Pi in low‑power mode between cycles.