Example code for esp32c6 wifi sensor in HA?

Bought my first esp32 (a c6), got IDF set up, blink works and I’ve also tested Rainmaker, but aiming for a simple wifi sensor on my own network (without the cloud).

Is there a sample project I can start from? A sensor that’s detected by HA and then I can add more code from there? Happy to dust off my old C knowledge.

Eventual goal is to monitor two limit switches in a motor, but I need to take some baby steps first. Any help is much appreciated.

PS: I know a c6 can also be a Zigbee client, but I’m strictly limited to either wifi or Zigbee-via-Aqara-M100-hub, and as far as I can tell Aqara doesn’t accept non-Aqara Zigbee clients, so wifi it is.

Have you looked at the docs?

this maybe what you need but not sure from what you are asking.

1 Like

Well that’s rather embarrassing. I totally expected ESPHome to be the next step once I got the sensor working - I never knew it to be a “one stop shop” / complete sensor-build-flash-deploy platform.

One problem seems to be though is that it’s unlikely to let me write my own code? Not sure some lines of YAML will let me build a sensor that will monitor two separate limit switches + change LED colours, etc.

Have you looked at the doc?

Lambdas are C++ code

1 Like

Esphome will do your project easily, check out some of the voice projects to see what you can do with a few lines of yaml.

You can go basic and create ESPHome binary sensors for each limit switch and do your automation in Home Assistant. Or you can create the finished product directly on ESPHome and expose whatever hihglevel entities directly on Home Assistant, bypassing the part where you monitor and emit the monitoring data for every limit switch. It’s your call. But yes a few lines of YAML.

1 Like

Appreciate the replies.

My esp32-c6 was misbehaving and while troubleshooting via Arduino I managed to get a working example including the RGB LED control I was after (thanks to hmueller01).

/*  Evolved from https://github.com/hmueller01/pubsubclient3 (+ a few other examples).
 Basic ESP32 MQTT client:
 - Connects to configured MQTT server and publishes "hello world" to topic "outTopic" every two seconds
 - Subscribes to "inTopic", printing out any messages received; If first char of "inTopic" message is 1, ESP LED is switched on, else it is switched off
 - Reconnects if connection drops.

 Uses onboard RGB LED to indicate status:
 - white   initial bootup (solid)
 - magenta attempting to connect via wifi 
 - blue    wifi connection established
 - red     unable to connect to MQTT server
 - green   connected to MQTT server
 - yellow  message received (brief flash, dim)
 - white   message sent (brief flash, dim)
 - white   user requested LED be turned on (extended BRIGHT flash)
*/
/******************** CONFIG **********************/
constexpr const char* WIFI_SSID     = "mywifi";
constexpr const char* WIFI_PASSWORD = "wifipass";
constexpr const char* MQTT_SERVER   = "broker.mqtt-dashboard.com";
constexpr const char* MQTT_USER     = "muser";
constexpr const char* MQTT_PASSWORD = "mpass;
constexpr uint8_t     LED_PIN       = 8;
constexpr int         MQTT_PORT     = 1883;

/**************** CONSTANTS, ET AL ****************/
#ifdef ESP8266
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#include <esp_random.h>
#define RANDOM_REG32 esp_random()
#else
#error Platform not supported.
#endif
#include <PubSubClient.h>
#include <Adafruit_NeoPixel.h>

Adafruit_NeoPixel rgbLed(1, LED_PIN, NEO_GRB + NEO_KHZ800);
struct RGB {
    uint8_t r, g, b;
};
constexpr RGB COLOR_OFF    = {  0,   0,   0};
constexpr RGB RGB_MAGENTA  = {255,   0, 255}; 
constexpr RGB RGB_YELLOW   = {255, 255,   0}; 
constexpr RGB RGB_RED      = {255,   0,   0}; 
constexpr RGB RGB_GREEN    = {  0, 255,   0}; 
constexpr RGB RGB_BLUE     = {  0,   0, 255}; 
constexpr RGB RGB_WHITE10  = { 25,  25,  25}; 
constexpr RGB RGB_WHITE100 = {255, 255, 255}; 
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE	(50)
char msg[MSG_BUFFER_SIZE];
int value = 0;                                              // MQTT message counter

/******************* FUNCTIONS ********************/
void LEDsetColor(const RGB& color, uint8_t brightness = 100) {
    uint16_t scale = (uint16_t)brightness * 255 / 100;
    uint8_t r = (uint8_t)(((uint16_t)color.r * scale) / 255);
    uint8_t g = (uint8_t)(((uint16_t)color.g * scale) / 255);
    uint8_t b = (uint8_t)(((uint16_t)color.b * scale) / 255);
    rgbLed.setPixelColor(0, rgbLed.Color(r, g, b));
    rgbLed.show();
}

void setup_wifi() {
    LEDsetColor(RGB_MAGENTA, 15);     
    Serial.print("WiFi: Connecting to ");
    Serial.println(WIFI_SSID);
    
    WiFi.mode(WIFI_STA);
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    LEDsetColor(RGB_BLUE, 15);        
    randomSeed(RANDOM_REG32);
    Serial.println("WiFi connected");
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
}

