Thursday, December 14, 2023

Christmas presents

For an index to all my stories click this text.

The holliday season is coming up. Lots of time to celebrate with your loved ones and friends, but also lots of time to spend with your hobby. And maybe you have relatives or friends also want to start with electronics or the Internet Of Things. What better way than a book that explains it all in an easy to understand manner.  

Next to being the author of this blog I also wrote (until now) 4 books in plain English and two in Dutch that explain these things in an easy way. That is why the series is called xxxx Simplified.


Javascript tips

My latest book. This was released in May/June this year and already many have been sold. This book does not teach programming in Javascript. It assumes that you have some basic knowledge in programmin in Javascript.


For those in the blind: Javascript is thye language that makes webpages tick. Programming in Javascript even allows you to build app's for your mobile phone. This will be featured on this weblog in the upcoming year.

So what is it ?
This is a book with more than 500 tips that help during programming in Javascript.
Here is a small selection of things discussed in this book.
- How to calculate the number of days between two dates.
- How ro remove all non-alphanumeric characters from a string.
= How to copy all even numbers from an array to a new array.
- How to sort an array capital independend.
- How to call a function with an unknown number of arguments.
- How to start a function at preset times or intervals.
- How to test if a certain key is present in an object.
= How to change buttons, text, clour etc. on a web-page.
- How to add or delete elements on a webpage.
- How to prevent a user to copy parts of a webpage.
- How to prevent a user from printing a webpage.

Click here to order this book at Amazon

Click here to order this book from Lulu (my publisher)

The book is avaliable through all local book stores, Barnes and Nobles and Amazon.



Raspberry Pico W Simplifeid.

This is my latest book that was released in October this year.
The book covers the already very popular Raspberry Pi Pico W. In which the W stands for Wifi. The Raspberry Pi Pico W is a serious competitor to the famous ESP32. Not only has this board a lot of memory, a fast dual-core processor, loads of IO ports and USB for easy programming. It also has Wifi which makes it ideal for the Internet of Things. Look at it as an Arduino with added Wifi.



This book covers the following subjects:
Installing MicroPython, the MicroPython language, the pins layout, how to use a breadboard, adding power, how to use a button, how to use leds, fading leds with PWM, connecting to wifi, check if someone is at home with ping, Dallas DS18B20 thermometer chip, building your own MicroPython library, access internet data with Urequests, getting jokes from the internet, publishing to and retrieving data from Thingspeak, using an LDR for measuring light intensity, using mains power with a relay, movement detection with a PIR, getting notifications on your phone with Pushbullet, vibration detection, sending data to Telegram Messenger, how to use JSON, sending data to and retrieving data from Dweet, building a webserver that displays data and has buttons to control leds and lamps etc., attach a reset button.

Every project is build on a breadboard. All programs in the book are written in MicroPython and fully documented in detail.

This book is available through my publisher and through Amazon:

Click here to buy this book from Lulu (my publisher)

Click here to buy this book from Amazon


Raspberry Pi Pico Simplified


The Raspberry Pi Pico was the first microcontroller released by the Raspberry Foundation. Within a year 1.000.000 (yes 1 million) pieces were sold. The Pico is a serious competitor for the Arduino range of microcontrollers. It has a fast processor, loads of IO pins and can easily be programmed with MicroPython. This book focuses on the MicroPython language and on how to use a multitude of sensors with this microcontroller.



The book covers the following subjects:
Getting started, installing libaries, Pico's pins layout, introduction to using a breadboard, power, basic programming knowlegde, buttons, leds, fading leds with PWM, Dallas DS18B20 Digital Thermometer, using an LDR for measuring light intensity, potmeter, servo motor, more power, using mains power with a relay, touch sensor, controlling a motor, making sound with a buzzer, neopixels, H-Bridge for advanced motor control, movement detection with a PIR, motion detection with the RCWL-0156 Radar, measuring distance, tilt sensor, vibration detection, display your data, rotary encoder, oled display and how to build a reset button.

Every project is build on a breadboard. All programs in the book are written in MicroPython and fully documented in detail.

Click here to buy this book from Lulu (my publisher)

Click here to buy this book from Amazon

ESP32 Simplified

