Raspberry pi 5 light app control

Hello fams.

Please any guide line on how to build an app to control light with raspberry pi 5 Bluetooth inbuilt and also code script to be program inside the raspberry pi 5. Please need help am on a project.

Thanks.

Yes i want an app the app that will have an ability to detects different kinds of accident using accelerometersensor, orientationsensor, locationsensor, from the phone and that Will have an ability to detects different kinds of accident and send an emergency alert message to another phone and location for example the kind of accident may be crush detected,or Roll accident detected

did you try some thing before???? if there post your block screenshot here.

First check if your raspberry pi 5 has inbuilt Bluetooth module, then all the guide below work fine.

There is some guides on YouTube

Community post also here

Also as chatgpt suggest me this is a detail step to try

Summary

1) Overview (what we'll build)

  • Raspberry Pi 5 runs a Bluetooth RFCOMM server (Python) that accepts simple text commands (ON, OFF, TOGGLE, STATUS).
  • The server toggles a GPIO pin that drives an LED (or a relay to control mains lighting).
  • MIT App Inventor Android app uses the BluetoothClient component to connect and send ON/OFF text messages.

2) Hardware list

  • Raspberry Pi 5 (power supply)
  • microSD with Raspberry Pi OS (64-bit recommended)
  • 1 LED + 220Ω resistor or a relay module (if controlling mains)
  • Breadboard and jumper wires
  • (Optional) USB keyboard, monitor, or use SSH

GPIO example: we'll use GPIO17 (pin 11) in the code. Change if you prefer another pin.

Safety: If you control mains power use a proper relay module and follow electrical safety rules.


3) Raspberry Pi setup (OS & Bluetooth packages)

Open a terminal on the Pi and run:

sudo apt update
sudo apt upgrade -y

# Install Bluetooth stack + dev files:
sudo apt install -y bluetooth bluez libbluetooth-dev

# Install Python dependencies:
sudo apt install -y python3-pip
pip3 install pybluez gpiozero

Enable Bluetooth service (should be enabled by default):

sudo systemctl enable bluetooth
sudo systemctl start bluetooth

(Optional) use bluetoothctl to make pairing easier (shown below).


4) Wire the LED (or relay)

  • LED anode -> 220Ω resistor -> GPIO17 (pin 11)
  • LED cathode -> GND (pin 9)
  • If using a relay module, connect relay Vcc/GND to Pi and input to GPIO17. Use module with opto/isolation as needed.

5) Pair the Android device with Pi (first-time)

You can pair from Android Settings → Bluetooth, or from Pi terminal:

# interactive pairing example:
bluetoothctl
# then inside bluetoothctl:
power on
agent on
default-agent
scan on            # find Android MAC address
pair AA:BB:CC:...  # use device MAC from scan
trust AA:BB:CC:...
connect AA:BB:CC:...
# then exit: quit

Pairing can be done in Android settings too — pairing first is often simplest.


6) Python server script (run on Pi)

Create a file /home/pi/bluetooth_led_server.py with the code below. It uses PyBluez RFCOMM server and gpiozero to control the LED.

#!/usr/bin/env python3
# bluetooth_led_server.py
import sys
import traceback
from bluetooth import (
    BluetoothSocket,
    RFCOMM,
    PORT_ANY,
    advertise_service,
    SERIAL_PORT_CLASS,
    SERIAL_PORT_PROFILE,
)
from gpiozero import LED
from signal import signal, SIGINT
import time

LED_PIN = 17   # GPIO pin (BCM numbering) - change if needed
led = LED(LED_PIN)

server_sock = None
client_sock = None

def cleanup():
    global client_sock, server_sock
    try:
        if client_sock:
            client_sock.close()
    except Exception:
        pass
    try:
        if server_sock:
            server_sock.close()
    except Exception:
        pass
    try:
        led.off()
    except Exception:
        pass

