Switch a lamp on a schedule with the Arduino Cloud scheduler

Make a lamp that switches itself on and off on a timetable you set from your phone. You use the Arduino Cloud Scheduler widget and a Schedule variable, an ESP32 and a relay, plus a "switch on now" button for...
  • Level:Intermediate
  • Duration: 50 min
  • Ages 12+
  • Platform: ESP32

Tools for this lesson

Helpful for this build. Open a tool to see tips and more projects that use it.

Switch a lamp on a schedule with the Arduino Cloud scheduler – EEMENTOR STEM™ lesson

A light that switches on by itself at sunset, a fish tank lamp that runs eight hours a day, a heater that only works on school mornings: these all follow a timetable. In this lesson you build one with the ESP32 and Arduino Cloud. You set the timetable in a Scheduler widget on your phone, for example "every day from 18:00 to 22:30", and the ESP32 switches a relay at the right moments, even when your phone is off. A "switch on now" button lets you override it. The lamp here is an LED powered through the relay, so everything stays at a safe low voltage.

What you'll learn

  • How the Arduino Cloud Schedule variable and Scheduler widget work
  • How to check a schedule in your sketch with isActive()
  • Why the Thing's time zone matters
  • How a relay switches a separate circuit through its COM and NO contacts
  • How to combine a timetable with a manual override

What you need

  • ESP32 board, expansion board and USB cable (ESP32 IoT Starter Kit)
  • Two-channel relay module, one channel used (ESP32 IoT Starter Kit)
  • White LED and a 220 Ω resistor, as the lamp (ESP32 IoT Starter Kit)
  • Breadboard and jumper wires (ESP32 IoT Starter Kit)
  • A 2.4 GHz Wi-Fi network, a free Arduino Cloud account and the free Arduino IoT Remote app on a phone

Low voltage only: in this lesson the relay switches an LED from the ESP32's 3.3 V. Never connect a relay module from a starter kit to mains electricity (the sockets in your home). Mains can kill, and it needs proper certified equipment and an electrician.

Wiring

The relay module has two sides. On the pin side, VCC, GND and IN1 connect to the ESP32 and work the relay's coil. On the screw side, the relay is just a switch with three contacts: COM (common), NO (normally open: connected to COM only while the relay is on) and NC (normally closed). The lamp circuit goes through COM and NO.

Wiring diagram: relay module VCC to ESP32 5V, GND to GND, IN1 to GPIO 23; relay COM to 3V3 and NO through a 220 ohm resistor to a white LED, whose other leg goes to GND.
Low voltage only: the relay switches an LED from 3.3 V. Check each connection against the table.
From To
Relay VCC ESP32 5V (5 V from USB)
Relay GND ESP32 GND
Relay IN1 ESP32 GPIO 23
Relay COM (channel 1) ESP32 3V3
Relay NO (channel 1) 220 Ω resistor → white LED long leg (+)
White LED short leg (−) ESP32 GND

Most relay modules like this one switch on when the IN pin is pulled LOW. The sketch takes care of that.

FREE

Build this circuit in EEMENTOR Lab

Wire it yourself in your browser before you touch a real wire. No sign-up, nothing to install.

The ESP32 and the parts for this lesson laid out in EEMENTOR Lab, ready to wireBuild it yourself
  1. The ESP32 and this lesson’s parts are already placed. Wire them using the wiring table above. Pins with no wire show red.
  2. Missing a part? Add it from the parts list on the left.
  3. Press Run, then try the inputs: click, hold or slide them under Selected.
  4. Wi-Fi and Bluetooth don’t run in the Lab yet, so use it to build the circuit and check the wiring before you upload the real sketch.

EEMENTOR Lab is free and in beta. Results are a guide; a real build can differ slightly. About the Lab

Set up Arduino Cloud

New to Arduino Cloud? Follow the setup steps in Connect the ESP32 to Arduino Cloud first: create the account, add your ESP32 as a device and keep the PDF with its secret key. Then:

  1. Open Things, click + Thing and rename it Schedule Lamp. Under Associated device, pick your ESP32, and under Network enter your Wi-Fi name, password and the secret key.
  2. Set the Thing's time zone (in the Thing's settings, from the drop-down menu) to where you live. The schedule uses it.
  3. Add three Cloud Variables:
    • lampSchedule, type Schedule, Read & Write
    • switchOnNow, type Boolean, Read & Write
    • lampOn, type Boolean, Read Only (the ESP32 reports whether the lamp is on)

Free plan: Arduino Cloud's free plan lets you use 2 Things with up to 5 variables each, so this Thing fits. Check the plans page for the current limits.

The sketch

In the Thing, open the Sketch tab, click Open full editor, replace the main sketch with the code below and upload. Leave the thingProperties.h and Secret tabs as Arduino Cloud made them.

#include "thingProperties.h"

const int RELAY_PIN = 23;           // relay IN1: LOW = on, HIGH = off

void setup() {
  Serial.begin(115200);
  delay(1500);                      // give the Serial Monitor time to open
  pinMode(RELAY_PIN, OUTPUT);
  digitalWrite(RELAY_PIN, HIGH);    // start with the lamp off

  initProperties();
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  setDebugMessageLevel(2);          // connection messages in the Serial Monitor
  ArduinoCloud.printDebugInfo();
}

