Friday, November 27, 2026

Receiving messages from Whatapp with a Pico W and Micropython

For an index to all my stories click this text

Long time ago, I wrote about Callmebot. A service that allows you to send messages from your microcontroller (ESP32 or Raspberry Pi Pico) to Whatsapp. You can find that story here: https://lucstechblog.blogspot.com/2021/05/esp8266-and-esp32-sending-messages-to.html


Last time I wrote about a similar service which is my favorite now. It's called Whatabot. 
You can find it's homepage here: https://whatabot.io/

The idea is the same but Whatabot offers something extra. To use this service you need to create an account to obtain an API key. It's easy and the first 200 messages are free !! I urge you to read that story because this story leans heavily on it. You can find the story here:
https://lucstechblog.blogspot.com/2026/09/send-messages-to-whatsapp-with-pico-w.html

From Whatsapp to your microcontroller.

The previous story showed how to send text and data from your Raspberry Pi Pico to Whatsapp. I used a MicroPython program for that.

This time I am going to show you how to send data and text from Whatsapp to your microcontroller. For this I created a special websocket client library. This is especially written in MicroPython for the Raspberry Pi Pico W.

The library

Copy the code below.
Then paste it into an empty tab in Thonny and then save it in the lib folder on your Raspberry Pi Pico.
Please make sure to save it using the name websocket_client.py 

import uasyncio as asyncio
import ubinascii
import urandom
import usocket as socket
import ssl

class WebSocketClient:
    """ Minimal async WebSocket client with SSL support for Pico W. """

    def __init__(self, url, headers=None):
        self.url = url
        self.headers = headers or {}
        self.reader = None
        self.writer = None

    async def connect(self):
        proto, host, path = self._parse_url(self.url)
        port = 443

        # ---- TCP socket ----
        addr = socket.getaddrinfo(host, port)[0][-1]
        sock = socket.socket()
        sock.connect(addr)

        # ---- SSL wrap ----
        sock = ssl.wrap_socket(sock, server_hostname=host)

        # Bind to uasyncio
        self.reader = asyncio.StreamReader(sock)
        self.writer = asyncio.StreamWriter(sock, {})

        # ---- Generate Sec-WebSocket-Key ----
        key_bytes = bytes([urandom.getrandbits(8) for _ in range(16)])
        key = ubinascii.b2a_base64(key_bytes).strip().decode()

        # ---- Handshake ----
        req = (
            "GET {} HTTP/1.1\r\n"
            "Host: {}\r\n"
            "Upgrade: websocket\r\n"
            "Connection: Upgrade\r\n"
            "Sec-WebSocket-Key: {}\r\n"
            "Sec-WebSocket-Version: 13\r\n"
        ).format(path, host, key)

        for k, v in self.headers.items():
            req += "{}: {}\r\n".format(k, v)

        req += "\r\n"

        await self.writer.awrite(req)

        # ---- Read handshake response ----
        status = await self.reader.readline()
        if b"101" not in status:
            raise Exception("Handshake failed: " + status.decode())

        # Skip headers
        while True:
            line = await self.reader.readline()
            if line == b"\r\n":
                break

    async def send(self, msg):
        payload = msg.encode()

        await self.writer.awrite(bytes([0x81]))  # FIN + text frame
        ln = len(payload)

        if ln < 126:
            await self.writer.awrite(bytes([ln]))
        else:
            raise Exception("Payload too large")

        await self.writer.awrite(payload)

    async def recv(self):
        hdr = await self.reader.readexactly(2)

        opcode = hdr[0] & 0x0F
        length = hdr[1] & 0x7F

        if length >= 126:
            raise Exception("Extended lengths unsupported")

        data = await self.reader.readexactly(length)
        return data.decode()

    def _parse_url(self, url):
        if not url.startswith("wss://"):
            raise ValueError("Only wss:// URLs supported")

        no_proto = url[6:]
        parts = no_proto.split("/", 1)
        host = parts[0]
        path = "/" + parts[1] if len(parts) > 1 else "/"
        return "wss", host, path

