Weihnachtsbeleuchtung über Relais mit eigener Bluetooth App schalten - AZ-Delivery

"I made fire," says Tom Hank's pride in the film "Cast Away - missing". I had the same feeling when I had my first smartphone app for one a few weeks ago Robot Car remote control with which with app inventor. Since almost all of them have a smartphone today, you can often find a cheaper solution for remote controls with its possibilities, because you can do without a microcontroller and the transceiver. So I take a second attempt with my own smartphone app to switch a relay module.

In the past, we have shown the switching of relay modules several times in different ways, e.g. 

Relays are very important components if different tensions or high currents can be switched or for other reasons a galvanic separation of load circuit and the control group is necessary. I had the example of the model railway in one other blog already mentioned. Other applications in the Advent and Christmas season are fairy lights or, for example, a stepper motor for the Christmas pyramid if candles are to be dispensed with for the drive. Owners of aquariums or terrariums can also switch on or off lighting, heating, pumps, etc.

Here is the most cost-effective solution: In addition to the relay module with voltage supply, only a Raspberry Pi Pico W and some jumper cables are required.

Used hardware


Raspberry Pi Pico W or WH

With the WH model, the pinbags are already soldered


Relay module 8er, 4er, 2nd, 1 series


Breakboard/Punching board, Jumper cable


Android smartphone 

With app inventor also works with iPhone, but not tried out 

First another look at the relay module. Like the different types of engine, relays with their electromagnetic properties are not really harmless consumers such as LEDs. Especially when switching on and off, significantly higher currents flow than our microcontrollers tolerate. With more than one relay, this means using an external voltage supply, galvanic separation and an open -air diode (flyback diode) for the switch -off process. For this, pension is made at the modules.

In the following picture you can see (from top to bottom)

  • The connections for the external (to be switched) circuit with NC (= Normally Closed, mostly remaining), CO (= common, the common input) and NO (= Normally Open, the output for the power supply, when the relay is switched on),
  • The actual magnetic switches (the blue blocks),
  • Control electronics with free-range diode, optocoupler (further galvanic separation), resistances and display LED,
  • Connections to the GPIOs of the microcontroller and the external power supply

When supplying the voltage of the relay module, a distinction must be made between the control streams and the electromagnet. The total of 10 pins in the middle are GND, inputs in1 to in8 and VCC (voltage input of the control electronics), the three pins on the right in the picture are GND and tension input for the magnets. If, as here in the picture, there is a short -circuit plug (jumper) between VCC and JD -VCC, both supply tensions are identical and - one cannot say it often enough - come from an external voltage source, not from the microcontroller (!). And about the inputs in1 up to in8, it should be said that the relay attracts in most modules when the signal is set to low from the microcontroller. But there are also exceptions, just try it out when it clicks.

In my Breadboard circuit, I left the jumper and connected a battery pack with three AA batteries (3*1.5 V = 4.5 V) to the power rails. If you want to use batteries, you should use four batteries (4* 1.2 V = 4.8 V). In the end I also connected the Raspberry Pi Pico W to this power rail. The entrance VSYS tolerates tensions between 1.8 V and 5.5 V. Quote from the DataSheet: “VSYS is the Main System input Voltage, which can vary in the allowed range 1.8v to 5.5v, and is used by the on- Board SMPS to Generates the 3.3V for the RP2040 and Its GPIO. "

However, the USB output of the computer provides the tension for the PICO W, the Battery Pack the tension for the relay module. Only at the end is the Micropython program under the name main.py Stored on the PICO to activate the autostart function and the PICO is then connected to the external voltage.

circuit diagram

Program code

Anyone who has not yet installed Thonny and Micropython can have the individual steps in the blog posts Raspberry Pi Pico and Thonny with Micropython - Part 1 and Raspberry Pi Pico W now with Bluetooth - Part 1 look at. With Micropython, please remember to use the current file with the ending.


# 8 Relays Controlled by Raspberry Pi Pico W Ble and smartphone
# Modified from Official Rasp Pi Example here:
# https://github.com/micropython/micropython/tree/master/examples/bluetooth
# by Bernd54albrecht for AZ-Delivery 2023

import bluetooth
import random
import struct
import time
From ble_advertising import Advertising_payload
From micropython import const
From machine import Pin code, PWM
import RP2

# Initialize relay pins
r1 = Pin code(6, Pin code.OUT,value=1)
r2 = Pin code(7, Pin code.OUT,value=1)
r3 = Pin code(8, Pin code.OUT,value=1)
r4 = Pin code(9, Pin code.OUT,value=1)
r5 = Pin code(10, Pin code.OUT,value=1)
r6 = Pin code(11, Pin code.OUT,value=1)
r7 = Pin code(12, Pin code.OUT,value=1)
r8 = Pin code(13, Pin code.OUT,value=1)