void loop() {
  ArduinoCloud.update();            // keeps the connection alive and syncs variables

  // The lamp is on during a scheduled job, or when "switch on now" is on
  bool shouldBeOn = lampSchedule.isActive() || switchOnNow;
  if (shouldBeOn != lampOn) {
    lampOn = shouldBeOn;            // shows up on the dashboard
    digitalWrite(RELAY_PIN, lampOn ? LOW : HIGH);
    Serial.println(lampOn ? "Lamp ON" : "Lamp OFF");
  }
}

// Runs when you change the schedule in the dashboard
void onLampScheduleChange() {
  Serial.println("New schedule received");
}

// Runs when you flip the "switch on now" switch
void onSwitchOnNowChange() {
  Serial.println(switchOnNow ? "Override: on" : "Override: off");
}

For reference, this is the kind of thingProperties.h that Arduino Cloud creates from the three variables. Yours has your own device ID and may look slightly different.

// Code generated by Arduino Cloud (yours has your own device ID)
#include <ArduinoIoTCloud.h>
#include <Arduino_ConnectionHandler.h>

const char DEVICE_LOGIN_NAME[] = "YOUR_DEVICE_ID";
const char SSID[] = SECRET_SSID;              // from the Secret tab
const char PASS[] = SECRET_OPTIONAL_PASS;
const char DEVICE_KEY[] = SECRET_DEVICE_KEY;

void onLampScheduleChange();
void onSwitchOnNowChange();

CloudSchedule lampSchedule;
bool switchOnNow;
bool lampOn;

void initProperties() {
  ArduinoCloud.setBoardId(DEVICE_LOGIN_NAME);
  ArduinoCloud.setSecretDeviceKey(DEVICE_KEY);
  ArduinoCloud.addProperty(lampSchedule, Permission::ReadWrite).onUpdate(onLampScheduleChange);
  ArduinoCloud.addProperty(switchOnNow, Permission::ReadWrite).onUpdate(onSwitchOnNowChange);
  ArduinoCloud.addProperty(lampOn, Permission::Read);
}

WiFiConnectionHandler ArduinoIoTPreferredConnection(SSID, PASS);

Build the dashboard

  1. Open Dashboards, click + Dashboard and name it "Schedule Lamp".
  2. Add a Scheduler widget and link it to lampSchedule.
  3. Add a Switch widget linked to switchOnNow, and a Status (or LED) widget linked to lampOn.
  4. Open the Scheduler and create a job: pick a start date and time a couple of minutes from now, set a duration of 2 minutes, and choose to repeat it every day.

Try it

  1. Wait for the start time. The relay clicks, the white LED lights, the Status widget shows the lamp is on and the Serial Monitor says "Lamp ON".
  2. Two minutes later it clicks off again by itself.
  3. Flip switch on now: the lamp comes on at once. Flip it back, and the schedule takes over again.
  4. Open the dashboard in the Arduino IoT Remote app on your phone and change the job to a real timetable, such as every day from 18:00 for 4 hours 30 minutes, or only on weekdays.
  5. Close the app and switch your phone off. The lamp still follows the timetable, because the schedule lives in Arduino Cloud and the ESP32.

What you should see

The Schedule Lamp dashboard with a Scheduler set to 18:00 for 4 hours 30 minutes every day, a switch-on-now switch and a lamp status that is on, next to the Serial Monitor messages.
Set the timetable once; the lamp follows it.

How it works

How it works: the Scheduler widget sets a job, Arduino Cloud keeps it and sends it to the ESP32, and the ESP32 checks isActive() to switch the relay; a day timeline with the lamp on from 18:00 to 22:30.
The timetable lives in the cloud; the ESP32 follows it.

A Schedule variable doesn't hold a simple on or off. It holds a job: a start and end date, how long each run lasts (in hours, minutes and seconds) and how often it repeats: every minute, hour, day, week, month or year, or only on certain days. You edit it with the Scheduler widget, and Arduino Cloud sends the job to the ESP32 like any other variable.

In the sketch, lampSchedule.isActive() answers one question: "is a job running right now?" It returns true or false, using the time the ESP32 gets from Arduino Cloud and the Thing's time zone. That's why the time zone setting matters: with the wrong one, your lamp would switch at 18:00 somewhere else in the world.

loop() asks isActive() over and over, combines it with switchOnNow using || (or), and only touches the relay when the answer changes. Each change is also written to lampOn, a Read Only variable, so the dashboard shows what the lamp is really doing. The relay itself is an electromagnet that pulls a metal contact across from NC to NO, connecting COM to the LED's circuit. The LED's power never passes through the ESP32's pin; the pin only switches the relay's coil.

Try this next

  • Use the second relay channel and a second Schedule variable for a second lamp on its own timetable.
  • Add a light sensor and only switch the lamp on during the schedule if it's actually dark, like in the automatic night light.
  • Count how many minutes the lamp was on today and show it in a Value widget.
  • Go back to the smart home control panel and add a schedule to it.

Troubleshooting

  • The lamp switches at the wrong hour: check the Thing's time zone, and that the job's start time is in that time zone.
  • The relay clicks but the LED stays dark: the LED is wired to NC instead of NO, or it is the wrong way round. Long leg towards the resistor.
  • The relay is on when it should be off: your relay module switches on with HIGH. Swap LOW and HIGH in the two digitalWrite() lines.
  • Nothing happens and the Serial Monitor shows connection errors: check the Wi-Fi name and password (2.4 GHz only) and the secret key in the Thing's network settings.
  • The sketch doesn't compile: "lampSchedule was not declared": the variable names in the Thing must match the sketch exactly, including capital letters.