A functional automatic on off timer switch prototype built with ESP32, DS3231 RTC, and a relay, controlling an AC light bulb.

Build Your Own Automatic ON OFF Timer Switch: The “Devraj Lab” Edition (ESP32 + WiFi)

I hate mechanical timer switches.

There, I said it.

I spent years working as an embedded systems engineer, often installing those cheap, plastic analog dials for clients. They needed a simple automatic timer switch for water pump control or to manage their shop’s street lights.

The promise was simple: “Set it and forget it.”

The reality? One power cut, and the clock stops. Suddenly, the street lights are turning on at 2:00 PM in the blazing sun, and the water pump is running dry at midnight, waking up the whole neighborhood.

I knew I could build something better.

After frying a few microcontrollers, battling I2C noise in my workshop, and dealing with the infamous “78:40” Glitch, I finally cracked the code.

Today, I am sharing the full design with source code of the Devraj Lab Smart Timer. It uses an ESP32, features automatic mobile WiFi sync, handles power cuts gracefully, and costs less than a large pizza to build.

If you are looking for a reliable automatic on off timer switch that you can actually trust, this is the build for you.


The “Why”: Real Problems Require Real Engineering

Before we solder a single pin, we must address why most DIY timers fail in the field. It is easy to assume that connecting a microcontroller to a basic relay is enough, but real-world appliances like 1.5HP water pumps or heavy street lights are “inductive loads.”

When these devices are turned off, they fight back by generating a massive spike of voltage, known as Back EMF, which shoots back through the circuit. This electrical noise was the single biggest cause of failure in early prototypes, leading to frozen screens and system crashes.

The Solution: Use a Professional Contactor

To handle heavy inductive loads safely, you must use a 220V AC contactor, such as the Schneider LC1D25M7, or any contactor with a coil voltage that is within the relay module’s operating voltage. If you are building this in the USA, you should use a 110V relay coil contactor instead. This ensures that the high-voltage switching is handled by a rugged component designed for industrial loads, keeping your electronics safe from interference.

Real Project Experience: The “78:40” Glitch

I had just finished installing a prototype for a client. It was controlling a heavy AC motor. The system worked perfectly on my workbench with a small LED bulb.

But the moment I connected the real motor, chaos ensued.

Every time the timer tried to turn the motor OFF, the LCD screen would scramble. Sometimes it went blank. Sometimes it displayed gibberish like “Time: 78:40”.

Why Did This Happen?

It wasn’t a coding bug. It was a physical “lightning strike” on my I2C data lines.

When the relay switches an inductive load (like a pump or street light), it creates a massive Electromagnetic Interference (EMI) spike.

This spike hit the SDA and SCL wires (the communication lines between the ESP32 and the RTC).

The noise was so strong that it literally “tripped” the internal memory of the RTC module. The RTC started feeding the ESP32 scrambled numbers, and the ESP32 just dutifully printed that nonsense to the screen.

The Fix (And Why We Use Capacitors)

I realized the power rail was dipping and spiking too fast for the ESP32 to handle. I needed a shock absorber.

I didn’t have a large 1000ยตF capacitor in my bin, but I had a drawer full of smaller ones.

My Solution: I soldered two 470ยตF capacitors in parallel right next to the ESP32’s 5V input pin.

  • Why Parallel? Capacitors in parallel add up. 470ยตF + 470ยตF = 940ยตF. This gave me roughly the 1000ยตF buffer I needed.
  • The Result: The glitch vanished instantly. The power rail became stable, the screen stayed clear, and the timer has been running for months without a single error.
Two 470uF electrolytic capacitors connected in parallel on a breadboard next to an ESP32 to stabilize voltage and prevent I2C screen glitches.
The secret to stability: Capacitor “Shock Absorbers” on the power rail.

(To ensure maximum reliability, the code includes “Sanity Check” logic that forces the ESP32 to ignore any impossible or unexpected data from the RTC module, keeping the timer running without interruption.)


Why “Devraj Lab Smart Timer” Beats Store-Bought Units

You might be asking, “Devraj, why not just buy a digital timer from Amazon?”

I did the math. Most digital timers in the โ‚น1,500+ range are decent, but they have fatal flaws. Here is how our custom build compares:

FeatureGeneric Mechanical/Digital TimerDevraj Lab Smart Timer
Priceโ‚น1,000 – โ‚น2,500~โ‚น750
Power CutsClock stops or drifts significantly.RTC Battery keeps time perfect for years.
InterfaceTiny, confusing rubber buttons and small icons.Mobile WiFi Sync & Large LCD Display.
DurabilityPlastic gears wear out; relay contacts fuse.Solid State Logic (No gears to break).
RepairabilitySealed Unit. If the relay burns, you throw the whole device in the trash.100% Modular. If the โ‚น33 relay fails, you swap it out in 5 minutes.

The Repairability Factor

This is huge. In India, voltage fluctuations are common. If a spike kills the relay in a store-bought timer, the whole unit is e-waste. With the Devraj Lab design, every part is modular. You are building an asset, not buying a disposable toy.


