GadgetGamesAU
Published © GPL3+

WLED-Connected WiFi Radar Trigger

A simple M5 Atom Lite project, using .NET nanoFramework and a human presence radar to trigger a WLED-controlled sign!

BeginnerFull instructions provided4 hours406
WLED-Connected WiFi Radar Trigger

Things used in this project

Hardware components

ATOM Lite ESP32 Development Kit
M5Stack ATOM Lite ESP32 Development Kit
×1
HLK-LD2410B FMCW 24G Human Presence Status Sensing Radar
×1
5V USB Power Bank
×1
Jumper wires (generic)
Jumper wires (generic)
×1

Software apps and online services

nanoFramework.CoreLibrary
.NET nanoFramework nanoFramework.CoreLibrary

Hand tools and fabrication machines

Soldering iron (generic)
Soldering iron (generic)
Solder Wire, Lead Free
Solder Wire, Lead Free

Story

Read more

Code

Main Program File

C#
using System;
using System.Collections;
using System.Device.Gpio;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using nanoFramework.Networking;
using System.Drawing;
using Iot.Device.Ws28xx.Esp32;
using nanoFramework.Runtime.Native;
using nanoFramework.Hardware.Esp32;

namespace WLEDRadarSensor
{
    public class WledRadarMainClass
    {
        private static AutoResetEvent sendMessage = new AutoResetEvent(false);
        private static GpioPin _userButton;
        private static GpioPin _radarDetect;
        private static HttpClient _httpClient;

        //Wled preset-setting Json
        public const string str_WLEDON = "{\"on\":\"t\",\"v\":true}";
        public const string str_WLEDOFF = "{\"on\":\"t\",\"v\":false}";

        //Wled preset-setting Json, turns strip on and tells it to run presets 1 or two
        public const string str_WLED_PRESETONE = "{\"on\":\"t\",\"ps\":\"1\",\"v\":false}";
        public const string str_WLED_PRESETTWO = "{\"on\":\"t\",\"ps\":\"2\",\"v\":false}";

        //Local tracking of what the state of the strip is
        public static bool isLedstripOn = false;

        public static bool isChangingLEDStrip = false;

        //Make sure we track the first time we run the loop to force an update
        public static bool firstTime = true;

        public static Iot.Device.Ws28xx.Esp32.Sk6812 neoPixel = new Iot.Device.Ws28xx.Esp32.Sk6812(27, 1, 1);

        public static void Main()
        {
            const string Ssid = "WIFISSID";
            const string Password = "WIFIPASSWORD";

            Debug.WriteLine("Connecting to wifi");

            // Give 60 seconds to the wifi join to happen
            CancellationTokenSource cs = new(60000);
            var success = WifiNetworkHelper.ConnectDhcp(Ssid, Password, requiresDateTime: true, token: cs.Token);
            if (!success)
            {
                // Something went wrong, you can get details with the ConnectionError property:
                Debug.WriteLine($"Can't connect to the network, error: {WifiNetworkHelper.Status}");
                NeopixelOrange();
                if (WifiNetworkHelper.HelperException != null)
                {
                    Debug.WriteLine($"ex: {WifiNetworkHelper.HelperException}");
                }
            }
            else
            {
                // Otherwise, you are connected and have a valid IP and date
                Debug.WriteLine("We're in! Wifi connected. Just to make sure. Wifi is REALLY connected.");
                NeopixelThread();
            }

            // setup user button
            _userButton = new GpioController().OpenPin(39, PinMode.Input);
            _userButton.ValueChanged += _userButton_ValueChanged;

            // setup radar
            RadarLoop();

            // Keep the main thread from exiting to ensure program continues running
            Thread.Sleep(Timeout.Infinite);

        }