def sigint_handler(signal_received, frame):
    print("\nSIGINT received, shutting down...")
    cleanup()
    sys.exit(0)

signal(SIGINT, sigint_handler)

def main():
    global server_sock, client_sock
    server_sock = BluetoothSocket(RFCOMM)
    server_sock.bind(("", PORT_ANY))
    server_sock.listen(1)
    port = server_sock.getsockname()[1]

    advertise_service(
        server_sock,
        "PiLight",
        service_classes=[SERIAL_PORT_CLASS],
        profiles=[SERIAL_PORT_PROFILE],
    )

    print(f"[+] Waiting for connection on RFCOMM channel {port}")

    try:
        client_sock, client_info = server_sock.accept()
        print(f"[+] Accepted connection from {client_info}")

        client_sock.settimeout(1.0)
        while True:
            try:
                data = client_sock.recv(1024)
                if not data:
                    # remote closed
                    print("[*] Client disconnected")
                    break
                text = data.decode("utf-8", errors="ignore").strip()
                if not text:
                    continue
                print(f"[<] Received: {text}")

                # Commands
                if text.upper() == "ON":
                    led.on()
                    client_sock.send("OK:ON\n")
                elif text.upper() == "OFF":
                    led.off()
                    client_sock.send("OK:OFF\n")
                elif text.upper() == "TOGGLE":
                    if led.is_lit:
                        led.off()
                        client_sock.send("OK:OFF\n")
                    else:
                        led.on()
                        client_sock.send("OK:ON\n")
                elif text.upper() == "STATUS":
                    client_sock.send("STATUS:ON\n" if led.is_lit else "STATUS:OFF\n")
                elif text.upper().startswith("SET:"):
                    # optional: SET:1 or SET:0
                    arg = text.split(":", 1)[1].strip()
                    if arg in ("1", "ON", "on", "On"):
                        led.on()
                        client_sock.send("OK:ON\n")
                    else:
                        led.off()
                        client_sock.send("OK:OFF\n")
                else:
                    client_sock.send("ERR:UNKNOWN\n")
            except IOError:
                # timeout, continue waiting for data
                continue
            except Exception as e:
                print("Exception in main loop:", e)
                traceback.print_exc()
                break

    except Exception as e:
        print("Server error:", e)
        traceback.print_exc()
    finally:
        cleanup()
        print("[*] Server stopped")

if __name__ == "__main__":
    main()

Make it executable:

chmod +x /home/pi/bluetooth_led_server.py

Run it:

python3 /home/pi/bluetooth_led_server.py

When it runs you should see Waiting for connection.... From the Android app you will connect to the Pi and send ON/OFF.


7) (Optional) Run server on boot via systemd

Create /etc/systemd/system/bluetooth_led.service:

[Unit]
Description=Bluetooth LED server
After=bluetooth.target

[Service]
ExecStart=/usr/bin/python3 /home/pi/bluetooth_led_server.py
WorkingDirectory=/home/pi
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi

[Install]
WantedBy=multi-user.target

Enable/start:

sudo systemctl daemon-reload
sudo systemctl enable bluetooth_led.service
sudo systemctl start bluetooth_led.service
sudo journalctl -u bluetooth_led.service -f