void callback(char* topic, uint8_t* payload, size_t plength) {
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (size_t i = 0; i < plength; i++) {
        Serial.print((char)payload[i]);
    }
    Serial.println();

    if ((char)payload[0] == '1') {                          // Switch on LED if payload first character is '1'
        Serial.println("Detected LED trigger");
        LEDsetColor(RGB_WHITE100, 100);
        delay(1500);
    } else {
        LEDsetColor(RGB_YELLOW, 1);
        delay(1000);
        LEDsetColor(COLOR_OFF);
    }
}

void reconnect() {
    while (!client.connected()) {                           // Loop until reconnected
        Serial.println("Attempting MQTT connection...");
        String clientId = "ESP32c6Client";
        clientId += String(random(0xffff), HEX);

        Serial.print("   Client ID: ");
        Serial.println(clientId);
        Serial.print("   MQTT username: ");
        Serial.println(MQTT_USER);

        if (client.connect("ESP32c6Client",MQTT_USER,MQTT_PASSWORD)) {
            LEDsetColor(RGB_GREEN, 25);
            Serial.println("Connected to MQTT broker");
            client.publish("outTopic", "hello world");
            client.subscribe("inTopic");
        } else {
            LEDsetColor(RGB_RED, 25);
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            delay(5000);                                    // Wait 5 seconds before retrying
            LEDsetColor(COLOR_OFF);
        }
    }
}

/***************** ARDUINO SETUP ******************/
void setup() {
    Serial.begin(115200);
    Serial.println("---- SYSTEM START ----");
    
    rgbLed.begin();                                         // Setup RGB LED
    rgbLed.show(); 
    LEDsetColor(RGB_WHITE10, 15);
    
    setup_wifi();
    
    client.setServer(MQTT_SERVER, 1883);
    client.setCallback(callback);
}

/****************** ARDUINO LOOP ******************/
void loop() {
    if (!client.connected()) {
        reconnect();
    }
    client.loop();

    unsigned long now = millis();
    if (now - lastMsg > 2000) {
        LEDsetColor(RGB_WHITE10, 5);
        lastMsg = now;
        ++value;
        snprintf(msg, MSG_BUFFER_SIZE, "hello world #%d", value);
        Serial.print("Publish message: ");
        Serial.println(msg);
        client.publish("outTopic", msg);
        delay(150);
    } else {
        LEDsetColor(RGB_GREEN, 1);
        delay(100);
    }
    delay(100);
}

Your issue with that is its not esphome and this forum is to discuss esphome :slight_smile:

that being said driving the onboard led is easy in esphome, you just need to add the board as a new device then edit the yaml adding this

light:
  - platform: esp32_rmt_led_strip
    chipset: WS2812
    pin: GPIO8
    num_leds: 1
    rgb_order: GRB
    name: "Onboard RGB LED"

you may need to change the gpio pin but to me it looks far easier than your sample.

1 Like

Fair point! I’m still adjusting to that. It’s been a long day.

I’ll crack on with an ESPHome example tomorrow.

I totally get your frustration.

ESPHome unfortunately lacks any kind of proper introduction with a clear narrative and an overall explanation of how everything actually fits together. The references you see in this thread, like “Have you looked at the docs?”, explain absolutely nothing. They work more like technical reference manuals for people who already understand ESPHome.

Take “Getting Started with ESPHome and Home Assistant” for example. It basically explains nothing and jumps straight into configuring YAML files, as if you’re already supposed to know the architecture, the concepts, and why things are designed the way they are.

Hopefully this will improve over time, because the project itself deserves better onboarding than this. ESPHome is an incredibly powerful solution, and it keeps getting better with every release.

The current ESPHome devs have done wonders with the entire ESPHome ecosystem and are pushing improvements at an almost unbelievable pace. Their documentation of internal enhancements and breaking changes is among the best I have seen.

2 Likes

What do you expect the " Getting Started with ESPHome and Home Assistant" page to tell you. It is a step by step guide to creating a device. If you feel it needs more information or explanation I am sure the devs would love you to help with the docs.

In my eyes though it describes the process well.

I get Laurence’s point - the subheading “Introduction to ESPHome” can be taken as an implied early explainer but can also be read a secondary step that assumes the reader is ready to get into it.

Not sure how I compare to users who visit that page, but maybe a sub heading “What is ESPhome?” might be worth writing? I’d be happy to take a stab at it if you want a fresh eyes.

Recently configuring my keyboard through a browser was an evolutionary step given decades of security paranoia that isolated browsers from any direct interaction with hardware. Completely managing an esp device is another step forward, hence my surprise.

Else maybe be a “background” page that lays out some of these basics so the “getting started” page doesn’t get crowded with explanations vs initial steps for folks ready to get their hands dirty?

The only differiencing part of ESPHome vs coding your ESP in C++ is that it is declarative (and its HA coupling capabilities).

Architecturally, the important part to understand is that it generates code.
Building the firmware is done through standard tools (platformio here).

Most of ESP C++ firmware code is the boilerplate configuration of each component (basically copy/paste), and it’s exactly what ESPHome is generating through “components”.

Arguably, that might be highlighted in the “Getting started”.

Beyond that, you ought to know what is an ESP, ofc, but the OP knows it quite well…

If new to HA a good place to find the info you need is in the cookbook. You will see a section on Esphome and many other subjects

As ever with HA most stuff is already out there, its just difficult to find sometimes.

1 Like

Learning fast but definitely wearing Learner plates in here.
Several weeks ago I thought all esp32’s were just bad Pi clones.