        static void RadarLoop()
        {
            _radarDetect = new GpioController().OpenPin(19, PinMode.Input);

            while (true)
            {
                // Read the sensor state
                PinValue sensorValue = _radarDetect.Read();
                if (sensorValue == PinValue.High)
                {
                    // Radar detected a human body
                    Console.WriteLine("Human body detected");

                    if (firstTime || isLedstripOn == false)
                    {
                        SendPOSTWLED(true);
                        NeopixelGreen();
                        isLedstripOn = true;
                        firstTime = false;
                    }
                }
                else
                {
                    // Radar did not detect a human body
                    Console.WriteLine("No human body detected");

                    if (firstTime || isLedstripOn == true)
                    {
                        SendPOSTWLED(false);
                        NeopixelRed();
                        isLedstripOn = false;
                        firstTime = false;
                    }
                }

                Thread.Sleep(1000); // Wait for 1 second before the next read
            }
        }

        private static void _radarDetect_ValueChanged(object sender, PinValueChangedEventArgs e)
        {
            //This triggers too often. Switch to timed checks instead.
            //if (e.ChangeType == PinEventTypes.Falling)
            //{
                //Debug.WriteLine("R");
                //NeopixelRed();
            //}
        }

        private static void NeopixelThread()
        {
            ColorWipe(neoPixel, Color.White, 1);
            Thread.Sleep(500);
            NeopixelOff();
        }

        private static void NeopixelRed()
        {
            ColorWipe(neoPixel, Color.Red, 1);
            Thread.Sleep(500);
            NeopixelOff();
        }

        private static void NeopixelOrange()
        {
            ColorWipe(neoPixel, Color.Yellow, 1);
            Thread.Sleep(500);
            NeopixelOff();
        }

        private static void NeopixelGreen()
        {
            ColorWipe(neoPixel, Color.Green, 1);
            Thread.Sleep(500);
            NeopixelOff();
        }
        private static void NeopixelOff()
        {
            ColorWipe(neoPixel, Color.Black, 1);
            Thread.Sleep(500);
        }

        static void ColorWipe(Ws28xx neo, Color color, int count)
        {
            BitmapImage img = neo.Image;
            for (var i = 0; i < count; i++)
            {
                img.SetPixel(i, 0, color);
                neo.Update();
            }
        }

        private static void _userButton_ValueChanged(object sender, PinValueChangedEventArgs e)
        {
            if (e.ChangeType == PinEventTypes.Falling && isChangingLEDStrip == false)
            {
                isLedstripOn = !isLedstripOn;

                // signal event
                Debug.WriteLine("About to send message");
                sendMessage.Set();

                if (IS_RADAR_VERSION)
                {
                    SendPresetToWLED();

                }
                else
                {
                    SendPOSTWLED(isLedstripOn);
                }
                Debug.WriteLine("Sent message");
            }
        }

        static void SendPresetToWLED()
        {
            _httpClient = new HttpClient();
            StringContent content;
            content = new StringContent(str_WLEDON);
           
            _httpClient.BaseAddress = new Uri($"http://192.168.178.82/json/state/");

            try
            {
                var response = _httpClient.Post("", content);
                response.EnsureSuccessStatusCode();
                _httpClient.Dispose();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }

        static void SendPOSTWLED(bool isWledOn)
        {
            _httpClient = new HttpClient();
            StringContent content;
            if (!isWledOn)
            {
                content = new StringContent(str_WLED_PRESETONE);

            }
            else
            {
                content = new StringContent(str_WLED_PRESETTWO);
            }

            _httpClient.BaseAddress = new Uri($"http://192.168.178.82/json/state/");

            try
            {
                var response = _httpClient.Post("", content);
                response.EnsureSuccessStatusCode();
                _httpClient.Dispose();
                response.Dispose();
            }
            catch (Exception e)
            {
                Debug.WriteLine("CAUGHT ERROR");
                Debug.WriteLine(e.Message);
                NeopixelOrange();
                Power.RebootDevice();
            }
        }
    }
}

Credits

GadgetGamesAU

GadgetGamesAU

1 project • 0 followers

Comments