When the ESP8266 was released it was a sensation. It was a microcontroller like an Arduino but then with Wifi. The ESP32 offers even more benefits. The ESP32 has many IO pins, a fast processor, a lot of memory, bluetooth and an USB port so you can easily program it. The popular Arduino language (which is C++) is vailable for it and that opens the gate to many libraries for sensors and access to web-services. The ESP32 is a popular widely used microcontroller and therefore this book is a valuable source of information for anyone who wants to start with electronics and the Internet of Things.



This book covers the follwong subjects:
Installing the Arduino IDE, ESP32 board install, using the IDE, using the library manager, using ZIP libraries, installing libraries manually, first use of libraries, ESP32 Pin layout, ESP32 on a breadboard, introduction to using a breadboard, power, USB Breadboard connector,batteries, external Power Supply, programming basics, how to attach a button, buttons or switches, led, fading leds with PWM, Dallas DS18B20 digital thermometer, using an LDR for measuring light intensity, potmeter, make a dimmer, servo Motor, building a web server, more power, using mains power with a relay, automatic night light, touch sensor, a touch sensitive lamp, plant watering system, IFTTT, neopixels, thermometer with led indication, roll the dice, H-Bridge for advanced motor control, movement detection with a PIR, motion detection with the RCWL-0156 Radar, vibration detection, tilt sensor, display data with the TM1637, oled display, Thingspeak a cloud basede IOT, sending thermometer values to Thingspeak.

Every example is build on a breadboard so no soldering is required. Every example has an accompanying program which is documented in detail.

Click here to buy this book from Lulu (my publisher)

Click here to buy this book from Amazon



ESP32 Uitgelegd
Javascript tips


The Dutch versions of my books. For more information look at this story:

https://lucstechblog.blogspot.com/2023/11/sinterklaas-2023.html


Thanks for reading.
Have a great Xmas, a happy and healthy new year and loads of fun.

Luc Volders




Friday, December 8, 2023

ESPEasy part2: send data from esp to esp

For an index to all my stories click this text.

Introduction

ESPEasy is a software package for the ESP8266 and ESP32 that brings IOT functionality where no programming knowledge for is needed. The previous story in this series showed how to install ESPEasy and how to build a button in Domoticz that controls a led attached to an ESP8266 that runs ESPEasy. Indeed no programming was involved !!!

Please read or re-read that story first before continuing here because all the necessary background information is in that story. You can re-read it here http://lucstechblog.blogspot.com/2023/10/espeasy-part-1-iot-without-programming.html

This story tells how to send data from an ESP8266 with ESPEasy to another ESP8266 also with ESPEasy. Again: no programming required !!!! You could use this as a doorbell, movement alarm, door alarm, setting a lamp on etc. etc. etc.

As we will be sending data from one ESP8266 to another ESP8266 no home automation system or cloud service is needed. This is pure communication between two ESP's.

What you'll need.

To reproduce this project you will need two ESP8266's. I used two Wemos D1 Mini's but any version will do. The first ESP8266 will have a led attached. The second ESP8266 has a button attached.

So start with flashing ESPEasy on both ESP8266's as described in the previous story in this series : http://lucstechblog.blogspot.com/2023/10/espeasy-part-1-iot-without-programming.html

Breadboard setup

We need two breadboards. The first one has an ESP8266 with a led and is the receiver. It will get a command from the other ESP8266 to set the led on or off.



The setup is as simple as it gets. An ESP8266 (Wemos D1) with a led, connected to D7. As usual there is a current delimiting resistor of 220 ohm connected to the led. Actually this is the same setup as used in the previous story.

The second breadboard has an ESP8266 with a button. No pull-up resistor needed. We are going to use the internal pull-up resistor in the ESP8266 for that. This is the transmitter.



So this setup is equally simple. The button is at one side connected to GND and the other side to D3.

Setting up the receiver

Actually there is nothing to set up. As you might know from the previous story in this series ESPEasy reacts on simple HTTP commands to set an IO pin high or low.
The receiver has in this example the IP-number 192.168.1.82 Please alter this to your own settings.

Setting up the transmitter

First step is to tell ESPEasy to which pin the button is attached.

At the top of the screen click on Devices.



As the picture shows we can add 12 devices (Tasks) to the ESP8266. A device can be a button or a sensor.

The list of sensors that direct can be used in ESPEasy can be found here:
https://www.letscontrolit.com/wiki/index.php?title=Devices As you can see there are more as 100 sensors that direct can be used as the drivers are build into ESPEasy !!!

We want to add a switch. So first press on the Add button for Task1


