Overview
In this project, we will build a Home Automation Project with Raspberry Pi Pico W & Blynk 2.0 using MicroPython Code.
Home automation has become increasingly popular in recent years, with many homeowners seeking ways to control their homes’ various systems remotely. One affordable and customizable solution is to use a Raspberry Pi Pico W microcontroller and the Blynk app to control a 4-channel relay.
The Raspberry Pi Pico W is a low-cost microcontroller board that can be programmed in C or MicroPython, and it has a number of input/output pins that can be used to control other devices. The Blynk app is a smartphone app that allows users to create custom interfaces for controlling devices connected to the internet.
By connecting a 4-channel relay to the Raspberry Pi Pico W and programming it with MicroPython Code, homeowners can control a variety of home automation systems, including lighting, HVAC, and security. This setup is affordable, customizable, and can be adapted to suit the needs of individual homeowners.
Bill of Materials
In this guide, I used SunFounder Raspberry Pi Pico W Kit to test different Modules. You can buy the kit and perform some other operations as well. From this kit, you can use the following components.
| S.N. | Components | Quantity | Purchase Links |
|---|---|---|---|
| 1 | Raspberry Pi Pico W | 1 | |
| 2 | DC POWER-JACK | 1 | |
| 3 | LED 1206 | 5 | |
| 4 | Diode 1N4007 | 4 | |
| 5 | 3 Pin Terminal Block | 4 | |
| 6 | Transistor BC547A | 4 | |
| 7 | Resistor 1K | 9 | |
| 8 | Capacitor 10uF/16V | 2 | |
| 9 | Capacitor 100uF/25V | 1 | |
| 10 | LM7805 Voltage Regulator IC | 1 | |
| 11 | Relay 5V | 4 | |
| 12 | PCF817 Optocoupler IC | 4 |
Schematic & Hardware Design
Let’s have an overview of the schematic for the Raspberry Pi Pico W Home Automation Project. The circuit consists of several key components, including relays, optocouplers, transistors, diodes, LEDs, a voltage regulator, and a power source.
The optocouplers are used to isolate the low-voltage control signal from the high-voltage AC or DC load. They consist of an LED and a photo-transistor in a single package and are used to activate the corresponding relay coil by providing a current to the BC547 transistor. The BC547 transistor amplifies the current supplied by the optocouplers and provides enough current to energize the relay coil. This allows current to flow through the load device connected to the relay.
The 1N4007 diodes are connected in reverse bias across each relay coil. They provide a path for the back-emf energy generated by the relay coil when it is turned off, protecting the BC547 transistor from damage. The 7805 voltage regulator provides a stable 5V DC output from the input voltage, which is used to power the optocouplers and the BC547 transistors.
The Raspberry Pi Pico W is powered with 5V via Vbus and GND pin. Similarly to control the relay, we can use GP19, GP18, GP17 & GP16 pin of Raspberry Pi Pico W.
The four indicator LEDs are connected in parallel with the relay coils and light up when the corresponding relay is activated, providing a visual indication of which device is being controlled. The 5V DC power jack is the input power source that powers the entire circuit, and can be connected to a 5V DC power supply, such as a wall adapter or a USB port.
The various components work together to amplify the low-voltage control signal and switch the high-voltage load devices while providing protection and visual indication of the devices being controlled.
For testing and demo, you can use 4 LEDs as in the image below. They work same exactly like a 4 Channel Relay.
PCB Design, Gerber File & Ordering PCB Online
If you don’t want to assemble the circuit on a zero PCB or a breadboard and you want PCB for the project, then here is the PCB for you. I used EasyEDA to draw the schematic first. Then I converted the schematic to PCB. The PCB Board for this project looks something like below.
The Gerber File for the PCB is given below. You can simply download the Gerber File and order the PCB from ALLPCB at 1$ only.
You can use this Gerber file to order high quality PCB for this project. To do that visit the ALLPCB official website by clicking here: https://www.allpcb.com/.
You can now upload the Gerber File by choosing the Quote Now option. From these options, you can choose the Material Type, Dimensions, Quantity, Thickness, Solder Mask Color and other required parameters.
After filling all details, select your country and shipping method. Finally you can place the order.
Setting up Blynk 2.0 Application
To control the 4 Home Appliances using Blynk and Raspberry Pi Pico W, you need to create a Blynk project and set up a dashboard in the mobile or web application. Here’s how you can set up the dashboard:
Visit blynk.cloud and create a Blynk account on the Blynk website. Or you can simply sign in using the registered Email ID.
Click on +New Template.
Give any name to the Hardware. Choose the Hardware type as Other and the connection type as WiFi.
Click on OK so that the template is created successfully.
Now we need to create Datastreams. So go to the Datastreams section.
Select virtual Pin and name it Relay1. Select Virtual Pin as V1 and Data Type as Integer.
Repeat the same steps for other 4 datastreams as Relay2, Relay3 and Relay4.
Now we need to create widget for the dashboard.
Drag and drop 4 switch widgets on the Dashboard screen.
Click on the Setting option for Switch 1 and do the following setting as in this image.
Similarly set all 4 switches and do the settings with regard to Virtual Pin.
Now we need to create a Device for this project.
Choose from Template.
Choose the template you created earlier. Give any name to the Device.
Finally a New Device is created and you will see Blynk Authentication Token now. Copy this token as it is required in the MicroPython Code.
Finally our Web Dashboard is ready.
Using the Raspberry Pi Pico W, you can control 4 Home Appliances for your Blynk based Home Automation Project.
Source Code/Program
The code for Home Automation using Raspberry Pi Pico W Blynk 2.0 App is divided into two parts as BlynkLib.py and main.py. The controlling of LED requires Blynk Library for MicroPython.
BlynkLib.py
This library provides an API that enables connectivity between your IoT hardware, which supports Micropython/Python, and the Blynk Cloud. With this API, you can send both raw and processed sensor data and remotely control any connected hardware (such as relays, motors, and servos) from anywhere in the world using the Blynk mobile apps available on both iOS and Android.
Copy the following code and save it to your Raspberry Pi Pico W board with name ‘BlynkLib.py’.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
# Copyright (c) 2015-2019 Volodymyr Shymanskyy. See the file LICENSE for copying permission. __version__ = "1.0.0" import struct import time import sys import os try: import machine gettime = lambda: time.ticks_ms() SOCK_TIMEOUT = 0 except ImportError: const = lambda x: x gettime = lambda: int(time.time() * 1000) SOCK_TIMEOUT = 0.05 def dummy(*args): pass MSG_RSP = const(0) MSG_LOGIN = const(2) MSG_PING = const(6) MSG_TWEET = const(12) MSG_NOTIFY = const(14) MSG_BRIDGE = const(15) MSG_HW_SYNC = const(16) MSG_INTERNAL = const(17) MSG_PROPERTY = const(19) MSG_HW = const(20) MSG_HW_LOGIN = const(29) MSG_EVENT_LOG = const(64) MSG_REDIRECT = const(41) # TODO: not implemented MSG_DBG_PRINT = const(55) # TODO: not implemented STA_SUCCESS = const(200) STA_INVALID_TOKEN = const(9) DISCONNECTED = const(0) CONNECTING = const(1) CONNECTED = const(2) print(""" ___ __ __ / _ )/ /_ _____ / /__ / _ / / // / _ \\/ '_/ /____/_/\\_, /_//_/_/\\_\\ /___/ for Python v""" + __version__ + " (" + sys.platform + ")\n") class EventEmitter: def __init__(self): self._cbks = {} def on(self, evt, f=None): if f: self._cbks[evt] = f else: def D(f): self._cbks[evt] = f return f return D def emit(self, evt, *a, **kv): if evt in self._cbks: self._cbks[evt](*a, **kv) class BlynkProtocol(EventEmitter): def __init__(self, auth, tmpl_id=None, fw_ver=None, heartbeat=50, buffin=1024, log=None): EventEmitter.__init__(self) self.heartbeat = heartbeat*1000 self.buffin = buffin self.log = log or dummy self.auth = auth self.tmpl_id = tmpl_id self.fw_ver = fw_ver self.state = DISCONNECTED self.connect() def virtual_write(self, pin, *val): self._send(MSG_HW, 'vw', pin, *val) def send_internal(self, pin, *val): self._send(MSG_INTERNAL, pin, *val) def set_property(self, pin, prop, *val): self._send(MSG_PROPERTY, pin, prop, *val) def sync_virtual(self, *pins): self._send(MSG_HW_SYNC, 'vr', *pins) def log_event(self, *val): self._send(MSG_EVENT_LOG, *val) def _send(self, cmd, *args, **kwargs): if 'id' in kwargs: id = kwargs.get('id') else: id = self.msg_id self.msg_id += 1 if self.msg_id > 0xFFFF: self.msg_id = 1 if cmd == MSG_RSP: data = b'' dlen = args[0] else: data = ('\0'.join(map(str, args))).encode('utf8') dlen = len(data) self.log('<', cmd, id, '|', *args) msg = struct.pack("!BHH", cmd, id, dlen) + data self.lastSend = gettime() self._write(msg) def connect(self): if self.state != DISCONNECTED: return self.msg_id = 1 (self.lastRecv, self.lastSend, self.lastPing) = (gettime(), 0, 0) self.bin = b"" self.state = CONNECTING self._send(MSG_HW_LOGIN, self.auth) def disconnect(self): if self.state == DISCONNECTED: return self.bin = b"" self.state = DISCONNECTED self.emit('disconnected') def process(self, data=None): if not (self.state == CONNECTING or self.state == CONNECTED): return now = gettime() if now - self.lastRecv > self.heartbeat+(self.heartbeat//2): return self.disconnect() if (now - self.lastPing > self.heartbeat//10 and (now - self.lastSend > self.heartbeat or now - self.lastRecv > self.heartbeat)): self._send(MSG_PING) self.lastPing = now if data != None and len(data): self.bin += data while True: if len(self.bin) < 5: break cmd, i, dlen = struct.unpack("!BHH", self.bin[:5]) if i == 0: return self.disconnect() self.lastRecv = now if cmd == MSG_RSP: self.bin = self.bin[5:] self.log('>', cmd, i, '|', dlen) if self.state == CONNECTING and i == 1: if dlen == STA_SUCCESS: self.state = CONNECTED dt = now - self.lastSend info = ['ver', __version__, 'h-beat', self.heartbeat//1000, 'buff-in', self.buffin, 'dev', sys.platform+'-py'] if self.tmpl_id: info.extend(['tmpl', self.tmpl_id]) info.extend(['fw-type', self.tmpl_id]) if self.fw_ver: info.extend(['fw', self.fw_ver]) self._send(MSG_INTERNAL, *info) try: self.emit('connected', ping=dt) except TypeError: self.emit('connected') else: if dlen == STA_INVALID_TOKEN: self.emit("invalid_auth") print("Invalid auth token") return self.disconnect() else: if dlen >= self.buffin: print("Cmd too big: ", dlen) return self.disconnect() if len(self.bin) < 5+dlen: break data = self.bin[5:5+dlen] self.bin = self.bin[5+dlen:] args = list(map(lambda x: x.decode('utf8'), data.split(b'\0'))) self.log('>', cmd, i, '|', ','.join(args)) if cmd == MSG_PING: self._send(MSG_RSP, STA_SUCCESS, id=i) elif cmd == MSG_HW or cmd == MSG_BRIDGE: if args[0] == 'vw': self.emit("V"+args[1], args[2:]) self.emit("V*", args[1], args[2:]) elif cmd == MSG_INTERNAL: self.emit("internal:"+args[0], args[1:]) elif cmd == MSG_REDIRECT: self.emit("redirect", args[0], int(args[1])) else: print("Unexpected command: ", cmd) return self.disconnect() import socket class Blynk(BlynkProtocol): def __init__(self, auth, **kwargs): self.insecure = kwargs.pop('insecure', False) self.server = kwargs.pop('server', 'blynk.cloud') self.port = kwargs.pop('port', 80 if self.insecure else 443) BlynkProtocol.__init__(self, auth, **kwargs) self.on('redirect', self.redirect) def redirect(self, server, port): self.server = server self.port = port self.disconnect() self.connect() def connect(self): print('Connecting to %s:%d...' % (self.server, self.port)) s = socket.socket() s.connect(socket.getaddrinfo(self.server, self.port)[0][-1]) try: s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) except: pass if self.insecure: self.conn = s else: try: import ussl ssl_context = ussl except ImportError: import ssl ssl_context = ssl.create_default_context() self.conn = ssl_context.wrap_socket(s, server_hostname=self.server) try: self.conn.settimeout(SOCK_TIMEOUT) except: s.settimeout(SOCK_TIMEOUT) BlynkProtocol.connect(self) def _write(self, data): #print('<', data) self.conn.write(data) # TODO: handle disconnect def run(self): data = b'' try: data = self.conn.read(self.buffin) #print('>', data) except KeyboardInterrupt: raise except socket.timeout: # No data received, call process to send ping messages when needed pass except: # TODO: handle disconnect return self.process(data) |
main.py
Copy the following code and save it to the Raspberry Pi Pico W with name ‘main.py’.
You need to change the WiFi SSID, Password and Blynk Authentication Token on the following lines.
|
1 2 |
wlan.connect("SSID","Password") BLYNK_AUTH = '*****************************' |
Here is the complete code.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
import time import network from machine import Pin import BlynkLib wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect("SSID","Password") BLYNK_AUTH = '**************************' # Wait for network connection wait = 10 while wait > 0: if wlan.status() < 0 or wlan.status() >= 3: break wait -= 1 print('waiting for connection...') time.sleep(1) # Handle connection error if wlan.status() != 3: raise RuntimeError('network connection failed') else: print('connected') ip = wlan.ifconfig()[0] print('IP: ', ip) # Connect to Blynk blynk = BlynkLib.Blynk(BLYNK_AUTH) # Initialize the relay pins relay1_pin = Pin(19, Pin.OUT) relay2_pin = Pin(18, Pin.OUT) relay3_pin = Pin(17, Pin.OUT) relay4_pin = Pin(16, Pin.OUT) # Register virtual pin handler @blynk.on("V1") #virtual pin V1 def v1_write_handler(value): #read the value if int(value[0]) == 1: relay1_pin.value(1) #turn the relay1 on else: relay1_pin.value(0) #turn the relay1 off @blynk.on("V2") #virtual pin V2 def v2_write_handler(value): #read the value if int(value[0]) == 1: relay2_pin.value(1) #turn the relay2 on else: relay2_pin.value(0) #turn the relay2 off @blynk.on("V3") #virtual pin V3 def v3_write_handler(value): #read the value if int(value[0]) == 1: relay3_pin.value(1) #turn the relay3 on else: relay3_pin.value(0) #turn the relay3 off @blynk.on("V4") #virtual pin V4 def v4_write_handler(value): #read the value if int(value[0]) == 1: relay4_pin.value(1) #turn the relay4 on else: relay4_pin.value(0) #turn the relay4 off while True: blynk.run() |
Code Explanation
This Micropython code sets up a connection to a Blynk server using a WiFi network and controls 4 relays based on the user’s inputs from the Blynk app.
The code imports the necessary libraries such as time, network, machine, and BlynkLib. It sets up a WiFi network connection using the SSID and password provided. The code then waits for the network connection to be established and raises a RuntimeError if it fails.
The code initializes 4 relay pins using the Pin class from the machine library. It then registers four virtual pin handlers for pins V1 to V4 on the Blynk server using the @blynk.on() decorator. Each virtual pin handler function reads the value of the corresponding virtual pin and turns the corresponding relay on or off based on the value received.
Finally, the code enters an infinite loop and continuously calls blynk.run() to handle incoming data from the Blynk server. This allows the code to constantly monitor for changes in the virtual pins and control the relays accordingly.
Overall, this code sets up a connection to a Blynk server, controls 4 relays based on the user’s inputs, and continuously runs in an infinite loop to monitor for changes in the virtual pins.
Home Automation Testing & Demo with Blynk
Save the above code and run it on the Pico W board.
You can now test the Raspberry Pi Pico Home Automation Project using the Blynk web app. Open the web app and navigate to the project dashboard. Click on the button widget, and the LED or Relay should turn on.
Click it again, and the LED or Relay should turn off.
You can also control the LED or Relay using the Mobile Dashboard. Open the Blynk app and navigate to the project dashboard. Tap the button widget, and the LED or Relay should turn on. Tap it again, and the LED or Relay should turn off.
With these steps, you have successfully tested and demonstrated the Raspberry Pi Pico W Home Automation Project using the Blynk app. You can now use this project as a starting point to build more complex IoT projects using Blynk and MicroPython.





