This is obvious a long and complicated code. It took me quite some time and effort to create it. Explaining it would take a lot of space on this weblog, so I am not going to do that.
Just copy it and save it in your Pico's lib folder using the name websocket_client.py

The program for recieving Whatsapp messages.

Next to the library we need a program that opens a websocket and constant listens for incoming commands. Here is that program.

import uasyncio as asyncio
import ujson
from websocket_client import WebSocketClient  # use the class above

import network
import time
import gc

gc.enable()
gc.collect()
print("Start memory free: "+str(gc.mem_free()))

ssid = "YOUR-ROUTERS-NAME"
pw = "PASSWORD"

print("Connecting to wifi...")

# wifi connection
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(ssid, pw)
print('Waiting for connection.',end="")
while wifi.isconnected() == False:
    time.sleep(1)
    print('', end='.')
print("")

ip = wifi.ifconfig()[0]
print("Connected with IP adress : "+ip)

class WhatabotRealtimeClient:
    def __init__(self):
        self.api_key = "YOUR-API-KEY"
        self.chat_id = "YOUR-PHONE-NUMBER"
        self.url = "wss://api.whatabot.io/realtimeMessages"

        self.connect_message = (
            ujson.dumps({"protocol": "json", "version": 1}) + '\u001e'
        )

    async def run_websocket(self):
        while True:
            try:
                print("Connecting...")

                ws = WebSocketClient(
                    self.url,
                    headers={
                        "x-api-key": self.api_key,
                        "x-chat-id": self.chat_id,
                        "x-platform": "whatsapp"
                    }
                )

                await ws.connect()
                print("Connected!")

                await ws.send(self.connect_message)

                while True:
                    msg = await ws.recv()
                    await self.handle_message(ws, msg)

            except Exception as e:
                print("ERROR:", e)

            print("Reconnecting in 10 seconds...")
            await asyncio.sleep(10)

    async def handle_message(self, ws, message):
        message = message.rstrip('\u001e')

        try:
            data = ujson.loads(message)
        except:
            print("Invalid JSON:", message)
            return

        target = data.get("target")
        args = data.get("arguments")

        if target == "ReceiveMessage" and args:
            txt = args[0]
            up = txt.upper()

            # --- your command handling ---
            if up == "START":
                print("Starting…")
            elif up == "STOP":
                print("Stopping…")
            elif up == "PAUSE":
                print("Pausing…")
            elif up == "RESUME":
                print("Resuming…")
            else:
                print("Unknown:", txt)

            # reply
            reply = ujson.dumps({
                "type": 1,
                "target": "SendMessage",
                "arguments": [f"Pong: {txt}"]
            }) + '\u001e'

            await ws.send(reply)
            print("Sent:", reply)


asyncio.run(WhatabotRealtimeClient().run_websocket())

Again I am just giving you the program without an explanation as that would take up to uch space.

I do want you to pay special attention to the following lines:

ssid = "YOUR-ROUTERS-NAME"
pw = "PASSWORD"

You will need to replace these with your actual routers name and password.

class WhatabotRealtimeClient:
    def __init__(self):
        self.api_key = "YOUR-API-KEY"
        self.chat_id = "YOUR-PHONE-NUMBER"
        self.url = "wss://api.whatabot.io/realtimeMessages"

Further on in the program you need to replace these with your actual API key and phone number.

How does it work in real life.

In Whatsapp look for your Whatabot contact.


I am using the Whatsapp web version here for easily making screenshots.


Click on that contact and the message screen opens.

Now make sure the Raspberry Pi Pico W is running the above program and is connected to Whatabot.


Thonny's shell shows when there is a firm connection to Whatabot.


You can now type anything you like in Whatsapp and it will be send to your Raspberry Pi Pico W. Here I am sending: this is a test from Whatabot

And this is what your Raspberry Pi Pico receives.

Unknown: This is a test from whatabot
Sent: {"arguments": ["Pong: This is a test from whatabot"], "type": 1, "target": "SendMessage"}