## Taken from ble_simple_peripheral.py
_Irq_gatts_write = const(3)

_Flag_read = const(0x0002)
_Flag_write_no_Response = const(0x0004)
_Flag_write = const(0x0008)
_Flag_notify = const(0x0010)

_Uart_uuid = bluetooth.Uuid("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
_UART_TX = (
   _Flag_read | _Flag_notify,
_UART_RX = (
   _Flag_write | _Flag_write_no_Response,
_Uart_service = (

class Blesimpleperipheral:
   def __init__(self, bleed, Surname="Picow"):
       self._Ble = bleed
      ((self._handle_tx, self._handle_rx),) = self._Ble.Gatts_ Register_services((_Uart_service,))
       self._Connections = set()
       self._write_callback = None
       self._Payload = Advertising_payload(Surname=Surname, services=[_Uart_uuid])

   def _irq(self, event, data):
       # Track Connections so we can send notifications.
       IF event == _IRQ_CENTRAL_CONNECT:
           Conn_handle, _, _ = data
           print("New Connection", Conn_handle)
       elif event == _IRQ_CENTRAL_DISCONNECT:
           Conn_handle, _, _ = data
           print("Disconnected", Conn_handle)
           # Start Advertising Again to Allow A New Connection.
       elif event == _Irq_gatts_write:
           Conn_handle, value_handle = data
           value = self._Ble.Gatts_read(value_handle)
           IF value_handle == self._handle_rx and self._write_callback:

   def send(self, data):
       for Conn_handle in self._Connections:
           self._Ble.Gatts_notify(Conn_handle, self._handle_tx, data)

   def IS_CONNECTED(self):
       return len(self._Connections) > 0

   def _advertisise(self, interval_us=500000):
       print("Starting advertising")
       self._Ble.gap_advertise(interval_us, Adv_data=self._Payload)

   def on_write(self, callback):
       self._write_callback = callback

# This is the main loop
def demo():    # This part modified to control 8 relays
   bleed = bluetooth.Bleed()
   P = Blesimpleperipheral(bleed)

   def on_rx(code):  # code is what has been receiven
       print("Code =",code)       # Print code
       code = Str(code)[2:-5] # Necessary only for smartphone app
       code = intimately(code)
       print("Code =",code)       # Print code

       IF code & 1 == 1:
           print("Relais1 on")
           r1.off()   # Relay1 on
           print("Relais1 Off")
           r1.on()   # Relay1 off

       IF code & 2 == 2:
           print("Relais2 on")
           r2.off()   # Relay2 on
           print("Relais2 Off")
           r2.on()   # Relay2 off
       IF code & 4 == 4:
           print("Relais3 on")
           r3.off()   # Relay3 on
           print("Relais3 off")
           r3.on()   # Relay3 off  
       IF code & 8 == 8:
           print("Relais4 on")
           r4.off()   # Relay4 on
           print("Relais4 Off")
           r4.on()   # Relay4 off  
       IF code & 16 == 16:
           print("Relais5 on")
           r5.off()   # Relay5 on
           print("Relais5 Off")
           r5.on()   # Relay5 off  
       IF code & 32 == 32:
           print("Relais6 on")
           r6.off()   # Relay6 on
           print("Relais6 off")
           r6.on()   # Relay6 off
       IF code & 64 == 64:
           print("Relais7 on")
           r7.off()   # Relay7 on
           print("Relais7 Off")
           r7.on()   # Relay7 off  
       IF code & 128 == 128:
           print("Relais8 on")
           r8.off()   # Relay8 on
           print("Relais8 off")
           r8.on()   # Relay8 off  

IF __Surname__ == "__Main__":

Notes on the program code:

As usual, program modules (cf. libraries/libraries at Arduino-IDE) are imported as usual. From the Micropython examples for Bluetooth, see:


Will the program ble_advertising.py Stored unchanged as a module on the Pico W. From the program ble_simple_peripheral.py I copied the important parts and integrated into my program.

I use GP 6 to 13 for the initialization of the relay pins and set the starting value to 1 (high), because as I said, my relays switch when the input is set to 0 (low).

This is followed by the Bluetooth-relevant code components, which I copied from the example.

In the main part of the program, the message sent by the smartphone and evaluating and using the code are read out. I assigned the eight relays to the value of the two potency with the number of the relay minus 1. Code 0 means all relays switched off, 255 means all on. Example: relay 1 (value 2 high 0), 2 (value 2 high 1) and 8 (value 2 high 7) means code 2 high 0 plus 2 high 7 = 1 + 2 + 128 = 131.

In eight if/else-Queries are checked whether the respective two potency is contained in the code and the respective relay is switched on. The rest of your own performance lies in the smartphone app, which is created online in the browser with the Inventor app.

Create Android app

A GMail account is used for logging in. In addition, Bluetooth LE must be inserted as an extension (menu item Import Extension). For details see the blog post
Raspberry Pi Pico W now with Bluetooth - Part 4 - Robot Car with flashing lights and siren (pio -controlled).

If you started it with app inventor, just my file Ble_controller_8relais.apk Import and with the app With AI2 Companion Try it out, make changes if necessary and finally compile and install it as a new app.

Here are my screenshots of the browser, first the designer view:

And composed the blocks view from two pictures:

After starting the program of the PICO W and pressing the button Start scanning In the app, the Pico W should be displayed as a BLE partner and the relays can be switched on or switched off individually.

Once again to explain the code: In the app, I numbered the relays of simplicity for the sake of 1 to 8 for the sake of simplicity. For the value and calculation of the code, this number must be reduced by 1. The code 176 = 2 high 4 plus 2 high 5 plus 2 high 7, so relay 5, 6 and 8 are switched on the picture at the top left. The user does not need to take this pointed speed of the programmer into account.

Of course, you can also use smaller relay modules and delete the non-required code shares in the micropython program and the app. Have fun recovery and switching your Christmas decoration.

We wish you a happy and blessed Christmas.

If you do not see a video at this point, you must allow cookies in the browser settings.

Raspberry piSmart homeSpecials


Bernd Albrecht

Bernd Albrecht

@ Michael Lang. Leider kann ich die Fehlermeldung hier nicht nachvollziehen. Für mich sieht es so aus, als fehle auf dem Android Smartphone die entsprechende Berechtigung für Bluetooth LE. Bitte in den Einstellungen prüfen. Ist BLE eingeschaltet? Wird der Pico W unter Einstellungen/Bluetooth angezeigt? Empfehlung: die App zunächst mit dem MIT AI2 Companion ausprobieren. Unter Einstellungen/Apps … die Berechtigungen für den MIT AI2 Companion prüfen. Viel Erfolg

Michael Lang

Michael Lang

Wenn ich “Start Scanning” in der App drücke , kommt bei mir die Fehlermeldung:
“Runtime Error
Need android.permission.BLUETOOTH_SCAN permission for AttributionSource { uid = 10687, packageName = appinventor.ai_bernd54albrecht.BLE_controller_8Relais, attributionTag = null, token = android.os.BinderProxy@ca4404a, next = null}: GattService registerScanner”
Was habe ich übersehen?

Andreas Wolter

Andreas Wolter

Bernd Albrecht hat eine AIA Datei für den Import im MIT App Inventor zur Verfügung gestellt. Diese haben wir im Artikel neu verlinkt. Danke für den Hinweis.
Den Schaltplan checken wir ebenso.

Andreas Wolter
AZ-Delivery Blog

Michael Lang

Michael Lang

Hallo Bernd, könntest du die .aia-Datei der BLE_controller_8relais.apk zum Herunterladen bereitstellen? Danke Michael

Michael Lang

Michael Lang

Fehlt im Fritzing-Schalplan weiter oben nicht die VCC-Verbindung von der VCC-Schiene des Breadboards zum VCC-Anschluss der Relaisplatine neben den Anschlüssen zu den GPIOs?

Peter Hilpert

Peter Hilpert

Wie kann man die apk-Datei (BLE_controller_8Relais.apk) im MIT App Inventor importieren oder benötige ich hier eine .aia Datei welche ich im Beitrag leider nicht finden kann.

Andreas Wolter

Andreas Wolter

@Robert Fuchs: das wird wahrscheinlich in der Arduino IDE mit den passenden Bibliotheken genauso funktionieren. Entweder finden Sie Beispiele hier im Blogbereich, oder Sie schauen z.B. mal dort hinein:

Andreas Wolter
AZ-Delivery Blog

Robert Fuchs

Robert Fuchs

Kann ich das auch mit C in der Arduino IDE machen?

Leave a comment

All comments are moderated before being published

Recommended blog posts

  1. ESP32 jetzt über den Boardverwalter installieren - AZ-Delivery
  2. Internet-Radio mit dem ESP32 - UPDATE - AZ-Delivery
  3. Arduino IDE - Programmieren für Einsteiger - Teil 1 - AZ-Delivery
  4. ESP32 - das Multitalent - AZ-Delivery