8) MIT App Inventor Android app — step-by-step

  1. Open MIT App Inventor (ai2.appinventor.mit.edu), start a new project (e.g., PiLight).

  2. Designer screen — add components:

    • User Interface:

      • ListPicker (Name: ListPicker_BT) — text: "Choose Bluetooth Device"
      • Button (text: "Connect") — or use the ListPicker to select and connect
      • Button (text: "ON") — name btnOn
      • Button (text: "OFF") — name btnOff
      • Button (text: "TOGGLE") — optional
      • Label lblStatus — to show connection and response
    • Connectivity:

      • BluetoothClient (non-visible) — name BluetoothClient1
    • (Optional) Notifier for messages.

  3. Blocks (logic). Use these building blocks (described as steps — you can reproduce in App Inventor blocks editor):

  • BeforePicking (ListPicker_BT.BeforePicking):

    • Set ListPicker_BT.Elements to BluetoothClient1.AddressesAndNames
    • (This will show paired devices & addresses. If none, pair the phone with the Pi in Android settings.)
  • AfterPicking (ListPicker_BT.AfterPicking):

    • Call BluetoothClient1.Connect with address = ListPicker_BT.Selection
    • If BluetoothClient1.IsConnected then set lblStatus.Text to "Connected"
    • Else show notifier "Failed to connect"
  • btnOn.Click:

    • If BluetoothClient1.IsConnected then call BluetoothClient1.SendText("ON")
    • Optionally call BluetoothClient1.ReceiveText(1000) to get response and set lblStatus.Text to response
  • btnOff.Click: same but send "OFF"

  • TOGGLE button: send "TOGGLE"

  • Disconnect (optional): call BluetoothClient1.Disconnect

  • Receive loop option: MIT App Inventor can't block-wait forever easily. After sending, you can call ReceiveText with a small timeout (e.g., 1000 ms) to read the server response.

Example blocks in words:

  • ListPicker.BeforePicking -> set ListPicker.Elements to BluetoothClient.AddressesAndNames
  • ListPicker.AfterPicking -> call BluetoothClient.Connect(ListPicker.Selection) -> if connected set label to "Connected to " + ListPicker.Selection else show alert.
  • btnOn.Click -> if BluetoothClient.IsConnected then call BluetoothClient.SendText("ON") then set label to BluetoothClient.ReceiveText(1000)
  • btnOff.Click -> send "OFF" similarly.
  1. Build (BuildApp (provide QR code) or download .apk) and install on your phone.

9) Test flow

  1. Start the Python server on Pi.
  2. Pair the phone and Pi (if not already).
  3. Open the App Inventor app on phone → tap ListPicker → select PiLight (or the Pi MAC) → connect.
  4. Tap ON — LED should light. OFF turns it off.
  5. Check Pi console logs to see received commands.

10) Troubleshooting

  • If ListPicker shows no devices: make sure the Pi is discoverable/power on and devices are paired via Android settings or use bluetoothctl on Pi.
  • If connection fails: check firewall, ensure bluetooth service running, and pairing/trust completed.
  • If client_sock.recv() blocks or times out: server sets a timeout; adjust as needed.
  • If using a relay for mains, ensure relay is powered correctly and isolate mains wiring from logic.

11) Security & improvements

  • Right now server accepts any paired client — if you want authorized control only from your phone, implement a simple passcode handshake (e.g., client sends PASS:yourcode on connect).
  • For better UI/UX, add feedback from server (OK:ON) and parse that in the app to update UI.
  • For multiple lights, accept commands like LIGHT1:ON, LIGHT2:OFF.
  • For BLE (if you prefer BLE and MIT App Inventor BLE extension), the architecture differs — BLE peripheral on Pi is more complex. RFCOMM is easiest for App Inventor built-in BluetoothClient.

12) Example quick test using phone terminal app

If you want to quickly test from any Android Bluetooth terminal app (instead of building AI2 app), install "Bluetooth Terminal" from Play Store, connect to Pi and type ON/OFF.


13) Recap (minimal quick checklist)

  1. Wire LED to GPIO17 + GND with resistor.
  2. On Pi: sudo apt update && sudo apt install -y bluetooth bluez libbluetooth-dev python3-pip then pip3 install pybluez gpiozero.
  3. Put Python server on Pi and run it.
  4. Pair phone with Pi (Android settings or bluetoothctl).
  5. Build MIT App Inventor app with BluetoothClient and buttons to send ON / OFF.
  6. Connect and test.

If you do NOT have inbuilt module, then your Pi 5 board has no Bluetooth, and you must use a USB Bluetooth dongle.

1 Like