At the end of the program you'll find this code:

        if target == "ReceiveMessage" and args:
            txt = args[0]
            up = txt.upper()

            # --- your command handling ---
            if up == "START":
                print("Starting…")
            elif up == "STOP":
                print("Stopping…")
            elif up == "PAUSE":
                print("Pausing…")
            elif up == "RESUME":
                print("Resuming…")
            else:
                print("Unknown:", txt)

This is where I provided some words that are filtered by the program to help you getting started.


In this example I send the word "start"


Then the Pico reacts with the word Starting.

You can replace this easily with your own commands like "Lamp on", "Lamp off", "Fan on", "Fan off" etc. etc.
You can then add your desired action after the print command.

How many credits left

As said before you get credits with your free account.
200 Credits to send from your microcontroller to Whataspp
100 Credits to send from Whatsapp to your microcontroller

You can send a command to Whatabot to show how many credits you have left:


The command is : "Remaining messages"

As you can see I can still send 191 messages from my Pico to Whatsapp and receive 96 messages.

Multiple Raspberry Pi Pico's or ESP's ????

Well I still have to do some testing but I presume it would be possible to have multiple Raspberry Pi Pico's sending data to Whatsapp and multiple other Raspberry Pi Pico's receiving messages.

I should also be possible to combine the send and receive program into one. So a single Raspberry Pi Pico would be able to send and receive commands to Whatsapp.

However I would recommend using another service as intermedeair if you need to send a lot of messages. Dweet for example would be better suited for that. You can read about Dweet here: https://lucstechblog.blogspot.com/2025/08/dweet-is-dead-long-live-dweet.html

That's it for now.
Till next time
have fun !

Luc Volders

Thursday, November 5, 2026

Web apps explained

For an index to all my stories click this text.

My last post regarding my new book raised some questions from readers of this weblog.
So I am going to explain what web apps are as clear as possible.



You have an idea for building a program. That can be anything: something for your family, a business application, a game etc. etc.
Let's say your main computer is a Windows machine. So you start building your program on that.

The platform dilemma; Android, IOS, Windows or Linux.

However a program that runs on a Windows computer will not work on a Linux machine or an Apple. And it certainly will not work on Android phones/tablets or Apple pones/tablets. That might not be a problem if you build your program for a small group of people you know personally. You will know what kind of computers they own.
But what if your program will be used by a larger group. Like the club you are a member of, or customers from a company. You might not even know how may users will use the program and on what platforms. And some even might not have a desktop machine anymore !!

So that's your first problem: for what platform will you develop.
Of course you can develop for all these platforms, but then you need to learn all kinds of programming languages. Android apps use Java or Kotlin, Apple uses Swift for it's phones and Objective C for it's desktop computers. For Windows computers you can write in C# (.NET) and you can use C++ for Linux. Anyway: you need to learn a lot of different languages.

This is where web apps make life easy !!!
You just have to learn one language: Javascript.
For good looks add some simple HTML and CSS code and you're done !!

You can write your program on a Windows machine and it will run happily on an Apple, Linux computer, an Android Phone or an Iphone. And that works the other way around to. My main computer is a Raspberry Pi5 running Linux and I build web apps that run on my phone, Iphones and on Windows and Apple computers !!

Imagine being able to write a program just once and it runs on every device !!!


To build web apps you need expensive equipment (and software).

No, no, no !!
You can develop web apps on any computer that has a simple editor.
I write my apps on a Linux machine (a Raspberry) with Kate. On Windows you could even use Notepad. TextEdit on a Mac does the job equally well.


So web apps are webpages ??

You might wonder if web apps are just simple web pages that run in your browser.

 
The above picture shows a JavaScript program running in a browser


And this is how the same program runs as a web app !! No browser window. Just a program window like most programs have.
 

Not so!! Web apps can be as complicated as you like. With multiple pages, data collecting and sending data to sites (or home automation systems) and whatever you can think off.
And best of all they run in their own window. So they do not look like websites.

