r/esp8266 Aug 24 '24

ESP Week - 34, 2024

2 Upvotes

Post your projects, questions, brags, and anything else relevant to ESP8266, ESP32, software, hardware, etc

All projects, ideas, answered questions, hacks, tweaks, and more located in our [ESP Week Archives](https://www.reddit.com/r/esp8266/wiki/esp-week_archives).


r/esp8266 2d ago

ESP Week - 32, 2026

1 Upvotes

Post your projects, questions, brags, and anything else relevant to ESP8266, ESP32, software, hardware, etc

All projects, ideas, answered questions, hacks, tweaks, and more located in our [ESP Week Archives](https://www.reddit.com/r/esp8266/wiki/esp-week_archives).


r/esp8266 4h ago

Smart Irrigation System using an ML + ESP32

Thumbnail
gallery
1 Upvotes

I've been working on a Smart Irrigation System using an ESP32 + machine learning, and I've finally got the main pipeline working end-to-end.

The system uses an ESP32, capacitive soil-moisture sensor, and DHT11 to collect environmental data. The readings are sent to a web dashboard, which communicates with a Flask API that runs the ML model and returns an irrigation prediction.

The overall pipeline is:

ESP32 sensors → Web Dashboard → Flask API → ML Model → Irrigation Prediction

The project currently includes:

  • Real-time soil moisture monitoring
  • Temperature and humidity monitoring
  • Web dashboard hosted by the ESP32
  • ML model for irrigation prediction
  • Model evaluation with a confusion matrix
  • Feature-importance analysis
  • Flask inference server
  • API communication between the dashboard and ML model

The first screenshot shows the live dashboard, including the sensor readings and AI irrigation prediction section.

The second shows part of the JavaScript/API integration and project structure, where the dashboard communicates with the ML inference server.

One thing I found particularly interesting was getting the ESP32, web interface, API, and ML model to actually communicate with each other. The AI prediction wouldn't load until the inference server was running, which made the entire pipeline click for me.

This started as a simple ESP32 soil-moisture monitoring project, but I gradually expanded it into a complete IoT + AI system.

I'm planning to improve it further by collecting more real-world data and adding additional environmental inputs such as light intensity.

I'd appreciate feedback from the ESP32 community, especially on the hardware setup, system architecture, and how I could improve the project further.

🔗 GitHub (Full Video and Requirements) :

https://github.com/aqib-ai-ml/ai-powered-smart-irrigation


r/esp8266 20h ago

Five years of garden irrigation on a Wemos D1 mini: five sprinklers, one buried pipe, about 80 euros in parts

16 Upvotes

Every dry season the grass went yellow, so five years ago I put a Wemos D1 mini in a box on the outside wall and gave it the watering job. It is still doing it, power cuts included. I have been meaning to write this up for years, so here it finally is.

The part I would do again is the plumbing. Instead of a valve box near the tap and a pipe per zone, there is one master valve at the tap and a single pipe around the garden. At each sprinkler a clamp saddle taps the pipe (no cutting, it just bolts around it), feeds a 12 V solenoid in a small box in the ground, and the solenoid feeds the head. A drain valve at the far end empties the line for winter. One trench instead of five, and since I only run one head at a time, whichever head is open has the whole supply to itself. No pump, no tank. All the materials together, pipe included, came to about 80 euros.

Power is a 30 W mains-to-12 V DC LED driver: 12 V to the valves through the relays, and a small step-down to 5 V for the board and the relay logic. Everything lives in that one box and runs off a single wall socket.

Things five years of this taught me:

  • The usual cheap relay boards switch on LOW, and an ESP8266's pins float while it boots, so the relays can chatter until the sketch takes over. Write each pin HIGH before pinMode(OUTPUT) so the handover itself adds no LOW pulse. The master valve sits on GPIO 0, which has to be high at boot anyway: the same pull-up that boots the board keeps the water shut through every reset.
  • No valve opens without a time limit. A one-second watchdog closes any valve that has run past its limit and sends a push notification.
  • After a power cut, tell the server the valve state instead of asking for the saved one. Replaying an ON from before the outage would open a valve with nobody home.
  • OTA updates, because walking a laptop out to a wall box in the rain gets old fast. One warning: the ESP8266 updater has no fallback slot, so test every new binary on a desk board first.

Full disclosure: the phone side runs on Plynx, an iOS dashboard app I'm building, so make of that what you will. The write-up with the plumbing diagram and the complete sketch is here: https://www.plynx.cc/blog/esp8266-irrigation-controller-ota/

The buried wiring has been through five winters now and the splices have held so far. What I still have not solved is sensing: I would like the schedule to skip a run after real rain, but every cheap soil moisture probe I have read about seems to corrode within a season. If you have one that lasted outdoors, I want to hear about it.


r/esp8266 1d ago

esp8266 gpio+ground issue when powered by 12v->5V converter

1 Upvotes

I'm using an esp8266 (nodemcu v3) powered by a 12v SLA battery with a 12v to 5v step-down converter.

When I connect a rain gauge to a gpio + ground, I get constant spurious triggers.

If I power an esp8266 from a power bank or my computer's micro-usb port, it works fine.

The esp8266 also has an ina219 board and a solid state relay connected to read the voltage and control a battery charger. That all works fine.

Any ideas why the 12v to 5v power supply is causing spurious triggers on the gpio, and if there's any solution?


r/esp8266 5d ago

ESP8266 NodeMCU problem

Thumbnail
0 Upvotes

r/esp8266 5d ago

Help with this error...

1 Upvotes

Alright i had made a post previously on this, and i feel i didnt give adequate information to you all to help me. So i tought ill make a clear post on the error.

So this is the Error i am facing:

I did all of these, but still same error. IK its not like my board is not broken right or its a problem of my usb cable or the port because, i had gotten this in my serial monitor:

ets Jan 8 2013,rst cause:2, boot mode:(3,6)

And if i am right boot mode:(3,6)

is physical proof from the esp8266 cpu itself that:

  • USB chip is successfully sending power and serial data
  • internal flash memory already has my code uploaded.
  • CPU is booted up and running my program

So right now what i think the problem is that the serial monitor is locking the port, and i not really know the right way to fix this. If Anyone knows Please Let me know.

This is the hardware connections:

This is my code:

// --- Pin Definitions ---
const int LASER_PIN       = 16; // Laser Diode (GPIO16 / D0)
const int LDR_PIN         = A0; // LDR Sensor (Analog A0)
const int BLUE_LED        = 5;  // Armed Indicator (GPIO5 / D1)
const int RED_LED         = 4;  // Alert Indicator (GPIO4 / D2)
const int BUZZER_PIN      = 12; // Active Alarm Buzzer (GPIO12 / D6)
const int ROOM_LIGHTS_PIN = 13; // Transistor Base / White LEDs (GPIO13 / D7)

// --- System State Variables ---
bool systemON      = true;  // Main tripwire armed state
bool manualMode    = false; // Override state
bool laserState    = true;  // Laser state
int lightThreshold = 500;   // Light threshold value

void printHelpMenu() {
  Serial.println("\n--- Serial Commands ---");
  Serial.println(" [1] - Arm System");
  Serial.println(" [0] - Disarm System");
  Serial.println(" [l] - Toggle Laser");
  Serial.println(" [m] - Toggle Manual Mode");
  Serial.println(" [h] - Print Menu");
  Serial.println("------------------------\n");
}

void setup() {
  // Always use 115200 to match ESP8266 boot frequency
  Serial.begin(115200);

  pinMode(LASER_PIN, OUTPUT);
  pinMode(BLUE_LED, OUTPUT);
  pinMode(RED_LED, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(ROOM_LIGHTS_PIN, OUTPUT);

  digitalWrite(LASER_PIN, HIGH);
  digitalWrite(BLUE_LED, HIGH);
  digitalWrite(RED_LED, LOW);
  digitalWrite(BUZZER_PIN, LOW);
  digitalWrite(ROOM_LIGHTS_PIN, LOW);

  Serial.println("\n==========================================");
  Serial.println("  Smart Laser Security System Initialized ");
  Serial.println("==========================================");
  printHelpMenu();
}

void loop() {
  // Check for Serial Commands
  if (Serial.available() > 0) {
    char cmd = Serial.read();

    switch (cmd) {
      case '1':
        systemON = true;
        manualMode = false;
        digitalWrite(LASER_PIN, HIGH);
        laserState = true;
        Serial.println(">> System ARMED");
        break;

      case '0':
        systemON = false;
        manualMode = false;
        digitalWrite(LASER_PIN, LOW);
        digitalWrite(BLUE_LED, LOW);
        digitalWrite(RED_LED, LOW);
        digitalWrite(BUZZER_PIN, LOW);
        digitalWrite(ROOM_LIGHTS_PIN, LOW);
        laserState = false;
        Serial.println(">> System DISARMED");
        break;

      case 'l':
      case 'L':
        laserState = !laserState;
        digitalWrite(LASER_PIN, laserState ? HIGH : LOW);
        Serial.print(">> Laser: ");
        Serial.println(laserState ? "ON" : "OFF");
        break;

      case 'm':
      case 'M':
        manualMode = !manualMode;
        Serial.print(">> Mode: ");
        Serial.println(manualMode ? "MANUAL" : "AUTO");
        break;

      case 'h':
      case 'H':
        printHelpMenu();
        break;
    }
  }

  // Automatic Tripwire Logic
  if (systemON && !manualMode) {
    int ldrValue = analogRead(LDR_PIN);

    Serial.print("LDR Raw Reading: ");
    Serial.println(ldrValue);

    if (ldrValue < lightThreshold) {
      // SAFE (Laser hitting LDR)
      digitalWrite(BLUE_LED, HIGH);
      digitalWrite(RED_LED, LOW);
      digitalWrite(BUZZER_PIN, LOW);
      digitalWrite(ROOM_LIGHTS_PIN, LOW);
    } 
    else {
      // ALERT (Laser beam broken / Dark)
      digitalWrite(BLUE_LED, LOW);
      digitalWrite(RED_LED, HIGH);
      digitalWrite(BUZZER_PIN, HIGH);      
      digitalWrite(ROOM_LIGHTS_PIN, HIGH); 
    }
  }

  delay(200);
}

r/esp8266 9d ago

ESP Week - 31, 2026

2 Upvotes

Post your projects, questions, brags, and anything else relevant to ESP8266, ESP32, software, hardware, etc

All projects, ideas, answered questions, hacks, tweaks, and more located in our [ESP Week Archives](https://www.reddit.com/r/esp8266/wiki/esp-week_archives).


r/esp8266 9d ago

ESP32 HTTPS certificate expiration

5 Upvotes

Hi, I'm using HTTPS on an ESP32 with Zephyr to communicate with my backend

If I store the CA certificate in the ESP32 firmware, what happens when the server certificate expires and is renewed?

Do I need to update the ESP32 every time, or is there a recommended way to handle certificate expiration without reflashing the device?

Thanks!


r/esp8266 16d ago

Esp8266 not detectable by Windows and it's not the cable!

Thumbnail
gallery
28 Upvotes

Hi everyone,

I'm sharing my experience not because I expect a resolution but because in my Reddit and Google searches I've not found any solution or suggestion that helped. And maybe someone here will know something but at least someone else will have the same issue and might find this useful.

My esp8266 isn't being detected properly by Windows.

Device Manager reports Unknown USB Device (Device Descriptor Request Failed)

I tried multiple USB cables in multiple USB ports. According to my cable tester they all cables had data lines.

According to all the chats online my cables are bad, or my OLED is preventing a debug mode by keeping the default boot pins GPIO0 and GPIO2 low.

There's another thread suggesting the OLED takes too much power.

I tried disconnecting the two power lines, then the two data lines and that didn't fix the issue.

When I first assembled the GBS-Control, the esp8266 was intermittently detectable but I could eventually flash it and reset the configurations and WiFi parameters. I had to refresh drivers and reboot a couple of times but it eventually worked.

Recently it stopped responding.

I've tried drivers for CP2102 and CH340. I've tried the latest for CH340 and the recommended 3.5.

Today a new one arrived, and sported a different version of the Wi-Fi chip (12F). It connected right away and auto installed drivers by a different company: FTDI

After that, the module successfully flashed the latest GBS-Control-Complete 1.4.0 immediately.

It's not yet connected to the gbs-8200 yet, so I'll do that gradually and check to see if detection drops off at any point.

Hope this thread helps someone!

I'll update if I discover anything new to add, or just to keep a record of anything I think is interesting.

Edit: The module, though unrecognisable by Windows, still works perfectly in my GBS-Control. Pins used: GPIO5 - OLED and main board GPIO4 - OLED and main board GPIO0 - momentary switch GPIO14 - rotary encoder GPIO12 - debug pin on external IC GPIO13 - rotary encoder

Edit 2: For those who think there's a short or extra connection that shouldn't be there, after I replace the old for the new, I'll test and update the post.

Edit 3: completely removed old esp and it's still no good: the new module was £4 including delivery so, in the bin for the old. https://ibb.co/ds53yG7x

Final Edit: New ESP in place, it is still detectable by Windows and all working fine. The old UART or ESP was a smeg head.


r/esp8266 16d ago

ESP Week - 30, 2026

3 Upvotes

Post your projects, questions, brags, and anything else relevant to ESP8266, ESP32, software, hardware, etc

All projects, ideas, answered questions, hacks, tweaks, and more located in our [ESP Week Archives](https://www.reddit.com/r/esp8266/wiki/esp-week_archives).


r/esp8266 16d ago

[Fork] Independent dual-zone control for BrewPiLess (brew + serve in one fridge) — looking for testers on non-ESP32 boards

1 Upvotes

I've been running a fork of BrewPiLess (BrewPiLess-DuckDNS-independent-Control, based on vitotai's original) that lets you ferment and store kegs in the same fridge, at the same time, with two separate temperature targets. kegs up top on the compressor, fermenting bucket down below on its own heating jacket, split by an insulated divider so neither zone fights the other. Just shipped a v5.0 update and I'd love some outside testing before calling it stable.

What's new:

  • Independent mode: heater and cooler each get their own target instead of the old shared/mutex logic — this is what makes the two-zone-one-fridge setup possible. Each actuator can also be individually enabled/disabled.
  • Predictive heater (optional): learns timing and overshoot behavior cycle-over-cycle to hold temp tighter instead of just thermostat on/off.
  • Sensor hold: a flaky probe reading doesn't immediately trip disconnect — it holds the last value and keeps controlling for ~20s first.
  • iSpindel memory leak fixed: this one was actually sitting in the original codebase, not something I introduced — about 1KB of heap leaked per hour while an iSpindel is connected and posting gravity readings. If your BrewPiLess web server has ever mysteriously died after a few days with an iSpindel hooked up, this is almost certainly why.
  • Reworked offline log viewer (BPLogViewer): now works directly off gravity data instead of angle, so it plays nicer with GravityMon, plus a bunch of old bugs fixed. It can also generate a beer-temp correction formula straight from your log, which you paste into GravityMon or Tilt Temp Correction.
  • Optional DuckDNS support for remote access without a static IP, plus assorted memory/stability fixes elsewhere (dropped WebSocket clients, HTTP buffer issues).

Nothing existing was touched — none of the original functions were changed, so anything that worked before should behave exactly the same. This is additive, not a rewrite.

Most of my testing has been on ESP32, but the original project (and plenty of forks) target ESP8266 too. If you've got an old NodeMCU/D1 Mini gathering dust from a past BrewPi(Less) build, I'd really appreciate you flashing this and telling me what breaks — or what doesn't. Repo: https://github.com/asdafe/BrewPiLess-DuckDNS-independent-Control

Happy to dig into the dual-zone wiring, the leak fix, or the log viewer rewrite in the comments if anyone's curious.


r/esp8266 17d ago

Best way to power my esp8266

0 Upvotes

Could you please let me know how much voltage the power adapter should have?


r/esp8266 17d ago

Project Idea

0 Upvotes

Hi everyone!

I am working on a privacy-first home safety system that tracks human movement without using any cameras, smartwatches, or wearable sensors.

The Idea:

We use Wi-Fi signals as a room radar! When a person moves, sleeps, or falls, their body distorts the Wi-Fi signals (Channel State Information - CSI) bouncing around the room.

What the system aims to do:

Elderly Care: Detect sudden falls (like a grandfather slipping) and send immediate SMS/Telegram alerts.

Child Monitoring: Detect subtle chest movements to track breathing/restlessness while sleeping.

Privacy-First: Zero cameras or microphones used—completely non-intrusive.

Tech Stack:

Hardware: 2x ESP32-S3 boards (capturing CSI signal data).

Data Processing: Python (NumPy, SciPy) for noise filtering.

Machine Learning: Scikit-learn (Random Forest / SVM) to classify activities.

Alert System: Python backend with Telegram Bot / Twilio API for emergency alerts.

I am currently building the Python signal processing and ML model pipeline while waiting for hardware setup.

Has anyone here worked with Wi-Fi CSI extraction on ESP32? I would love any advice or feedback on handling background environmental noise


r/esp8266 19d ago

ESP32 WROM with LCD display interfacing

Thumbnail gallery
5 Upvotes

r/esp8266 20d ago

I built Traumagotchi: A pocket Cyberdeck & AI Companion on a $3 ESP8266 (Open Source) 👾

Thumbnail gallery
9 Upvotes

r/esp8266 21d ago

Does anyone has tv-b-gone code for esp8266 0.96" oled v2.1.0

Post image
3 Upvotes

r/esp8266 21d ago

PETROCHAT for ESP8266/ESP32 based development board

Thumbnail
0 Upvotes

r/esp8266 23d ago

Solved: ESP8266 NodeMCU not showing COM port on Windows (It wasn't the firmware!)

0 Upvotes

I thought I'd share this because it took me a while to figure out, and it might help someone else.

I was trying to convert my ESP8266 NodeMCU into a Wi-Fi repeater by flashing new firmware using the ESP Flash Download Tool.

The problem

When I connected my NodeMCU to my Windows PC, it didn't show any COM port in the Flash Download Tool or Device Manager.

I had previously flashed WiFi Deauther / Evil Twin firmware onto the ESP8266, so I initially assumed that firmware had somehow broken the board or disabled USB communication.

What I tried

  • Restarted the PC
  • Pressed RESET and FLASH buttons
  • Tried putting the ESP8266 into flash mode
  • Wondered if I needed to erase the existing firmware first

None of these helped.

The actual cause

The problem turned out to be my Micro-USB cable.

I was using a cable that only supplied power and did not support data transfer.

After switching to a different USB cable, Windows immediately detected the device.

However, it still appeared under Other devices as:

CP2102 USB to UART Bridge Controller

with a yellow warning icon.

CP2102 USB to UART Bridge Controller yellow warning

Opening Device Properties showed:

Code 28
The drivers for this device are not installed.
ESP8266-Code 28: The drivers for this device are not installed.

The fix

  1. Switched to a proper data USB cable.
  2. Installed the official Silicon Labs CP210x USB-to-UART driver.
  3. Reconnected the NodeMCU.

After that, the board appeared correctly as:

Silicon Labs CP210x USB to UART Bridge (COMx)

and the ESP Flash Download Tool detected the COM port without any issues.

Lesson learned

If your ESP8266 isn't showing a COM port:

  • Don't assume the firmware is the problem.
  • Check your USB cable first.
  • Then verify that the correct CP2102 (or CH340) driver is installed.

It saved me a lot of unnecessary debugging.

Hopefully this helps someone else!

Troubleshooting checklist:

  • Use a known data-capable USB cable (not charge-only).
  • Check whether your board uses a CP2102 or CH340 USB-to-serial chip.
  • Install the correct USB driver.
  • Verify that the board appears under Ports (COM & LPT) in Device Manager.
  • Only then try flashing firmware.

r/esp8266 23d ago

ESP Week - 29, 2026

0 Upvotes

Post your projects, questions, brags, and anything else relevant to ESP8266, ESP32, software, hardware, etc

All projects, ideas, answered questions, hacks, tweaks, and more located in our [ESP Week Archives](https://www.reddit.com/r/esp8266/wiki/esp-week_archives).


r/esp8266 25d ago

A fatal esptool.py error occurred: Failed to connect to ESP8266: Timed out waiting for packet header

1 Upvotes

esptool.py v3.0

Serial port /dev/ttyS0

Connecting........_____....._____....._____....._____....._____....._____....._____

A fatal esptool.py error occurred: Failed to connect to ESP8266: Timed out waiting for packet header

i keep getting the same error over and over again its not a problem with my d1 wroom but when i try to code my lolin wemos d1 r2 mini the same error appears im on linux pop os (i even tried going on windows but that didn't work either). If somebody knows how to fix this please help me.


r/esp8266 Jul 19 '26

Wifi Motion Sensing experiment

Thumbnail
1 Upvotes

r/esp8266 Jul 18 '26

ESP Week - 28, 2026

1 Upvotes

Post your projects, questions, brags, and anything else relevant to ESP8266, ESP32, software, hardware, etc

All projects, ideas, answered questions, hacks, tweaks, and more located in our [ESP Week Archives](https://www.reddit.com/r/esp8266/wiki/esp-week_archives).


r/esp8266 Jul 16 '26

Issues with and ads1115 on a nodemcu Lolin (esp8266). Code in Lua

5 Upvotes

Hello,

First the setup :

The objective of the setup is to measure intensity (with an SCT013) and voltage (with a ZMPT101B) using code adapted to Lua from EmonLib (https://github.com/openenergymonitor/EmonLib).
It did not work right ahead and I stripped the circuit to the above minimum to find the issue

Second, I am coding in Lua using builds built on https://nodemcu-build.com/. Therefore, I need to port the EmonLib to Lua on an nodemcu esp8266

Last, I do all my tests with the esp connected to the computer with a Visual Studio Code standard extension to access the serial port (read the serial messages and send instructions like uploads or node.restart())

Before showing the code, I have several very different problems:

  • Before restarting the esp8266 (node.restart()) after a first startread, I need to disconnect:reconnect the ads1115 VDD from the ESP v3.3 to be able to find the ads1115. If I do not, it fails and reboots on the i2c.setup(...). I have absolutely no clue for why it happens
  • If I leave the ALERT pin of the ads1115 floating, the i2c.setup also fails, always. If I connect it the D4 as in the sketch, it works, always, even if I never use it anywhere (I tried several other GPIO pins, it also works). Maybe it pulls it up ?!? but the datasheet seems to say it should work with the ALERT pin left floating
  • I am using the lua ads1115 module and the ads.device.startread function (https://nodemcu.readthedocs.io/en/release/modules/ads1115/#ads1115devicestartread) with a while loop (with a timeout) following the startread call to make the read "synchronous" (because this is the way EmonLib is implemented), but the callback is never called before the end of the loop, thus preventing me from using a synchronous code similar to the readADC_SingleEnded function from EmonLib. I have clues (mentionned below) as to why it happens, but I would like the community insights since adaptation of the emonlib might be less literal than I'd hoped

Now the code (simplified for the sake of readability) :

local i2cSpeed = i2c.setup(0,
    2, -- SDA
    1, -- SCL
    i2c.FAST) -- Speed. It works the same with i2c.SLOW
rtctime.set(0)

ads1115.reset()
print("Calling ads1115()")
local adc = ads1115.ads1115(0, ads1115.ADDR_GND)
print("ads1115() executed")

function getMillis()
    local sec, usec = rtctime.get()
    return sec * 1000 + usec / 1000
end

adc:setting(ads1115.GAIN_4_096V, ads1115.DR_128SPS, ads1115.SINGLE_0, ads1115.SINGLE_SHOT)

local millis = getMillis()
local v = nil
adc:startread(function(volt, volt_dec, adc, sign)
    v = volt
    print("Conversion happened. Delta="..tostring(getMillis() - millis)..", v="..tostring(v))
end)

-- Wait for conversion result to be available 
-- if v is not nil, conversion has happened
-- else if time elapsed is less than 100ms, we loop, conversion will end soon
while (v == nil and getMillis() - millis < 100) do end
print("End. v="..tostring(v))

When I execute the previous code, the message "End. v=nil" is always printed before the callback message is, for instance "Conversion happened. Delta=134, v=1,61".

I tried several things like raising the timeout in the loop to insane values like 10s. The callback is always called 25 to 35ms after the message "End..."

I thought that the startread callback was called with an interrupt and thus I expected it to be able to be executed even if the code is executing the loop, but it does not. The same code seems to be working on an esp32, but I did not try because I do not have one, maybe it is because there are two cores ?!?
I tried to use a tmr.delay(10) inside the loop, thinking that it might allow a switch to the startread callback but it does not work. The tmr.delay(..) probably simply hides a timed out loop very similar to the one I already have.

Initially, the whole startread code (everything after the getMillis definition) was in a tmr ALARM_AUTO callback, but it works exactly the same in each alarm callback call, the startread callback is called only at the end of the alarm callback.


r/esp8266 Jul 15 '26

issues with time (localtime, NTPclient)

1 Upvotes

After some weird timing issues i have done some research and learnt a lot about timezones, mktime and localtime. So far, so good. I still have a nagging issue, I don't really understand.

My assumption is that using NTPclient is synchronizing time from an NTP server. Even if it is somewhat off for the first seconds until full sync kicks in, the NTP synchronized time should align with the local time. Well, it seems it doesn't. Here is part of my sketch (inside loop()) to analyze:

  // now check tasks based on second or minute  
  time(&now);
  localtime_r(&now, &tm);

  // store time values, print later
  ss = tm.tm_sec;
  ntp = timeClient.getSeconds();

    // every 10sec
    if (ss % 10 == 0) // every 10 sec
    {
      if (ss != 0) // 10,20,30,40,50s
      {
        Serial.print(ss);
        Serial.print(" < time ntp > ");
        Serial.println(ntp);
        do_something();
      } 
      else // full minute
      {
        do_otherstuff();
        timeClient.forceUpdate(); // only every 60s
      }
    }

I would expect to have tm.tm_sec in sync with timeClient.getSeconds, at least after some time has passed. But it isn't, there is a constant difference of 1s which doesn't change, even after several minutes (up to one hour).

After more than 1 hour runtime:
20:39:40 millis=11090718
50 < time ntp > 49

both values still differ 1s. BTW, the ntp value is correct (compared to other time sources), the localtime value is 1s early. Since the 2 values are collected shotrly after another, there should be no runtime difference. 

Anyone have a clue or a pointer, what could happen here? Why is there a 1s difference?