Bill of Materials (BOM): What You Need

I have optimized this list for cost and availability. You don’t need exotic parts. These are standard components available at any local electronics shop or online.

(Prices are estimates based on current market rates in India)

  1. ESP32 Development Board (30 Pin)
    • Cost: ~โ‚น350
    • Why: We need WiFi for the mobile sync feature. An Arduino Uno cannot do this easily. The ESP32 is also dual-core, meaning it can handle the WiFi connection without pausing the timer logic.
    • I chose the ESP32 for this build because it outperforms traditional boards. If you are new to this, check out my comprehensive microcontroller development boards guide to see how the ESP32 stacks up against the competition.
  2. DS3231 RTC (Real Time Clock) Module
    • Cost: ~โ‚น100
    • Why: Do not use the cheaper DS1307. The DS3231 is “Temperature Compensated,” meaning it stays accurate even in hot Indian summers or cold winters. It includes a coin cell battery holder to keep time during power cuts.
  3. 16×2 I2C LCD Display
    • Cost: ~โ‚น180
    • Why: The “I2C” version is critical. It uses only 2 wires (SDA and SCL) instead of 16 wires, leaving the other pins free for buttons and relays.
  4. 1-Channel 5V Relay Module
    • Cost: ~โ‚น33
    • Why: This module includes the transistor and flyback diode built-in, so you can connect it directly to the ESP32. It can handle up to 10A (roughly 2000 Watts), which is enough for most water pumps and lights.
  5. 4x Tactile Push Buttons
    • Cost: ~โ‚น4
    • Why: For manual control (Up, Down, Left, Right). We need a physical interface because you might not always have your phone with you.
  6. 2x 470ยตF Electrolytic Capacitors (16V or higher)
    • Cost: ~โ‚น10
    • Why: Critical. As discussed, these prevent the ESP32 from resetting when the relay clicks. If you have a single 1000ยตF capacitor, that works too, but two 470ยตFs in parallel is often cheaper and easier to fit in flat cases.
  7. Plastic Enclosure & Jumper Wires
    • Cost: ~โ‚น80
    • Why: Safety first. We are dealing with Mains AC voltage on the relay side. Never leave this project open on a breadboard permanently.

Total Estimated Build Cost: ~โ‚น750

Flat-lay photo of Devraj Lab Smart Timer components including ESP32, DS3231 RTC, 16x2 I2C LCD, 5V Relay, and 470uF capacitors on a workbench.
The complete parts list for the Devraj Lab Smart Timer. Every component is chosen for its high reliability and low cost (under โ‚น750 for the basic kit).

The Circuit Diagram: Keeping It Clean

Wiring is where 90% of beginners make mistakes. If you connect the 5V relay to the 3.3V pin of the ESP32, it won’t trigger. If you swap SDA and SCL, the screen will remain blank.

When wiring your relay and buttons, be careful with the pin numbers. For this project, I used GPIO 23 for the relay. You can refer to my detailed ESP32 pinout reference if you want to use different pins or expand the project further.

Here is the definitive pin mapping for the Devraj Lab Edition.

Fritzing wiring diagram and connection table for the Devraj Lab Smart Timer, showing the ESP32 microcontroller connected to a DS3231 RTC module, an I2C LCD1602 display, a single-channel relay module, and four push buttons.
The complete wiring schematic for the Devraj Lab Smart Timer, detailing the connections for the ESP32, RTC, LCD, and relay. This setup can be used as an automatic timer switch for water pumps, street lights, or any AC appliance.

1. Power Distribution (The Most Important Step)

The ESP32 is a 3.3V device, but the Relay and LCD need 5V.

  • Input Power: Connect your 5V USB charger or power supply to the VIN pin and GND.
  • The Split: From the VIN pin, run wires to the VCC of the Relay and the VCC of the LCD. Do not power these from the ESP32’s 3.3V pin.

2. The I2C Bus (LCD & RTC)

We are using the I2C protocol because it allows us to chain devices.

  • SDA (Data): Connect LCD SDA and RTC SDA -> GPIO 21.
  • SCL (Clock): Connect LCD SCL and RTC SCL -> GPIO 22.
  • Devraj’s Tip: Twist the SDA and SCL wires together. This acts like a “twisted pair” and helps reduce interference from the relay.

3. The Relay (The Muscle)

  • Signal Pin: Connect to GPIO 23.
  • Why GPIO 23? It is a safe output pin that doesn’t oscillate during boot-up. Some pins on the ESP32 (like GPIO 12) can toggle high/low during startup, which would turn your pump on and off rapidly. GPIO 23 is stable.

4. The Manual Buttons

We use the internal pull-up resistors of the ESP32, so you don’t need external resistors. Just connect one side of the button to the GPIO and the other side to GND.

  • UP: GPIO 18
  • DOWN: GPIO 19
  • LEFT: GPIO 4
  • RIGHT: GPIO 5

The Code: Devraj Lab Firmware v2.3.7

This is the brain of the operation. I have refined this code over dozens of iterations to ensure it is robust.