To make a html page with javascript behave like a normal app you need to add a few things. First you need to supply an icon and then there are two small additional programs needed which are easy to make: a manifest and a service worker.

No Wifi and no cookies

Web apps can run completely off-line. You do not need wifi or mobile data to run a web app.  And even better: there is no need for cookies.
So your web app can keep users completely anonymous !!!

However when you build a web app that needs real time information like weather forecasts, stock market prices, or access to your sensors for home automation then you need to activate wifi or mobile data.

A normal program or app has its own icon.

Web apps come with their own icons. You can design your own icon or download one from one of the many websites that provide them. Just like you would for any app for your phone or computer program. 

 



 

 

 

 

 




The picture on the left shows the clock icon on an Android Phone and the picture on the right on a Linux computer screen. Same app !!! No modifications !! Program once run everywhere !! 

Just click the icon and the web app starts. And best of all: looking at the icon will not tell you if it is a native program or a web app. So most users will even never know that they are using a web app.

How about updates.

If you build a program and there are just a few users, you can mail them when there is a new update. Or you can put a new version on your website and hope they will look at the site and update.

Web apps have a build in update mechanism.
A web app is stored on a website. When you, as a developer, upload a new version all users will automatically get an update !!

Distribution

Maybe you have heard that Google is restricting app distribution. If you are a new developer and want to put your app on the Play Store you first have to have it tested for 14 days by 12 testers. This is mandatory !!! There are now even websites where you can hire (for money) testers to tackle this problem.
Besides that you will need a developer account and that will set you back 25USD (one time fee).

And it gets worse. On this weblog are some Apps I build for Android and they are downloadable from a website. On your Android Phone you donload them, click on them and Android asks if it should install the app. This is called sideloading. And guess what: in the new Android updates this will be turned off. There goes your freedom !! And even worse: alternative app stores like Fdroid, apkmirror and apkpure will be out of business. You just can not simply download app's from these and install them.
Yes I know there will be a way to keep sideloading but that is so complicated and deeply hidden in Android that no ordinary user will use it.
This implies that you can not simply build an APP for Android and distribute it from your own website, by mail or alternative play stores !!

For Apple's apps this gets even worse. You need a developer account and that will set you back 100USD a year !!! Then your app needs to confirm to their rules concerning looks and behaviour.

And when all this is solved you app is one of the approximately 2.5 million apps on either one of these stores.

For web apps there are no rules!! And there is no developer account required.
Anyone can build web apps and distribute them through their own website. And if you do not own a website: no worries there are plenty free distribution methods available.
And at the moment there are even several web app stores around.

Yet for Windows, Linux and Apple computers there are no web stores. And still people find their way to the millions of available programs. So if your marketing is OK (or have a great solution for a problem) people will find your web app anyway.

Web apps are about freedom.

Who paid for that phone or computer. So who owns it ??
And if you are the owner YOU should decide what you can install and not the manufacturer !!!

Suppose we had this in other parts of our life. Like you buy a car and the manufacturer decides what brand of fuel you can use. Not just what kind of fuel but also what brand ! Nobody would accept that. So why should we accept that with our phones and computers.

Summarising:
- you do not need expensive equipment
- you do not need expensive software
- you only have to learn one programming language
- write once, run everywhere on all platforms
- web apps look like normal apps in their own window
- web apps have their own icons
- updates can be done automatically
- web apps can run stand alone without wifi
- you can guarantee your users privacy (no cookies)
- you do not need developer accounts
- you do not have to comply to app store rules
- there are many easy ways for distributing your web apps


All these points (and more) are addressed and explained in my book.
My book is a hands on, do it yourself, tutorial that shows how to build web apps yourself. By buying the book you will get your freedom as a developer back.

The book: Web Apps simplified

The books starts with a small Javascript program. Then that program is turned into a web app. Next the book shows easy ways for distributing the web app. And bit by bit the app is expanded with more functionality. And each time a new functionality is added the web app on your phone and computer are updated automatically !! There is a large chapter describing the extra functionality a phone offers like taking pictures and videos, working with the GPS, getting names and addresses from your contact lists, using the gyro etc. etc. etc.

