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.
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
ON
, OFF
, TOGGLE
, STATUS
).BluetoothClient
component to connect and send ON
/OFF
text messages.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.
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).
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.
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
.
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
Open MIT App Inventor (ai2.appinventor.mit.edu), start a new project (e.g., PiLight
).
Designer screen — add components:
User Interface:
ListPicker
(Name: ListPicker_BT
) — text: "Choose Bluetooth Device"Button
(text: "Connect") — or use the ListPicker to select and connectButton
(text: "ON") — name btnOn
Button
(text: "OFF") — name btnOff
Button
(text: "TOGGLE") — optionalLabel
lblStatus
— to show connection and responseConnectivity:
BluetoothClient
(non-visible) — name BluetoothClient1
(Optional) Notifier
for messages.
Blocks (logic). Use these building blocks (described as steps — you can reproduce in App Inventor blocks editor):
BeforePicking (ListPicker_BT.BeforePicking):
ListPicker_BT.Elements
to BluetoothClient1.AddressesAndNames
AfterPicking (ListPicker_BT.AfterPicking):
BluetoothClient1.Connect
with address
= ListPicker_BT.Selection
BluetoothClient1.IsConnected
then set lblStatus.Text
to "Connected"btnOn.Click:
BluetoothClient1.IsConnected
then call BluetoothClient1.SendText("ON")
BluetoothClient1.ReceiveText(1000)
to get response and set lblStatus.Text
to responsebtnOff.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:
Build
→ App (provide QR code)
or download .apk) and install on your phone.PiLight
(or the Pi MAC) → connect.ON
— LED should light. OFF
turns it off.ListPicker
shows no devices: make sure the Pi is discoverable/power on and devices are paired via Android settings or use bluetoothctl
on Pi.bluetooth
service running, and pairing/trust completed.client_sock.recv()
blocks or times out: server sets a timeout; adjust as needed.PASS:yourcode
on connect).OK:ON
) and parse that in the app to update UI.LIGHT1:ON
, LIGHT2:OFF
.BluetoothClient
.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
.
sudo apt update && sudo apt install -y bluetooth bluez libbluetooth-dev python3-pip
then pip3 install pybluez gpiozero
.bluetoothctl
).BluetoothClient
and buttons to send ON
/ OFF
.If you do NOT have inbuilt module, then your Pi 5 board has no Bluetooth, and you must use a USB Bluetooth dongle.