Quick answer: to control a relay from Blynk with an ESP32, create a V0 datastream (integer 0–1) for a Switch widget, wire the relay module's IN pin to a safe GPIO such as GPIO26, and in BLYNK_WRITE(V0) drive the pin LOW to switch on (most relay modules are active-low). Then add three things most tutorials skip: (1) set the pin to OFF before Wi-Fi starts, so the relay never clicks on at boot; (2) report the applied state on a second datastream (V1) so the app shows what the relay actually did; (3) a physical button that toggles the relay locally and updates the app, so the light still works when the internet is down. The full sketch is below.
| Requirement | How this guide handles it |
|---|---|
| Relay must not switch on at power-up | Output set OFF in setup() before Blynk.begin() |
| App must show the real state | ESP32 writes V1 (reported) separately from V0 (requested) |
| Must work without internet | Local push button toggles the relay; state syncs when back online |
| Correct behaviour after reconnect | Board pushes its current state to the app instead of replaying an old command |
| Active-low module on 3.3 V logic | Wiring options that switch fully off (section 1) |
Safety first: an LED or a 12 V lamp is the right test load. Mains wiring belongs in a proper enclosure with correctly rated parts and, where required, a qualified electrician. Never put mains on a breadboard.
1. Wire the relay module
Most hobby relay boards (blue SRD-05VDC-SL-C relays) have a transistor or optocoupler input and are active-low: IN pulled LOW = relay ON.
| Relay module pin | ESP32 pin | Notes |
|---|---|---|
| IN (or IN1) | GPIO26 | No boot-strapping role; set OFF in code before Wi-Fi |
| VCC | 5V (VIN) | Relay coils need 5 V on "5 V" modules |
| GND | GND | Common ground |
| JD-VCC / VCC jumper | See below | Only on optocoupler modules |
| COM / NO / NC | Load side | NO = open when OFF (use this for lights) |
The 3.3 V gotcha. With the module powered from 5 V, an ESP32 "HIGH" is only 3.3 V. On some modules that still leaves the input LED slightly lit, so the relay never fully releases, or chatters. Fixes, in order of preference:
- Optocoupler modules with a JD-VCC jumper: remove the jumper, feed VCC from 3V3 (input side) and JD-VCC from 5V (coil side), with GND shared. Now 3.3 V HIGH fully turns the input off, and the coil is still powered from 5 V.
- Buy a relay module rated for 3.3 V trigger (often sold as "3.3V relay module" or with a high/low-level jumper).
- Drive the IN pin through an NPN transistor or a logic-level MOSFET.
Avoid GPIO0, 2, 5, 12 and 15 for relays: they're strapping pins and can glitch or block booting. GPIO34–39 are input-only. See the ESP32 pinout guide.
Physical button (optional but recommended): a push button between GPIO27 and GND (the sketch enables the internal pull-up).
2. Set up the datastreams and widgets
| Datastream | Pin | Type | Range | Widget | Meaning |
|---|---|---|---|---|---|
| Relay command | V0 | Integer | 0–1 | Switch | What the user asks for |
| Relay state | V1 | Integer | 0–1 | LED | What the board actually applied |
Create both on your template (Developer Zone → Templates → Datastreams), add the Switch and LED widgets on the web and mobile dashboards, then create a device and copy its BLYNK_ lines. New to this? Control an ESP32 LED with Blynk walks through every click.
Why two datastreams? If the ESP32 is offline when you tap the switch, V0 changes in the app but nothing happens at the board. A separate V1 driven by the board makes that mismatch visible, together with Blynk's online/offline badge.
3. Upload the sketch
Set RELAY_ACTIVE_LOW to match your module (true for the common blue boards). Replace the three BLYNK_ lines and Wi-Fi details. The #define lines must stay above the includes. This sketch uses Blynk.config() + Blynk.connect() instead of Blynk.begin(), so the button keeps working even when Wi-Fi or Blynk.Cloud is unreachable.
#define BLYNK_TEMPLATE_ID "TMPLxxxxxxxxx"
#define BLYNK_TEMPLATE_NAME "ESP32 Relay"
#define BLYNK_AUTH_TOKEN "REPLACE_WITH_DEVICE_AUTH_TOKEN"
#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
const char* WIFI_SSID = "REPLACE_WITH_WIFI";
const char* WIFI_PASS = "REPLACE_WITH_WIFI_PASSWORD";
const int RELAY_PIN = 26;
const int BUTTON_PIN = 27; // push button to GND
const bool RELAY_ACTIVE_LOW = true; // most blue relay modules
BlynkTimer timer;
bool relayOn = false;
void writeRelay(bool on) {
relayOn = on;
digitalWrite(RELAY_PIN, (on == RELAY_ACTIVE_LOW) ? LOW : HIGH);
Serial.printf("Relay %s\n", on ? "ON" : "OFF");
if (Blynk.connected()) {
Blynk.virtualWrite(V1, on); // reported state
Blynk.virtualWrite(V0, on); // keep the switch in step (e.g. after a button press)
}
}
BLYNK_WRITE(V0) { // switch in the app
int v = param.asInt();
if (v == 0 || v == 1) writeRelay(v == 1);
}
BLYNK_CONNECTED() { // board is the source of truth after (re)connecting
Blynk.virtualWrite(V0, relayOn);
Blynk.virtualWrite(V1, relayOn);
}
// Debounced local button: works with or without internet
void checkButton() {
static int lastReading = HIGH, stable = HIGH;
static unsigned long changedAt = 0;
int reading = digitalRead(BUTTON_PIN);
if (reading != lastReading) { changedAt = millis(); lastReading = reading; }
if (millis() - changedAt > 40 && reading != stable) {
stable = reading;
if (stable == LOW) writeRelay(!relayOn); // pressed
}
}
void setup() {
// 1) Safe state FIRST, before any networking
digitalWrite(RELAY_PIN, RELAY_ACTIVE_LOW ? HIGH : LOW);
pinMode(RELAY_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.begin(115200);
// 2) Non-blocking connection: the loop runs even if Wi-Fi is down
WiFi.begin(WIFI_SSID, WIFI_PASS);
Blynk.config(BLYNK_AUTH_TOKEN);
timer.setInterval(20L, checkButton);
timer.setInterval(10000L, []() { // retry the cloud every 10 s if needed
if (WiFi.status() == WL_CONNECTED && !Blynk.connected()) Blynk.connect(3000);
});
}
void loop() {
if (Blynk.connected()) Blynk.run();
timer.run();
}What the important parts do
| Code | Why |
|---|---|
digitalWrite before pinMode(OUTPUT) in setup() | The pin starts at the OFF level the instant it becomes an output, avoiding a click at boot |
(on == RELAY_ACTIVE_LOW) ? LOW : HIGH | One flag handles active-low and active-high modules |
BLYNK_CONNECTED() writes V0 and V1 | After a reconnect, the app shows the board's real state instead of replaying a stale tap |
Blynk.config() + Blynk.connect() | Unlike Blynk.begin(), doesn't block: the button works offline |
| Debounce (40 ms) | One press = one toggle, even with a bouncy switch |
Why not Blynk.syncVirtual(V0) here? For an LED, restoring the last app value after a reboot is handy. For a relay, a power cut at 3 a.m. followed by "restore last state" can switch a heater or pump on with nobody watching. This sketch boots OFF and tells the app so. If your load is harmless and you want restore-after-power-cut, call Blynk.syncVirtual(V0) in BLYNK_CONNECTED() instead.
4. Extend to 2, 4 or 8 relays
Use arrays and one datastream pair per channel. Common safe GPIOs on an ESP32 DevKit: 26, 27, 25, 33, 32, 13, 14, 23 (move the button off 27 if you use it for a relay).
const int RELAYS[] = {26, 25, 33, 32}; // 4 channels
// V0..V3 = commands, V10..V13 = reported states
BLYNK_WRITE_DEFAULT() { // one handler for every virtual pin
int pin = request.pin;
if (pin >= 0 && pin < 4) setRelay(pin, param.asInt() == 1);
}BLYNK_WRITE_DEFAULT() catches writes to any virtual pin without its own handler; request.pin tells you which. Remember that many multi-channel boards draw 70–80 mA per energised coil, so 4–8 relays on at once need a real 5 V supply, not the ESP32's USB pin.
5. Test before connecting a real load
| Test | Expected result |
|---|---|
| Power up | Relay stays OFF (no click); app shows OFF |
| Tap the switch ON/OFF | Relay clicks; V1 LED follows within a second |
| Press the physical button | Relay toggles; app switch and LED update |
| Unplug the router, press the button | Relay still toggles; app shows the device offline |
| Reconnect the router | App switch and LED jump to the board's real state |
| Tap the switch while the board is offline, then reconnect | Board state wins; the stale tap is not applied |
| Reset the ESP32 with the relay ON | Relay goes OFF and stays OFF (safe boot) |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Relay works "backwards" | Active-low module with RELAY_ACTIVE_LOW = false (or vice versa) | Flip the flag |
| Relay never turns off, or its LED glows dimly | 3.3 V HIGH not enough for a 5 V module input | Use the JD-VCC split (VCC=3V3, JD-VCC=5V) or a 3.3 V-trigger module |
| Relay clicks once at boot | Pin set OFF too late, or a strapping pin used | Keep the order in setup(); use GPIO26 |
| ESP32 resets when the relay switches | Coil current or load noise browning out the supply | Separate 5 V supply for relays; add a snubber for inductive loads |
| App switch jumps back | Board publishes its state (by design) and the command didn't apply | Check wiring, flag and Serial output |
| Device offline, button does nothing | Sketch uses Blynk.begin() (blocks without Wi-Fi) | Use the Blynk.config() version above |
| Multiple relays: wrong one switches | Datastream ↔ index mismatch | Print request.pin in the handler |
FAQ
Is my relay module active-low or active-high? Most blue single/multi-channel boards are active-low (IN LOW = ON). Some have an H/L jumper. Test with a jumper wire: IN to GND should click it on if it's active-low.
Can I power the relay from the ESP32's 3.3 V pin? Only "3.3 V" relay modules. Standard 5 V relays need 5 V on the coil (from VIN/USB or a separate supply).
Will the relay work if Blynk is down? With this sketch, yes: the physical button works offline. Schedules and app control need the cloud.
Can I use an ESP8266 / NodeMCU?
Yes. Use ESP8266WiFi.h and BlynkSimpleEsp8266.h, and pick safe pins such as D1 (GPIO5) or D2 (GPIO4) for relays, D5–D7 for buttons. See NodeMCU ESP8266 with Blynk.
Can I schedule the relay? Yes, with Blynk Automations: Blynk schedules and automations on ESP32.
Next steps
- Control an ESP32 LED with Blynk: the simpler version of this sketch.
- Blynk automations and schedules.
- Blynk 2.0 complete guide.
- Prefer local control? ESP32 8-channel relay with MQTT and state feedback.
Official reference: Blynk documentation. This example is a control pattern, not a certified safety design for mains equipment.