By reading the book and following the  chapters you will learn step by step how to build programs that run on every platform on and offline !!

 


The book is at this moment (internationally) available through Lulu.com

 

Have fun building apps !!
Till next time

Luc Volders 

Friday, October 23, 2026

Vibration detecting with the MPU6050

For an index to all my stories click this text.

When I was working at my project for the Caravan/Mobile-home leveler (previous story on this weblog) I had an idea. What if we could use the data from the MPU6050 to detect vibration or mechanical movement.

The breadboard setup.

This is the same setup as I used in my stories about the caravan / mobile-home leveling aid.



This should not pose any problems and you can easily build this on a breadboard.
Just make sure that the SCL pin from the MPU6050 is attached to pin 5 (D1) of the ESP8266 and the SDA pin is attached to pin 4 (D2).

As this is so simple you can use any other microcontroller, like an ESP32 or Raspberry Pi Pico, to build this project. You even do not need to make alterations in the program except for the pin numbers.

MicroPython program

from machine import Pin, I2C
import time
import math
from lucsmpulib import init_mpu, get_data

i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000) # esp8266
init_mpu(i2c)

totz = 0
i = 0

# Calculate the average value of z
for i in range (20):
    x, y, z = get_data(i2c)
    totz = totz + z

average = totz / 20
print(average)

# use a margin
great = average + 0.017
less = average - 0.017


while True:
        x, y, z = get_data(i2c)
        if z > great or z< less:
            print("vibration detected ",z)
            time.sleep(.5)
        time.sleep(.2)


The idea is simple.

First a measurement is done 20 times and from that the average value for z is calculated.

Then we add a margin to the average value and call that great and we subtract the same value from average and call that less.
I used a margin of 0.017 but you will need to do some tests and adjust it to your own circumstances.

Inside the while loop we constant read the value of z and test if it is greater then the value of great or smaller as the value of less and if that is the case: vibration is detected.

Each time after vibration is detected we wait for .5 seconds to make sure everything is settled down before we take another reading.

This program is just a framework. You need to write additional code to make this useful like adding a led that lights up when vibration is detected. Or send a notification to your phone. I am sure you can find some purpose for this.

The MPU6050 library

To use this program you will need my own MPU6050 library. I discussed that in the story about the caravan / mobile-home leveling aid. But for your convenience I add it here:

'''
Luc Volders library for MPU6050
'''

from machine import Pin, I2C
import time

def init_mpu(i2c, address=0x68):
    i2c.writeto_mem(address, 0x6B, b'\x00')
    time.sleep_ms(100)
    i2c.writeto_mem(address, 0x19, b'\x07')
    i2c.writeto_mem(address, 0x1B, b'\x00')
    i2c.writeto_mem(address, 0x1B, b'\x00')
    i2c.writeto_mem(address, 0x1C, b'\x00')

def read_data(i2c, addr, address=0x68):
    high = i2c.readfrom_mem(address, addr, 1)[0]
    low = i2c.readfrom_mem(address, addr + 1, 1)[0]
    value = high << 8 | low
    if value > 32768:
        value = value - 65536
    return value

def get_data(i2c):
    readx = read_data(i2c, 0x3B) / 16384.0
    ready = read_data(i2c, 0x3B + 2) / 16384.0
    readz = read_data(i2c, 0x3B + 4) / 16384.0

    return readx, ready, readz


That's all for now.
Till next time


Luc Volders


Saturday, October 10, 2026

Web Apps simplified - My new book is now available

For an index to all my stories click this text

Something new......................................

 


At this moment available through Lulu.com.

In a few weeks also available through Amazon.com

For those who do not know what web apps are. Here is a (very) short description on what they are. And I am very exited about this.

As you know an app that works on Android will not work on IOS and certainly will not work on Windows, MacOS or Linux. They all have their own languages and operating systems. 

But if you build a Web App it runs on EVERY system.