Click on the - None - label and a drop down menu appears with all the available sensors. Scroll down till you see Switch input - Switch and click on that.

The screen changes in the settings screen for switches. Lets first look at the upper part of that page.



Now give the button a name. I named it sw1 but choose anything you like. As said before you can add multiple tasks so also multiple buttons. Therefore choose a logical name.

Make sure the button is enabled by checking enabled so it turns blue with the V sign in it.

In the sensor section check Internal Pullup. That way we do not have to use an external pull-up resistor on the ESP8266. Clicking it will turn it blue with the V sign.



The button is on the breadboard attached to D3 of the ESP8266 so make sure to choose GPIO-0 (D3) from the drop down menu.



Choose Switch as the switch type.



And choose Push Button Active Low as the button type.

Leave all other settings as they are.



At the bottom of the page make sure you check Send to Controller 1. ESPEasy can work with 3 Controllers. In this example we are going to use a single one. We will get to the meaning and purpose of the Controllers in a moment.
The IDX and interval value stay as they are: 0

And the last line allows you to name a variable in which the value of the button is stored. Just like coding with the Arduino IDE the value will be 1 if the button is NOT pressed, because of the pull-up function. The value will become 0 if the button is pressed. As with the button name choose the variables name wise as you can have multiple switches attached to the same ESP8266.

When done click Submit and the settings are stored in ESPEasy. Then click Close.

ESPEasy quircks

Well in the first part of this series I told you that in my opinion ESPEasy has some quircks. Well here is the first one.



This is now how your Devices screen should look. Task 1 is activated. The attached device is a Switch with the name sw1. The task communicates with CTR (Controller) 1 (more on that later). The button is attached to GPIO-0 (D3). And the variables name is sw1val and the value is 1 (in green).

The value is 1 as the button is not pressed and uses the internal pull-up resistor of the ESP8266. Now press the button on the ESP8266 and ........ nothing happens. Press it again a few times and still nothing happens.

When I started working with ESPEasy I thought something was wrong and I started searching for the error. I switched back to the Edit screen and fiddled with the settings and then sometimes the sw1val changed into a 0 and later back again into a 1. But it did not works as I expected it to work like I was used from a button in the Arduino IDE.

But ESPEasy works different !!!
First thing to know is that the button works as a latching button. If you press the button the value of sw1val changes to 0 and stays 0 till you press the button again.
Second thing to know is that the pages are not live updated.

So press the button on the breadboard and refresh the page. Now you will see that the 1 has changed into a 0 or the other way round.

Would be a good thing if that was explained more in the documents.


The Controller.

The switch is setup. Now we need a way to send it's state (0 or 1) to the other ESPEasy (the receiver). For that we need a Controller. So click on the Controllers tab at the top of the page.



As you can see we have room for setting up 3 Controllers. The name Controllers was a bit confusing to me. The manual defines it as follows: A controller is a component to enable a plugin to send data elsewhere. Well that mystified it only more for me. What the hell is a plugin and what is data elsewhere.

But of course I figured it out. A plugin is a sensor or a button etc. And data elsewhere is another ESP, your home automation system, a cloud based service like Thingspeak etc etc etc. Well that clears it up.

Click on the Add button in front of the 1 to setup the first (and for this story only) Controller.



As you can see the protocol for the Controllers is set as Standalone. Not what we want. We want to send commands over HTTP.



Click on Standalone in the drop-down menu. Dont hesitate to have a look at all the options. As you can see there are several communication protocols build in. For now we stick to Generic HTTP.



Use the same settings as you can see in the above picture. Only make sure that you replace the Controller IP with the IP number of your own receiver IP. The Controller port is 80 as we will send commands over HTTP. Leave the rest of the settings unchanged for now. Just make sure that Enabled (at the bottom) is checked. If Enabled is not checked the Controller will not work. This is an easy way to switch between multiple Controllers.

What needs a closer look is Controller Publish. That is the second last line in the Controller Setup.

Controller Publish

This line does exactly what it says. In here we need to compose the command which we are going to send over HTTP.

The previous story showed that for sending a command over HTTP to control an IO pin the command structure is:

http://<ESPEasy IP Adress>/control?cmd=GPIO,number,value

We know the receiver's IP adress in this example is 192.168.1.82. We also know that the led is attached to D7. ESPEasy however uses the real IO pin numbers and that is GPIO 13. So the command for setting the led on is:

http://192.168.1.82/control?cmd=GPIO,13,1

