Quick answer: in Node-RED, schedule things with the Inject node (Repeat: at a specific time, on chosen days). For cron expressions and sunrise/sunset triggers, use node-red-contrib-cron-plus. Remember state between messages with context: context (one node), flow (one tab) and global (all tabs), read and written with flow.get("name") / flow.set("name", value) and viewed in the Context Data sidebar. Context lives in memory and is lost on restart unless you enable localfilesystem storage in settings.js. For light sensors (LDRs), switch with two thresholds (hysteresis) so a reading hovering near the limit doesn't flicker the lamp.
This guide builds one practical automation that uses all three: lights on at dusk, off at a fixed bedtime, driven by an ESP32 LDR over MQTT, with the lamp's state remembered in context and a guard against stale sensor data.
| Tool | Use it for | Where |
|---|---|---|
| Inject → at a specific time | Fixed clock times on chosen weekdays | Core node |
| Inject → interval between times | "Every 5 minutes between 08:00 and 18:00" | Core node |
| cron-plus | Cron expressions, sunrise/sunset with offsets, time zones, schedules set by message | Palette: node-red-contrib-cron-plus |
context / flow / global | Remember values between messages | Function node, Change node, Context sidebar |
| Hysteresis | Stop noisy sensors switching outputs on and off | Function node (below) |
1. Schedules with the Inject node
Open an Inject node and set Repeat:
| Repeat option | Example | Notes |
|---|---|---|
| interval | Every 30 seconds | Starts counting at deploy |
| interval between times | Every 10 min, 07:00–22:00, Mon–Fri | Minimum interval is 1 minute |
| at a specific time | 23:00 on every day | One shot per selected day |
Set the payload to what the next node expects, for example the string OFF, and tick Inject once after 0.1 seconds only if you want the action to also run at every deploy or restart.
Time zone: Node-RED uses the time zone of the machine (or container) it runs on. A Raspberry Pi set to UTC fires "23:00" at 23:00 UTC. Check with timedatectl and fix it with sudo timedatectl set-timezone Asia/Kolkata (use your zone). In Docker, pass -e TZ=Asia/Kolkata.
Sunrise, sunset and cron with cron-plus
Install node-red-contrib-cron-plus from Manage palette. One node can hold several schedules:
| Schedule type | Example |
|---|---|
| Cron | 0 30 6 * * 1-5 = 06:30:00 on weekdays (6-field cron, seconds first) |
| Solar | sunset with an offset of +15 minutes |
| Dynamic | Add, remove or pause schedules by sending the node a message |
Solar schedules need your latitude and longitude (pick them on the node's map). This is the cleanest way to do "lights on 15 minutes after sunset", which changes every day. It also lets you set a time zone per node.
2. Read an LDR and switch with hysteresis
Sensor side. Wire the LDR in a voltage divider with a 10 kΩ resistor to an ESP32 ADC1 pin such as GPIO34 (ADC2 pins don't work while Wi-Fi is on). Publish the reading to MQTT every few seconds, for example as a 0–100 % "brightness". A raw ADC number is not lux: to work in real lux, calibrate against a lux meter or use a digital sensor such as the BH1750. See ESP32 ADC pins.
The flicker problem. With one threshold ("ON below 100"), a reading wobbling between 95 and 105 at dusk switches the lamp on and off every few seconds. Hysteresis uses two thresholds: turn ON below the low one and OFF only above the high one. Anything in between keeps the current state.
// Input: msg.payload = light level (calibrated lux or 0-100 %). Tune both thresholds.
const ON_BELOW = 80;
const OFF_ABOVE = 120;
const level = Number(msg.payload);
if (!Number.isFinite(level) || level < 0) {
node.warn("Invalid light reading: " + msg.payload);
return null;
}
flow.set("lightLastSeen", Date.now()); // for the stale-data guard
let lampOn = flow.get("lampOn") ?? false;
if (!lampOn && level < ON_BELOW) lampOn = true;
else if (lampOn && level > OFF_ABOVE) lampOn = false;
else return null; // inside the dead band: no change, no message
if (flow.get("manualOverride")) return null; // someone switched it by hand
flow.set("lampOn", lampOn);
msg.payload = lampOn ? "ON" : "OFF";
node.status({ fill: lampOn ? "yellow" : "grey", shape: "dot", text: msg.payload + " @ " + level });
return msg;Wire it as mqtt in (home/garden/light) → function above → mqtt out (home/garden/lamp/set). The function only sends a message when the state actually changes, so the relay and the broker don't get a command every few seconds.
3. Context: node, flow and global
Context is Node-RED's memory between messages. Use the smallest scope that works:
| Scope | Visible to | Read / write in a Function node | Typical use |
|---|---|---|---|
context | That one node | context.get("count") / context.set("count", n) | Counters, last value seen by this node |
flow | All nodes on the same tab | flow.get("lampOn") / flow.set("lampOn", true) | State shared by one automation |
global | Every tab | global.get("away") / global.set("away", true) | House-wide modes: away, holiday, night |
You don't need a Function node for simple cases: the Change node can set flow.lampOn or copy global.away into msg.away, and a Switch node can test flow.lampOn directly. Open the Context Data sidebar (the database icon in the right panel) and click refresh to see current values while you debug.
Make context survive restarts
By default context is held in memory: it survives deploys, but a Node-RED restart (or a reboot of the Pi) clears it and the flow forgets the lamp is on. Add this to settings.js and restart Node-RED:
contextStorage: {
default: { module: "memory" },
file: { module: "localfilesystem" }
},Then choose the store per value: flow.set("lampOn", true, "file") and flow.get("lampOn", "file"). Values in the file store are written to disk (by default every 30 seconds) and reloaded at startup. Keep fast-changing values in memory and only the important state on disk.
Remember that a remembered variable is what the flow believes. After a restart, the real lamp may have changed (a power cut, a wall switch). Where the device reports its state over MQTT, update flow.lampOn from that report instead of trusting the stored value.
4. Combine the schedule, the sensor and a manual override
A full evening-light automation on one tab:
| Trigger | Action |
|---|---|
| LDR drops below 80 (after sunset) | Lamp ON (hysteresis function) |
| Inject at 23:00 | Lamp OFF, flow.lampOn = false, flow.manualOverride = false |
| Dashboard switch | Lamp ON/OFF, flow.manualOverride = true until 23:00 |
| No light reading for 10 minutes | Alert; stop automatic switching (stale-data guard) |
The 23:00 Inject feeds a Change node that sets msg.payload to OFF and clears the two flow variables, then goes to the same mqtt out. The dashboard switch sets flow.manualOverride to true, so the sensor rule stops fighting the person who just pressed the button.
Stale-data guard: an Inject every minute → function:
const last = flow.get("lightLastSeen") || 0;
if (Date.now() - last > 10 * 60 * 1000) {
node.status({ fill: "red", shape: "ring", text: "light sensor silent" });
return { payload: "Light sensor has not reported for 10 minutes" }; // → alert
}
node.status({ fill: "green", shape: "dot", text: "sensor ok" });
return null;Never turn a missing reading into 0: zero lux means darkness, so a dead sensor would switch the lamp on.
5. Test with Inject nodes before connecting a lamp
Feed numbers into the hysteresis function from Inject nodes, starting with the lamp OFF:
| Send | Expected output | Why |
|---|---|---|
| 150 | nothing | Already OFF and bright |
| 70 | ON | Below 80 |
| 95 | nothing | Dead band: stays ON |
| 115 | nothing | Still in the dead band |
| 130 | OFF | Above 120 |
| 100 | nothing | Dead band: stays OFF |
"abc" or empty | warning only | Invalid input rejected |
Then restart Node-RED and check the Context Data sidebar: with in-memory context lampOn is gone, while with the file store it's still there.
When you connect a real relay, check its polarity and boot state, and treat the MQTT command as a request: let the device publish its actual state back. See ESP32 8-channel relay with MQTT state feedback.
Troubleshooting
| Problem | Likely cause | Fix |
|---|---|---|
| Schedule fires an hour (or 5½ hours) off | System time zone wrong | Set the Pi/server time zone; in Docker pass TZ |
| Inject didn't fire after a reboot at that time | Node-RED wasn't running at the scheduled moment | Add inject once at start plus logic that checks the current time |
| Lamp flickers at dusk | Single threshold or thresholds too close together | Widen the dead band; average a few readings first |
flow.get() returns undefined | Different tab (flow context is per tab), or the value was never set | Use global for cross-tab values; set a default with ?? false |
| Values lost after restart | Memory context | Configure localfilesystem and use the "file" store |
flow.get("x", "file") errors | Store name not defined in settings.js | Add the store and restart Node-RED |
| Sunrise/sunset times wrong | Location not set in cron-plus | Set the latitude/longitude on the node |
| Automation fights manual control | No override flag | Add flow.manualOverride as above |
FAQ
What's the difference between flow and global context in Node-RED? Flow context is shared by the nodes on one tab; global context is shared across all tabs. Prefer flow context and use global only for values that really are house-wide.
How do I schedule something in Node-RED? For a fixed time, use an Inject node set to at a specific time. For cron expressions or sunrise/sunset, install node-red-contrib-cron-plus.
Does context survive a deploy?
Yes. Deploying doesn't clear context. Restarting Node-RED clears in-memory context; persistent localfilesystem context survives restarts too.
Can I see context values without a debug node? Yes: open the Context Data sidebar and click refresh next to Node, Flow or Global.
Next steps
- ESP32 8-channel relay with MQTT state feedback: the device side of the lamp command.
- Node-RED 8-channel relay dashboard: manual switches next to the automation.
- Node-RED Dashboard 2.0 setup.
- Reliable flows with Catch nodes and subflows.
- Prefer a cloud app? Blynk automations and schedules.
Official references: Working with context and node-red-contrib-cron-plus.