This book shows how to build web apps. Write your program once and it runs on all devices and is easy to test, and to distribute (no app stores needed) to friends, family, club members and customers.

This is about getting your freedom back as a developer.
And it saves loads of time: develop once, run everywhere.

I bet you know about Apple's restrictions for developers. And Maybe you already know about the restrictions Google already is imposing and going to expand on developers.
Web Apps beats these. 

The book is NOW available through Lulu.com (click here)
And in a few weeks it will also be available through Amazon

For those that want to learn more about this subject. Just keep following this weblog as I will be posting more on web apps in upcoming stories.

This sure is fun !!!

Luc Volders



Thursday, October 1, 2026

Quick testing of webpages with Netlify

For an index to all my stories click this text

At the moment I am writing a lot of small Javascript programs. The reason is that I am heavily into PWA's. For those in the dark: A PWA is a program that runs on desktop computers (Windows, Linux and Apple) and also on tablets (Android and IOS) and mobile phones (Android and IOS). So you write one program and it runs on all systems !!! That saves a lot of developing time. Magic !!

Next to that you do not need a developer account (25USD once for Google and 99USD yearly for Apple), you do not need to publish through the app stores. And becoming a new developer with Google means you need to find 12 testers that test your app for 14 days !!  Even better you do not need to comply to their rules !!!
PWA's means getting your freedom as a developer back !!!

The programming language for PWA's is Javascript.
Actually I am writing a book about this. If you are interested in a book on this subject drop me a note. 

So I am writing a lot of small Javascript programs. And I want to test them.
Testing Javascript is actually easy. Just put it into an HTML file and open it in your browser. It will work immediately. And opening the developer console in your browser (More tools==>Web Developer Tools==>Console) you can even see what's wrong if there is a bug in your code.

Sidenote.

Javascript is a fun language which is not very difficult to learn. And you get instant results in your webbrowser. The language is useful for all kinds of projects, including IOT projects of which you find several on this weblog.
To make programming in Javascript easier I collected over 500 tips and tricks and bundled them in a book. The book is distributed world-wide by amazon.com



Click here to learn more about this book or order it


And sometimes I want to test these programs running from a real webserver.
In 2024 I wrote a story on a small reaction game I developed. It is pure vanilla Javascript (no frameworks and no libraries) and works surprisingly well. The source code for the game is in the story. You can find it here: 
https://lucstechblog.blogspot.com/2024/03/javascript-reaction-game.html

I used Github to store the html code and turn the Github repositry into a webpage. You can do the same. I have written how to do that in this story:  
https://lucstechblog.blogspot.com/2023/07/using-github-for-building-website.html

But to do so the first step is to create a Github repository. Then upload your html code. And then turn that repository into a website. All in all this takes a bit of time. And in the end you have a lot of repositories that you might not need so you have to delete them all again.

And then I found an easy way to get a temporary website.

Netlify Drop

Netlify is a company that offers a lot of webservices. And one of these services is Netlify Drop.
You can use this for free and you even do not have to log in !!!!


Just put your HTML file with CSS and Javascript in a folder on your computer. I made a folder called React-game (while writing this story). 
For those wondering: I am running Linux on my computer (actually a Raspberry Pi5) but don't worry this will work on Windows equally well !! And as I am not getting sponsored I do not have a Mac so I can not test that.


In that folder I put my reaction game HTML file. Do remember to rename the HTML file to index.html because every websites starting point is the file index.html.

Next open your webbrowser (I am using Firefox) and visit:
https://app.netlify.com/drop


Drag your folder with your test program to the webpage and you are done !!!


The folder is uploaded to Netlify and after a few seconds (depending on the size of your program and the number of files) the screen alters.

Your site is now alive. The name is at the top in a different color (green-blue) and in this example is:
https://dynamic-bunny-771e26.netlify.app

You can copy this name and put it in your browsers address bar. You can also just click on the name and the site will open.


The site is password protected. But in this case that is just a way to keep bots out cause the password for each site is the same: My-Drop-Site
The password was shown in the first screen where it mentioned that your site is alive !!