And setting the led off is done by:

http://192.168.1.82/control?cmd=GPIO,13,0


You might check the previous story for a detailed explanation on this. Re-read it here: http://lucstechblog.blogspot.com/2023/10/espeasy-part-1-iot-without-programming.html

The IP adress is filled in at the top of the page. So we only need to fill in the rest of this line. Leave away the first /. So we need to send: control?cmd=GPIO,13,1 to switch the led on, or a 0 at the end to switch the led off.

What we really want to do is to use the variable sw1val for that. So there needs to be a way to incorporate that into the command.

Well it took me a while to figure that out. This is also a quirck that is not explained in the documentation. But after a lot of experimenting I found it.

A variable in ESPEasy can be referred to by the name of the unit followed by # and then followed by the name of the variable. All packed between square brackets.

Our switch has the name sw1 and the variable has the name sw1val. That makes the reference to the variable: [sw1#sw1val]

So the total command shall be: control?cmd=GPIO,13,[sw1#sw1val]

And now we have the setup for the Controller complete. Exchange the names sw1 and sw1val for the ones you used in your Device setup and we are done. Press Submit at the bottom of the page and then press Close.

Indeed we are done.

This project is completed. To get things working just press the button on the transmitter ESP and the led on the receiver ESP will go on. Press the button again and the led will go off. All done without 1 line of coding and no cloud service needed !!!

That is all. It looks complicated but it really is not. Just get used to working with ESPEasy and you will enjoy it's simplicity in the end.

I was going to add how to send data from ESPEasy to Domoticz in this story. But there is already a lot of information in here so I save that for a future story.

Conclusion for now.

ESPEasy is fun to work with. It is indeed possible to get things done like sending data from one ESP to another without 1 line of code, as this story shows.

This story and the previous have not even scratched the surface of what is possible with ESPEasy. So I urge you to dive into it and start experimenting.

But it is not completly easy as the name suggests. The documentation is a bit crummy. You will need some experience with ESP8266 to attach buttons and sensors. And you need some insight about IP-Adresses, HTTP code etc. So the easy part of the name is only justified for those that are not total layman.

Still I urge you to experiment with ESPEasy and if you get the hang of it, it is possible to set up some IOT projects in a very short time.

Till next time
have fun

Luc Volders

 

 

Friday, November 24, 2023

Sinterklaas 2023

For an index to all my stories click this text.

Het is bijna Sinterklaas.
Als je nog een leuk cadeau zoekt voor je partner, kind, neefje etc die interesse heeft in electronica, microcontrollers of programmeren dan heb ik hier twee suggesties voor je.

ESP32 uitgelegd

Dit was het eerste boek dat ik schreef en is nog steeds een bestseller. Ideaal als je met  het Internet Of Things wil beginnen.



Dit boek begint met uitleg over de populaire ESP32 microcontroller en legt de programmeertaal C++ in het kort uit.
Daarna bespreekt elk hoofdtuk een sensor, laat zien hoe je deze aansluit en geeft een kort demo programma dat laat zien wat je ermee kunt doen. Vele sensoren komen aan bod: druktoets, bewegings sensor (PIR), tril sensor, tilt sensor, thermometer (Dallas DS18B20), licht sensor (LDR), aanraak sensor etc. etc.
Er komen ook aansturingen aan bod: leds, motoren, lichtstrips, servo's, relais, en transistoren en H-bruggen om motoren die meer kracht vergen aan te sturen.
En natuurlijk ontbreken displays als oled schermpjes, en TM1637 7-segment modules niet.
Als laatste wordt uitgelegd hoe je de Wifi mogelijkheden van de ESP32 kunt gebruiken. Met IFTTT kun je alarmen naar je telefoon sturen. Thingspeak wordt besproken om gegevens zoals temperatuur in grafiekvorm of wijzerplaat weer te geven. En uiteraard wordt uitgelegd hoe je de ESP32 een webpagina kunt laten maken waarop je gegevens kunt plaatsen, en waar knoppen op staan die acties (zoals een relais aanzetten) kunnen starten.

Het boek ESP32 Uitgelegd is verkrijgbaar bij alle boekhandels, de webshop van mijn drukker en Bol. Maar ook bij elektronica winkels als Otronic en Brokx. Hieronder vindt je een paar links die je naar de pagina's brengen als je er op klikt.

  
 
 

Brokx Electronics


https://www.otronic.nl/nl/




Javascript tips.

Het boek Javascript tips is dit jaar uitgekomen en er zijn er al vele van verkocht. Het boek gaat ervan uit dat je basiskennis over het programmeren in Javascript hebt. Het is dus geen leerboek. 



Wat is het dan wel ?
Het is een boek met meer dan 500 tips die je helpen bij het programmeren in Javascript. Hier is een kleine greep uit wat er allemaal beschreven wordt.
- Hoe reken ik ook al weer uit hoe lang het duurt tot een bepaalde datum
- Hoe verwijder ik leestekens uit een string
- Hoe kopieer ik alle even getallen uit een array naar een nieuw array
- Hoe sorteer ik ook weer een array maar zo dat de volgorde onafhankelijk is van hoofdletters
- Hoe roep ik een functie aan terwijl ik niet weet hoeveel argumenten de functie heeft
- Hoe start ik een functie op vastgestelde tijden
- Hoe test ik of een bepaalde key in een objecvt aanwezig is
- Hoe verander ik teksten, buttons, kleuren etc op een html pagina
- Hoe verwijder ik elementen of voeg ik elementen toe aan een html pagina
- Hoe voorkom ik dan een gebruiker delen van een webpagina kan kopieren.
- Hoe voorkom ik dat een gebruiker een webpagina kan printen.

Het boek Javascript tips is verkrijgbaar bij alle boekhandels, de webschop van mijn drukker en Bol.


https://www.boekenbestellen.nl/


En via Bol


Beide boeken zijn overigens ook in het engels verkrijgbaar bij Amazon. Net zoals mijn engelstalige boeken over de Raspberry Pi Pico.

Klik hier voor de link naar Amazon

 

 

Fijne Sinterklaas

Luc Volders

Friday, November 17, 2023

Domoticz with MicroPython part 4

For an index to all my stories click this text.


This is the fourth story in a series about sending data to, and receiving data from Domoticz with MicroPython.

The reason why I am writing these is because I migrated to a new internet provider. That meant reprogramming all of my microcontrollers. They needed to contact my new router and got new IP addresses. It was a hell of a job.

So I decided to reprogram the sensors in MicroPython. What made this easy is that all my favorite microcontrollers (ESP8266, ESP32 and Raspberry Pi Pico) are supported by MicroPython.

The first story describes connecting a pushbutton to a Raspberry Pi Pico and sending it's data to Domoticz. You can use this for a myriad of purposes like a doorcontact, a windowcontact, doorbell, PIR, vibration sensor, rain sensor etc. etc. Another purpose is using your Pico with a pushbutton as a remote control for your lamps. You can re-read that story here:
http://lucstechblog.blogspot.com/2023/11/domoticz-with-micropython-part-1.html

The second story describes how to build a switch in Domoticz that will set a led, attached to a microcontroller, on or off. You can re-read that story here:
http://lucstechblog.blogspot.com/2023/11/domoticz-with-micropython-part-2.html

The third story was about sending data to Domoticz again. The first story did that also but there I send just the ON or OFF state of a switch. The third story showed how to send values to Domoticz like the values of a temperature sensor, a light sensor etc. etc. You can read that story here:
http://lucstechblog.blogspot.com/2023/11/domoticz-with-micropython-part-3.html

This story covers how to send values from Domoticz to a microcontroller. This can be used to dim a lamp, dim a led strip, control a motor speed, control a servo position etc. etc. etc.

Breadboard setup

Actually it is the same setup from the second story. Just a Raspberry Pi Pico with a led.



Nothing special here. The led is connected to GPIO15 Through a current delimiting resistor of 220 Ohm.

Please note that you can also use an ESP8266 or an ESP32 in stead of the Pico. Just alter the pin number where the led is attached to in the program.

What we are going to do.

We are going to send values from a dimmer in Domoticz to the microcontroller. The value of the dimmer position determines how bright the led will glow.

Just like in the previous stories: this is just a demo. Replace the led with the proper electronics and you can use this for loads of purposes.

Creating a dimmer in Domoticz.



In Domoticz choose setup and then the Hardware entry.

In my case there was a Virtual 1 entry (which is my real mancave thermometer). If you do not have virtual entries you can call it whatever you like. But for the sake of this story call it Virtual 2 and choose as type Dummy.

Don't forget to press the Add button.



A new entry will become available in your hardware list with the name Virtual 2 which you gave it. Now click on Create Virtual Sensors.



A pop-up window opens where you can define your new virtual sensor. I gave it the name MicroPython-test-dimmer and choose as type Switch.

Press the OK button and Domoticz will tell you that the sensor can be found in the devices tab. But don't bother.



The just created switch is immediately visible in the Switches tab. As you can see I already had a lot of switches defined. The new switch looks like a lamp. But we want it to be a dimmer. Press on the edit button in the switch.



In the drop-down menu from the Switch Type choose dimmer.



The Icon changes in the picture of a small dimmed lamp. That is the default icon for a dimmer which is ok. You can choose another icon if you like.

Press the Save button and you are done for now.



And this is how your dimmer will look now in the Switches tab, or on your Dashboard.

Sending values over HTTP

The second article in this series showed how to send an ON or OFF command from Domoticz. That could be done in the switches settings with On Action and Off Action. You can read that here: http://lucstechblog.blogspot.com/2023/11/domoticz-with-micropython-part-2.html

However that method doesn't work for sending values. We need to take a different path for that.



Click on the Setup tab, then choose More Options and from there Data push and HTTP



In this window we need to change several parameters.



The first thing we can alter is Target Type. That is set as Global variable and DO NOT change this. A Global variable is a variable that can be used throughout all parts of Domoticz.

Next we need to choose the device we want to send data. From the Device Name drop-down menu therefore choose MicroPython-test-dimmer.



Set the value to send to: Level.

The other choise (Status) only sends on and off. We want to send a value.



The last thing to change in this Edit Link part of the screen is the Target Variable. I chose as name MP-Dimval. But feel free to choose any name you like.

Then press the Add button.
A pop-up screen arises that shows that the Http link is saved.



And as you can see at the top of the screen a new entry is shown.



Now let's have a look at the right side of this screen.
At the top it gives us all available data which we can send.

%v : Value
%t0 : Timestamp (epoc time localtime)
%t1 : Timestamp (epoc ms localtime)
%t2 : Timestamp (epoc time UTC)
%t3 : Timestamp (epoc ms UTC)
%t4 : Timestamp : "2015-01-29T21:50:44Z
%D : Target Device id
%V : Target Variable
%u : Unit
%n : Device name
%T0 : Type
%T1 : SubType
%h : hostname
%idx : 'Original device' id (idx)


As you can see there are many things we can send to our microcontroller.

In this demo we are going to make things easy and we are only going to send the level (value) of the dimmer.
For this we need to use %v in our HTTP command.

But first we now need to know where to send that command. And for that we need the IP address of the microcontroller.

MicroPython program to get IP address

This is just a small program to obtain the IP address that the microcontroller (Raspberry pi pico W) is going to get from the router.

import network

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

# 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)

Nothing unfamiliar here. We have used this part in our previous programs so look in the previous stories for a detailed description of this.



And this is what you will see in Thonny's shell.
Undoubtedly you will get a different IP address. But this is what we need.


Back to the HTTP screen.

Things are getting a bit complicated now.

In a real-life situation we are not going to send out just one command. We will be sending multiple HTTP commands to one microcontroller. But we will also be sending commands to several controllers. Therefore you need to choose wisely what command you are going to send to avoid confusion later on.

So the first part of our HTTP command is the IP number.
Next there is a / to separate the IP number from the actual command we are sending.
And then there is the command itself.

-dimval-%v-end

This is the command I used.
I start with -dimval- to show it is the dimmers value. Then %v which is the representation of the actual value that is going to be send. And I end with -end.
The %v is what we found we needed in the list at the top of this screen. %v is replaced by the real value by Domoticz.

http://192.168.178.193/-dimval-%v-end

So this is our complete HTTP command we are going to send. Please make sure to make no typo's in this as otherwise the program running on your Micro will not react.

You can make changes in this, however make sure to adjust the MicroPython program accordingly.



And here is how you should fill this in.

Leave the rest as is. We are going to send an HTTP Get command. Make sure Active is activated as the command will otherwise not be send.

Press Save.
Don't forget to press save otherwise your work was in vain.

The microPython dimmer program

The dimmer program is actually a webserver framework that does not produce a webpage but just uses the framework to receive data from an external source. In this case from Domoticz.

As usual I start with the complete program and will then look at some details.

import network
import socket
import time

from machine import Pin

led = machine.PWM(machine.Pin(15))
led.freq(1000)

ssid = "YOUR_ROUTER_NAME"
pw = "PASSWORD"

# 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)

addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

s = socket.socket()
s.bind(addr)
s.listen(1)

# Listen for connections
while True:        

        cl, addr = s.accept()
        print('client connected from', addr)
        request = cl.recv(1024)
        print(request)

        request = str(request)
        
        dimbeg = request.find('-dimval')
        dimend = request.find('-end')
        print("=================================")
        print(dimbeg)      
        print(dimend)
        start = (request[dimbeg:dimend])
        valdim = start.split("val-")[1]
        print(valdim)
        valdim = int(valdim)
        if (valdim <4):
            valdim = 0
            
        led = machine.PWM(machine.Pin(15))
        led.freq(1000)
        led.duty_u16(655*valdim)
        # response = html % stateis

        cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
        #cl.send(response)
        cl.close()

Let us look at some details.

import network
import socket
import time

from machine import Pin

led = machine.PWM(machine.Pin(15))
led.freq(1000)

The necessary libraries are imported which are all available with your standard MicroPython distribution.
Then GPIO15 is defined as a PWM pin. This makes it possible to dim the led.
The PWM frequency is set to 1000.

If you have any trouble with this part I recommend reading my book on the Raspberry Pi Pico W on which you will find a link at the bottom of this page.

In the next lines do not forget to replace YOUR_ROUTER_NAME and PASSWORD with your routers credentials.

addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

s = socket.socket()
s.bind(addr)
s.listen(1)

A network socket is opened and the program starts listening for incoming commands on this socket.

while True:        
    # try:
        cl, addr = s.accept()
        print('client connected from', addr)
        request = cl.recv(1024)
        print(request)

In the loop the program waits till it receives some data. That received data is stored in the variable request.
For our convenience the received data is printed in Thonny's shell.



And this is what the received data looks like. What we now need to do is to distill the actual data we need.

        request = str(request)
        
        dimbeg = request.find('-dimval')
        dimend = request.find('-end')
        print("=================================")
        print(dimbeg)      
        print(dimend)

First we make a string from the received data.
Then we search for the first position of the word -dimval and the first position of the word -end.

b'GET /-dimval-46-end

This is the first thing we have received and the information we need.
As you can see -dimval is at the seventh position in this string and -end at the 17th position. Remember counting starts at 0.
And the program indeed printed 7 and 17 in the shell.

start = (request[dimbeg:dimend])

The text in request starting at dimbeg and ending at dimend is stored in the variable start.
The variable start therefore contains: -dimval-46

We have to split that string up to get the value (in this case 46).

        valdim = start.split("val-")[1]
        print(valdim)
        valdim = int(valdim)

Therefore -dimval-46 is split at the letters "val-" in a list (kind of array), with two values: ["-dimval-"] and ["46"]
We need the second element, which is [1]

For our convenience we print the value in the Shell so we can see that we got the real thing.
The received value is a string and the last command in this part converts that into an integer value.

        if (valdim <4):
            valdim = 0

The program tests if the received value is less then 4. If that is the case valdim is set to 0 which sets the led off.

        led = machine.PWM(machine.Pin(15))
        led.freq(1000)
        led.duty_u16(655*valdim)

And this is the part where we actually dim the led to the received value.
The lowest brightness is 5 and the highest 65536.
The dimmer in Domoticz has a scale of 1 to 100. So we have to divide 65536 by 100 to get the dimming steps.
Next we multiply that step value by valdim which is the received number.
And that is the dim level to set the led's duty cycle.

That's it.

If you have any problems with this MicroPython program I really recommend my book on the Raspberry Pi Pico W. In this book the the webserver and several other internet capabilities are explained netx to the use of several sensors and actuators. You can find a link to this book at the bottom of this page.

Using the dimmer.

Well the only thing you have to do is to move the slider. When you release your mouse button the led on the microcontroller will almost immediately get dimmed to the value you choose.

Real world applications.

Using a dimmer is more complicated than just adding a relay to your microcontroller. There are however battery fed lightstrips that can be used with this setup.
You'll need a transistor and a resistor for powering the strip. You can find an example here:

https://lucstechblog.blogspot.com/2016/05/esp8266-controlled-ledstrip.html

As stated before you can use the dimmer to set the position of a servo. So how about a Domoticz controlled tea-timer:

https://lucstechblog.blogspot.com/2018/08/teatimer.html

Till next time.
Have fun


Luc Volders