Personal IoT App with Blynk and Raspberry PI
Last Updated on 22nd March 2024 by peppe8o
Today I want to show you how to create a flexible IoT solution, fully customizable, with the open source Blynk platform and a Raspberry PI 3 model A+. The same procedure apply also to newer Raspberry PI computer boards.
IoT applications are spreading the world to give people control of their homes, garden, work and many other applications. IoT apps are often linked to products to buy and are strictly connected to product functions. Blynk, together with Raspberry PI, can make their access super simple and efficient.
What Is Blynk
Blynk is an open-source IoT platform, hardware agnostic, which enables users to create their own app layout and connect it to its own IoT hardware. It has a really awesome App interface (available both from Google Play and Apple AppStore) with a widget-based building system. You can create your own layout by simply dragging and dropping available widgets.
It works with an accounting system based on Energy Point. The free version offers an account with 2000 Energy Points which you can spend by adding widgets to your project. Every time you remove a widget, its Energy Point will go back to your Energy Balance.
Blynk is based on a client-server-IoT HW architecture, with the Blynk server managing connection and authentication between App and your Hardware.
What We Need
As usual, I suggest adding from now to your favourite e-commerce shopping cart all the needed hardware, so that at the end you will be able to evaluate overall costs and decide if to continue with the project or remove them from the shopping cart. So, hardware will be only:
- Raspberry PI 3 Model A+ (including proper power supply or using a smartphone micro usb charger with at least 3A) or newer Raspberry PI Board
- high speed micro SD card (at least 16 GB, at least class 10)
Check hardware prices with the following links:
Step-by-Step Procedure
Blynk supports many hardware languages. In this guide, I’ll use Python. This procedure will proceed in the following order:
- Install the Blynk IoT app on your Smartphone
- Configure the Blynk dashboards (both Web and Mobile)
- Install Raspberry PI OS Lite on Raspberry PI
- Run the first test
Install Blynk IoT App (NOT legacy) on your Smartphone
This step depends on your smartphone’s Operating System. Use your app store (Google Play for Android or AppStore for iOS) to locate and install the “Blynk IoT” app.
Create a Blynk Account
After the Blynk app is installed, you will need to create a new Blynk app account. This account will require a mail to register. This mail will be used later in the next steps also to receive an authentication token to connect your hardware to your App.
So, open your Blynk IoT app and tap on “Sign Up” button
In the next window, please read the Terms and Conditions and Privacy Policy. You will need to accept them by flagging the related option and fill your email address. Then tap the “Continue” button.
The next window will confirm that the authentication email has been sent. You will need to check your email.
You’ll receive the Blynk email that will provide you with a link to view the following web page that will ask you to create a password:
The following page will ask for your first name:
Then a brief tour will show you the main features of Blynk:
You can skip it in order to get to the dashboard.
Create a New Template
Blynk templates are a set of pre-defined parameters that are common to multiple devices. This helps when adding multiple devices of the same kind. Before adding a new device linked to our Raspberry PI, we’ll create its template.
At any time, you can go to the templates page by clicking the related icon at the left bar (highlighted in the following picture). The very first time, when no templates are available, you will be warned and linked with a “New Template” button on the first page. In both cases, identify and click the “New Template button”.
Please fill the template details like name and description according to your preferences. Use the “Raspberry PI” option in “Hardware”. Then, click “Done”:
Once the Template is generated, you can set the default widgets to see on both web and mobile dashboards. Please remember that from your web console you can set the widget on Web Dashboard, while from Blynk IoT mobile app you can set the Mobile Dashboard widgets.
So, please select the Web Dashboard:
On your Web Dashboard page, please scroll down the “Widget Box” and identify the “Label” widget:
A double click on the Label widget will add this widget to your dashboard:
By moving the mouse over the new Label widget, it will show more options such as creating a copy, setting and deleting:
Please use the weel icon on it to enter the label widget settings window. Here you can define what will appear on top of the value we’ll update from our Raspberry PI. So, set the “Title” as you like and then press the “Create Datastream” button and select “Virtual Pin”:
The DataStreams are data connections that allow the endpoint device to send its data to Blynk, by keeping a reference (for example, the Virtual Pin Datastream will be named “V0”, “V1”, “V2” and so on). Please set the Datastream to “V1” and the Datastream type to “String”, as in the following picture:
You can now click the “Save” button on the bottom-right side of this window. You can also save the template with the following “Save” button:
Create a New Device
It’s time to associate a device (our Raspberry PI) with the Blynk template.
Use the glass icon on the left menu to reach the device search and then use the resulting “+ New Device” button to add a new device:
Click “From Template” in order to create the new device from the just saved Template:
In the new device creation, please set as Template the one just created. Then you can give your preferred name to this device. The click create:
After the device is created, a window on the right side will show the authentication info to connect from your Raspberry PI to the Blynk dashboard. With this tutorial, what will be important is the “BLYNK_AUTH_TOKEN” value. Keep it noted as it will be required later:
Create Blynk IoT App Dashboard on your Smartphone
After finishing the Web Dashboard, it’s time to move to the mobile side. As said, the Blynk Mobile Dashboard can be set only from the Blynk IoT App. So, go back to your smartphone and use the left arrow icon to go to the App login:
Here, please fill-in your email address and password to log in and reach the mobile dashboard:
Please use the “hamburger” icon (the three horizontal lines on the top-rigt) to open the side menu:
From here, please tap the “Developer Mode” link (we already have the device as we created it from the Web Console):
Tap the Raspberry PI Template (or whatever you created as your Raspberry PI template). You will enter the Template in Development mode. But this development mode only sets the mobile presentation of your project. At the start it will be empty:
Use the “+” button on top-right side of the page to open the list of Widgets that we can add. Scroll down untill you find the “Labeled Value”
Tap on it to add to the Dashboard.
As for the unhappy choice of colors, you may not clearly see it added. Paying more attention, you will find it in the form of a white square on top-left side of the dashboard:
Tap the label widget to enter its setting up:
Now, tap the “Choose datastream” button to enter the datastream configuration page:
Create a Virtual Pin Datastream with the related button and configure the Virtual Pin with the “V1” index. Also configure the Data Type as “String”, to get a configuration like the one shown in the following picture. Also set the Name and Alias to your favourite (“V1 string” in my case). Then click the “Done” button on top-right side of the page:
The following page will result in your label settings overview and you can click the “X” button on the top-left side of the page to go back at the app dashboard:
Our label is now created and configured:
With the same process, please add a Button associated to a “V2” Virtual Pin datastream, with Datatype “Integer” and max value to “1”:
Back to the Button configuration overview, please set the Mode to “Switch”:
Exit from the Dashboard and from the Developer mode to reach the Blynk IoT main page. It will show the button (by default, it is off). The label, even if present, will not be shown until no data are received
Configuration summary
Finally, just to resume what we’ve configured, we have:
- on Web Dashboard a Label widget set to V1 datastream
- on Mobile Dashboard a Label widget set to V1 datastream and a Button set to V2 datastream
So, the V1 Virtual Pin will be uploaded from our Raspberry PI to both our dashboards (Web and Mobile). The V2 Virtual Pin will be set from our Mobile dashboard via the button and will be read from our Raspberry PI.
These 2 Pins will show how to use both uplink and downlink communication between Raspberry PI and Blynk.
Prepare your Raspberry PI for Blynk
Please refer to my Raspberry PI OS Lite tutorial for OS installation. We’ll configure Raspberry PI from remote with an SSH terminal shell.
Be sure your OS is up to date. From terminal:
sudo apt update -y && sudo apt upgrade -y
Python is pre-installed in Raspberry PI OS Lite, as you can verify by typing:
pi@raspberrypi:~ $ python --version
Python 3.9.2
We’ll need the pip package to install the Python requests module, as this will allow us to use REST communication. The following two terminal commands will do the job:
sudo apt install python3-pip
python3 -m pip install requests
You can now get a copy of my Blynk script directly in your Raspberry PI computer with the following terminal command:
wget https://peppe8o.com/download/python/blynk/restblynk.py
The following will explain my code.
At the first line, we import the requests module:
import requests
Then we associate the token to a variable. Please fill there with your token get at the device creating time:
token="Add-Your-Device-Token-Here"
Here I prefer to manage the write (upload) and read (download) process by using custom functions so that the usage will be highly simplified as we’ll see later.
The first custom is the write() function, which allows the Raspberry PI to write a value to any virtual Pin on Blynk. It gets as input the token value, the Virtual Pin number and the value to write.
We’ll compose the API URL according to the Blynk REST documentation. The Blynk cloud service answers with only 2 possible results: the code “200” means that everything worked correctly, while the code “400” means that something went wrong. So, my custom function is the following:
def write(token,pin,value):
api_url = "https://blynk.cloud/external/api/update?token="+token+"&"+pin+"="+value
response = requests.get(api_url)
if "200" in str(response):
print("Value successfully updated")
else:
print("Could not find the device token or wrong pin format")
The read function is similar to the previous one, but this reads a Widget value and returns it to our Python program. Of course, it requires only the token and the Pin value:
def read(token,pin):
api_url = "https://blynk.cloud/external/api/get?token="+token+"&"+pin
response = requests.get(api_url)
return response.content.decode()
With these functions, writing a virtual Pin will be as simple as the following line:
write(token,"v1","150")
And reading a Virtual Pin will result as the following:
button=read(token,"v2")
print(button)
You can find the official Blynk REST documentation at https://docs.blynk.io/en/blynk.cloud/device-https-api.
Run the restblynk.py Script
Finally, execute this script. From
python3 restblynk.py
The result will be the following:
pi@raspberrypi:~ $ python3 restblynk.py
Value successfully updated
0
The first line means that it has successfully uploaded the “150” value to our labels and the “0” is the value read from the button (OFF=”0″ and “ON”=1),
From our web dashboard, the result will be the following:
While on your Mobile Dashboard you will have the following:
Of course, on the Mobile Dashboard, if you tap the button switching it to ON, running again the script will result in the following terminal result:
pi@raspberrypi:~ $ python3 restblynk.py
Value successfully updated
1
Enjoy!
How to activate on-off module in the python script?
Hi Zack,
I think that you may find useful my Weather station with Arduino, Blynk and Raspberry PI Zero W/ tutorial to better understand how to configure python scripts with widgets
Hello, I’ve been tasked to replicate and improve your Project regarding “WEATHER STATION WITH ARDUINO, BLYNK AND RASPBERRY PI OS LITE ON RASPBERRY PI ZERO W” but i’ve encoutnered mutiple errors, afew of them being
1. Traceback (most recent call last): import Blynklib
2. module = self._original_import(*args, **kw)
ModuleNotFoundError: No module named ‘BlynkLib’
I have been struggling with this issue and i hope you will be able to hhelp
I have afew errors and im still fairly new to raspberry but for a project i had to replicate and improve your weather station raspberry project
1. Traceback (most recent call last): import BlynkLib
2.module = self._orginal_import(*args, **kw)
ModuleNotFoundError: No module name ‘BlynkLib’
Hi Charlie,
I’m currently in holidays but in next daysI will try to find what happened.
My project is due in afew days, im hoping that if you are free you could help. But do no fret afterall this is my issue, Do enjoy your vacation have a wonderful time
In the meanwhile, what does following command returns to you?
pip install blynk-library-python
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Requirement already satisfied: blynk-library-python in ./.local/lib/python2.7/site-packages (0.2.0)
This is the what it says
Ok, this is a good news as Blynk seems correctly installed.
Now, do you use “python myBlynkTest.py” command or “python3 myBlynkTest.py”? The first one is the correct
i used the command python myBlynkTest.py as per your guide and it shows the “BLYNK for python V0.2.0 (Linux) Started!’
but it says Invalid auth token rigth after
I know you are on vacation and i really hope i am not troubling you to much, but is there any way to better contact you besides using this comment area. Im still a student and completly new to raspberry pi and blynk. So thank you for your help
Write me at giuseppe@peppe8o.com
Can this project works on Raspberry Pi 4 Model B?
Sure! If you intend Raspberry PI 4 instead of RPI Zero W. RPI 4 model B can’t be used instead of Arduino as the RPI hasn’t analog GPIOs