Just paste that name in and press the submit button and your site opens and can be tested.





Try it yourself.

Create a new folder on your computers storage.
Then copy the code from my reaction game from here:
https://lucstechblog.blogspot.com/2024/03/javascript-reaction-game.html
Or use your own HTML creation.
Just paste it in any editor and then save it as index.html in the just created folder.
Drag the folder to https://app.netlify.com/drop and you are off to the races.

Any Caveats ????

Well yes there are some things to consider.

First the name of your site is not something you will easily remember. In this example like you can see it is: https://dynamic-bunny-771e26.netlify.app/
So copy and store that name somewhere if you need to use it frequently.

And that is the other caveat: your site will only be available for one (1) hour.
Now one hour does not seem a lot, but remember that a single html file is loaded in the memory of your browser and will stay there operational until you close the browsers tab.

The sunny side

Your code will be removed after an hour. So anybody looking at this website now will get a page not found error or likewise. So your code is rather safe.,

You can use this many times a day for testing different websites. So you can test a lot, before making a real production site for it.

Long-time usage.

Sometimes a one hour test period is not enough.
If you need more just go to the Netlify webpage: https://www.netlify.com/
Sign up. Start a new project and dump your folder in it.
The, this way, created site will last for ever.

Netlify will grant you (at this moment) 300 credits per month for free. Each website you create this way will cost 15 credits. So effectively you can create 20 websites each month however........

Every GB of data that is transferred will cost you 10 credits. So if you have loads of people visiting your test-site that will cost a lot of credits. For small sites like my reaction game (which is only 1K) a GB will go a long way.

When you run out of credits your sites are put on hold till the next month.
Of course you can have paid subscriptions with a lot more credits.

Concluding

For quickly testing small websites this is a great solution.
The one hour limit is in my test phase not a problem and for some long time testing purposes I have made an account and applied some test sites that way.

The only reservation I have is that this is again a cloud based service and I have seen quite a few of these services suddenly limiting the free tier or stopping alltogether.
So to be really safe I am building my own webserver on a humble Raspberry Pi3. But that's for another story.


Till next time
have fun

Luc Volders

Friday, September 18, 2026

Getting the time with timezone and DST in MicroPython

For an index to all my stories click this text

April 2023 I published a story on this weblog that showed how to get the right time with MicroPython. You can read that story here:
http://lucstechblog.blogspot.com/2023/04/getting-right-time-with-micropython.html


The provided solution gets the actual time from an NTP server. There is only a small problem with this. The NTP server gets the UTC time. UTC stands for Universal Time Coordinated which is the same as GMT. And I am living in the Netherlands which is at CEST which stands for Central European Summer Time.

And of course there is a time difference between UTC and CEST time. Normally that does not pose a problem. But then I had a question of one of the readers on this weblog. On my Discord server he asked how to write a program that performs a daily task every day at the same time.

The program I provided in that story about getting the right time, did not take time zones and summer and winter time (DST) adjustments in account.
So I had some work to do as I did not want to disappoint him.

Time zones.

As I can not now where you are located you do have to fill this in manually. You can find your timezone easily by googling it.

In the new program which you find below there are two lines that look like this:

#adjust for timezone Netherlands
local_time = time.localtime(time.mktime(local_time) + 3600)

The Netherlands is in timezone UTC + 1 hour. This line adds 3600 seconds to the local_time which is one hour. If you are for example at timezone UTC+3 just alter 3600 in 3 * 3600 like this:

#adjust for timezone
local_time = time.localtime(time.mktime(local_time) + (3 * 3600))

Summertime and Wintertime.

In Europe summertime and wintertime do not start each year at the same date. No that would make things too easy.

Summertime starts the last sunday in March
Wintertime starts the last sunday in October.


So how do I find the last sunday of march or october.

Find last Sunday

Well here is a small program with a function that finds the last sunday in any given year and month.

import time

def find_last_sunday(year, month):
    last_sunday = 0
    for week in range(25, 32):
        if time.localtime(time.mktime((year, month, week, 1, 0, 0, 0, 0, 0)))[6] == 6:
            last_sunday = week
    return last_sunday