Key Features of v2.3.7:

  1. WiFi Sync: Creates a hotspot (Devraj_Smart_Timer). You connect to it, open a page, and click one button to sync the time from your phone.
  2. Non-Blocking Logic: The timer continues to check the schedule even while you are browsing the WiFi menu.
  3. Auto-Home Safety: If you leave the device in a menu (like “Set Time”), it automatically returns to the main screen after 20 seconds. This ensures the relay logic is never paused indefinitely.

How to Flash the Code

  1. Open Arduino IDE.
  2. Install the libraries: RTClib (by Adafruit) and LiquidCrystal_I2C.
  3. Select Board: ESP32 Dev Module.
  4. Copy and paste the code below.

(Note: This is the full, refined code based on our latest v2.3.7 release)

C++


Understanding the Logic (For the Geeks)

1. The “State Machine”

Notice I didn’t use delay(1000) inside the loop. Using delay() stops the processor. If the processor stops, it can’t check if you pressed a button or if the WiFi is trying to connect.

Instead, I used a State Machine. The code is always in one “State” (like MAIN_SCREEN or SET_CLOCK). The loop() runs thousands of times per second, checking “Is a button pressed?” or “Is it time to switch the relay?”

2. The Mobile Sync Magic

How does the phone sync work without typing numbers?

It uses JavaScript running on your phone’s browser.

JavaScript

When you click the green button on the web page, this script grabs the exact time from your phone’s system clock and shoots it to the ESP32 in a millisecond URL request. The ESP32 catches this and updates the DS3231 RTC instantly.


User Manual: How to Operate Your Timer

I designed the interface to be intuitive. You don’t need a PhD to turn on your water pump.

1. The Main Screen

This is the default view.

  • Top Line: Shows the current Time (HH:MM:SS).
  • Bottom Line: Shows the Mode (AUTO or MANUAL).
  • Relay Status: An LED (or icon) indicates if the load is ON.

2. Switching Modes (Auto vs. Manual)

Sometimes you need to run the pump right now, outside of the schedule.

  • Action: Hold UP and DOWN together for 1 second.
  • Result: The mode toggles.
    • MANUAL: The timer logic is disabled. You can turn the relay ON/OFF using the LEFT button.
    • AUTOMATIC: The timer follows your scheduled Start and Stop times.

3. Setting the Schedule (The Old Way)

  • Press RIGHT to enter the Menu.
  • Select 2. TIMER SET.
  • Use UP/DOWN to change hours/minutes and RIGHT to confirm.

4. Setting the Schedule (The Smart Way)

This is the “Devraj Lab” special feature.

  1. On your phone, connect to WiFi: Devraj_Smart_Timer.
  2. Enter Password: ofmkdevraj.
  3. Open browser and go to: 192.168.4.1.
  4. Click the big GREEN BUTTON to sync time.
  5. Type your ON and OFF times and click SAVE.

Troubleshooting: What if it doesn’t work?

Even the best engineering can have hiccups. Here is how to fix common issues.

Issue 1: The screen shows weird symbols or “78:40” when the pump turns off.

  • Cause: Back EMF from the motor is resetting the LCD controller.
  • Fix: Check your capacitors! Ensure the two 470ยตF capacitors are soldered securely and close to the ESP32/LCD power pins. If the problem persists, move the relay module further away from the LCD.

Issue 2: The WiFi connects, but the page won’t load.

  • Cause: Your phone might be trying to use Mobile data because the ESP32 has no internet.
  • Fix: Turn off “Mobile Data” on your phone for a minute. Or, try a different browser (Chrome works best).

Issue 3: I forgot the WiFi Password.

  • Cause: It happens to the best of us.
  • Fix: I added a helper menu!
    1. Press RIGHT to enter the System Menu.
    2. Scroll down to 4. WIFI INFO.
    3. Press DOWN to reveal the IP, SSID, and Password on the screen.

Enclosure & Final Assembly

Don’t leave this beautiful project naked on a table.

  • The Box: Use a generic 4×4 inch PVC electrical junction box (available at any hardware store for โ‚น50).
  • The Cutouts: Use a Dremel or a hot knife to cut a rectangle for the LCD. Drill 4 holes for the push buttons.
  • Mounting: Use hot glue to secure the ESP32 and Relay. Ensure the back of the PCB doesn’t touch anything metal!

Conclusion

We started with a frustrationโ€”unreliable mechanical timers that failed us when we needed them most.

We ended with a robust, WiFi-enabled Smart Timer that:

  1. Keeps perfect time (thanks to DS3231).
  2. Withstands electrical noise (thanks to our capacitor shock absorbers).
  3. Syncs effortlessly with your phone.
  4. Is fully repairable and modular.

By adding WiFi connectivity to a standard timer, we are turning a simple tool into a smart device. This is a perfect example of what IoT meansโ€”connecting physical hardware to the internet to solve real-world problems.

This is the difference between “sticking components together” and Engineering.

If you build this Devraj Lab Smart Timer, please share your photos in the comments below. Did you use it for a water pump? A hydroponic setup? Let me know!

Happy Making!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *