Skip to content

Tutorial

Node-RED Scheduler and Context Variables: Automate Lights with an LDR

Build a Node-RED light automation: Inject and cron-plus schedules, sunset triggers, node/flow/global context with persistent storage, LDR hysteresis and overrides.

  • 5 min read
  • Updated November 2, 2026
Node-RED Scheduler and Context Variables: Automate Lights with an LDR

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.

ToolUse it forWhere
Inject → at a specific timeFixed clock times on chosen weekdaysCore node
Inject → interval between times"Every 5 minutes between 08:00 and 18:00"Core node
cron-plusCron expressions, sunrise/sunset with offsets, time zones, schedules set by messagePalette: node-red-contrib-cron-plus
context / flow / globalRemember values between messagesFunction node, Change node, Context sidebar
HysteresisStop noisy sensors switching outputs on and offFunction node (below)

1. Schedules with the Inject node

Open an Inject node and set Repeat:

Repeat optionExampleNotes
intervalEvery 30 secondsStarts counting at deploy
interval between timesEvery 10 min, 07:00–22:00, Mon–FriMinimum interval is 1 minute
at a specific time23:00 on every dayOne 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 typeExample
Cron0 30 6 * * 1-5 = 06:30:00 on weekdays (6-field cron, seconds first)
Solarsunset with an offset of +15 minutes
DynamicAdd, 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.

With one threshold, the noisy dusk readings would switch the lamp 14 times; with an 80/120 lux dead band it switches twice
script.js
// 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:

ScopeVisible toRead / write in a Function nodeTypical use
contextThat one nodecontext.get("count") / context.set("count", n)Counters, last value seen by this node
flowAll nodes on the same tabflow.get("lampOn") / flow.set("lampOn", true)State shared by one automation
globalEvery tabglobal.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:

script.js
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:

TriggerAction
LDR drops below 80 (after sunset)Lamp ON (hysteresis function)
Inject at 23:00Lamp OFF, flow.lampOn = false, flow.manualOverride = false
Dashboard switchLamp ON/OFF, flow.manualOverride = true until 23:00
No light reading for 10 minutesAlert; 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:

script.js
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:

SendExpected outputWhy
150nothingAlready OFF and bright
70ONBelow 80
95nothingDead band: stays ON
115nothingStill in the dead band
130OFFAbove 120
100nothingDead band: stays OFF
"abc" or emptywarning onlyInvalid 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

ProblemLikely causeFix
Schedule fires an hour (or 5½ hours) offSystem time zone wrongSet the Pi/server time zone; in Docker pass TZ
Inject didn't fire after a reboot at that timeNode-RED wasn't running at the scheduled momentAdd inject once at start plus logic that checks the current time
Lamp flickers at duskSingle threshold or thresholds too close togetherWiden the dead band; average a few readings first
flow.get() returns undefinedDifferent tab (flow context is per tab), or the value was never setUse global for cross-tab values; set a default with ?? false
Values lost after restartMemory contextConfigure localfilesystem and use the "file" store
flow.get("x", "file") errorsStore name not defined in settings.jsAdd the store and restart Node-RED
Sunrise/sunset times wrongLocation not set in cron-plusSet the latitude/longitude on the node
Automation fights manual controlNo override flagAdd 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

Official references: Working with context and node-red-contrib-cron-plus.

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.