# Here is an example
year = 2024
month = 10
print(find_last_sunday(year, month))

Try it yourself with different months and years. You'll see that the outcode is accurate.
You can adjust this for any day of the week by changing the number 6 into another number from 0 to 5 being:

0 = monday
1 = tuesday
2 = wednesday
3 = thursday
4 = friday
5 = monday


So if you want to check for the last wednesday in a month alter the code in:

import time

def find_last_sunday(year, month):
    last_sunday = 0
    for week in range(25, 32):
        if time.localtime(time.mktime((year, month, week, 1, 0, 0, 0, 0, 0)))[6] == 2:
            last_sunday = week
    return last_sunday

# Here is an example
year = 2024
month = 10
print(find_last_sunday(year, month))

Testing if date is in DST

The next step is to test if the current data is within the summertime (DST)

    start = time.mktime((year, 3, dst_start, 1, 0, 0, 0, 0, 0))
    end = time.mktime((year, 10, dst_end, 1, 0, 0, 0, 0, 0))
    now = time.mktime(t)

    return start <= now < end

Let's have a look at that.

start = time.mktime((year, 3, dst_start, 1, 0, 0, 0, 0, 0))

This line converts the start date of DST into the number of seconds that passed since Jan first 2000 (epoch time). The converted figure is stored into the variable start.

The next line does the same for the end date of DST and stores that figure in the variable end.

And lastly the current date is stored into the variable now.

Then the program compares in one line if now is larger than start and smaller than end. If that is the case then TRUE is returned.

Now we need to add a line that tests if the function returns the value True, and if so an hour is added to the current time.

The complete code

This will (of course) only work on a microcontroller that has wifi like the Raspberry Pi Pico, ESP8266 or ESP32.

Next to that you will need to get the ntptime library which you can find here:
https://github.com/Lucvolders/MicroPython/blob/main/Libraries/NTPtime/ntptime.py

And here is the complete MicroPython code.

import network
import ntptime
import time
import machine

# Router credentials
ssid = "YOUR-ROUTERS-NAME"
pw = "PASSWORD"

# wifi connection
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(ssid, pw)

# wait for connection
print('Waiting for connection.',end="")
while wifi.isconnected() == False:
    time.sleep(1)
    print('', end='.')
print("")

ip = wifi.ifconfig()[0]
print("Connected with IP adress : "+ip)

time.sleep(1)

# Function to check if DST is in effect
def is_dst_europe(t):
    year, month, day, hour, minute, second, weekday, yearday = t
    print(t)
    # Last Sunday in March

    dst_start = 0
    for day in range(25, 32):
        if time.localtime(time.mktime((year, month, day, 1, 0, 0, 0, 0, 0)))[6] == 6:
            dst_start = day


    # Last Sunday in October

    dst_end = 0
    for day in range(25, 32):
        if time.localtime(time.mktime((year, month, day, 1, 0, 0, 0, 0, 0)))[6] == 6:
            dst_end = day

    start = time.mktime((year, 3, dst_start, 1, 0, 0, 0, 0, 0))
    end = time.mktime((year, 10, dst_end, 1, 0, 0, 0, 0, 0))
    now = time.mktime(t)

    return start <= now < end

rtc = machine.RTC()

rtc.datetime((2000, 1, 1, 0, 0, 0, 00, 0))
print(time.localtime())

# Set the time from NTP server
ntptime.settime()

time.sleep(2)

# Get the local time
local_time = time.localtime()

#adjust for timezone Netherlands
local_time = time.localtime(time.mktime(local_time) + 3600)


# Adjust for DST if necessary
if is_dst_europe(local_time):
    local_time = time.localtime(time.mktime(local_time) + 3600)

# Print the adjusted time
print("Adjusted time:", local_time)

This gives us the right date and time adjusted for our timezone and DST.
Best thing to do is to turn this into a library for ease of use.

Till next time
have fun

Luc Volders