Created
July 12, 2025 17:03
-
-
Save lolwuz/556a7fcf31ac25270680fa3ee4d3ad3c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <ESP8266WiFi.h> | |
| #include <OneWire.h> | |
| #include <DallasTemperature.h> | |
| #include <ArduinoHA.h> | |
| const char* mqttHost = "homeassistant.local"; | |
| const char* ssid = ""; | |
| const char* password = ""; | |
| const char* mqttUser = ""; | |
| const char* mqttPass = ""; | |
| byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A}; | |
| #define ONE_WIRE_BUS 4 // DS18B20 on GPIO4 (D2) | |
| #define PHOTO_PIN A0 // photo-resistor voltage divider on ADC0 | |
| OneWire oneWire(ONE_WIRE_BUS); | |
| DallasTemperature sensors(&oneWire); | |
| HADevice device(mac, sizeof(mac)); | |
| WiFiClient wifiClient; | |
| HAMqtt mqtt(wifiClient, device); | |
| HASensorNumber ambientTemp("ambient_temp", HASensorNumber::PrecisionP2); | |
| HASensorNumber lightLevel ("light_lvl", HASensorNumber::PrecisionP0); | |
| void setup() { | |
| Serial.begin(9600); | |
| sensors.begin(); | |
| WiFi.begin(ssid, password); | |
| while (WiFi.status() != WL_CONNECTED) { delay(500); } | |
| device.setName("TempLightController"); // rename if you like | |
| ambientTemp.setUnitOfMeasurement("°C"); | |
| lightLevel .setUnitOfMeasurement("%"); | |
| ambientTemp. | |
| mqtt.begin(mqttHost, 1883, mqttUser, mqttPass); | |
| } | |
| void loop() { | |
| mqtt.loop(); | |
| static uint32_t last = 0; | |
| if (millis() - last > 5000) { // every 5 s | |
| last = millis(); | |
| /* --- ambient temperature --- */ | |
| sensors.requestTemperatures(); | |
| float tempC = sensors.getTempCByIndex(0); | |
| ambientTemp.setValue(tempC); | |
| Serial.print("Temp °C: "); | |
| Serial.println(tempC); | |
| /* --- light level --- */ | |
| int raw = analogRead(PHOTO_PIN); // 0–1023 | |
| float pct = (raw / 1023.0) * 100.0; // 0–100 % | |
| lightLevel.setValue(pct); | |
| Serial.print("Light %: "); | |
| Serial.println(pct); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment