Raspberry Pi
Tutorial de Rapberry Pi en español.
- Juan Antonio Villalpando -
Volver al índice del tutorial
____________________________
31.- Bluetooth.
p9B3_enviar_RaspBerry.aia
- Vamos a enviar información desde App Inventor al Bluetooth de Raspberry.
- Enviaremos ciclos continuos de 5 bytes, un byte cada 600 mili segundos.
11001100,
00110010,
11011011,
10110110,
00000000
_____________________________________
- Diseño.
_____________________________________
- Bloques.
- Para parar enviamos la letra "Q" mediante el Button2, observa el código (no está en la imagen).
____________________________
- Raspberry.
__________________________
1.- Instalación y arranque.
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install bluetooth [esto para bluetooth en modo gráfico]
sudo apt-get install bluez
sudo apt-get install python-bluez
sudo apt-get install bluez-utils (no es necesario)
sudo apt-get install python-bluetooth (no es necesario)
service bluetooth start
service bluetooth status [Para salir pulsar Ctrl Z]
- lsusb, para ver los USB reconocidos.
-
BlueZ protocolo oficial de LINUX para trabajar con Bluetooth.
-
python-bluez Library para la comunicación por Bluetooth, se utilizar para enviar y recib ir mediante RFCOMM con Python.
__________________________
2.- Activación y vinculación.
- Activamos el Bluetooth y lo vinculamos con nuestro móvil.
sudo bluetoothctl
[bluetooth]# power on
[bluetooth]# agent on
[bluetooth]# discoverable on
[bluetooth]# pairable on
[bluetooth]# scan on
[bluetooth]# pair MAC BLUETOOTH DEL MÓVIL
[bluetooth]# paired-devices
[bluetooth]# help
[bluetooth]# quit
______________________________________________________________________________
- Las siguientes órdenes no hacen falta ejecutarlas, solo están puesta como información:
#
sudo hciconfig hci0 piscan
Esto es igual que lo anterior.
hcitool scan
hcitool dev [Muestra la Mac del Bluetooth]
hciconfig -a [Muestra información del Bluetooth]
sudo rfcomm connect hci0
______________________________________________________________________________
__________________________
3.- Establecimiento del canal 22.
- Vamos a activar el canal 22
sudo sdptool add --channel=22 SP
- Comprobamos si ese puerto está activado:
sudo sdptool browse local
- En caso que obtengas este error:
Failed to connect to SDP server on FF:FF:FF:00:00:00:No such file or directory
- Entra en el archivo:
sudo nano /lib/systemd/system/bluetooth.service
- Añade --compat a esta línea:
ExecStart=/usr/lib/bluetooth/bluetoothd --compat
- Reinicia el servicio bluetooth:
sudo systemctl daemon-reload
sudo systemctl restart bluetooth
- Cambia los permisos de este archivo:
sudo chmod 777 /var/run/sdp
- Ejecuta de nuevo:
sudo sdptool browse local
- Debemos obtener algo así... observa el Channel: 22
Service Name: Serial Port
Service Description: COM Port
Service Provider: BlueZ
Service RecHandle: 0x10003
Service Class ID List:
"Serial Port" (0x1101)
Protocol Descriptor List:
"L2CAP" (0x0100)
"RFCOMM" (0x0003)
Channel: 22
Language Base Attr List:
code_ISO639: 0x656e
encoding: 0x6a
base_offset: 0x100
Profile Descriptor List:
"Serial Port" (0x1101)
Version: 0x0100
__________________________
4.- Script servidor Bluetooth con Phyton.
- En el Raspberry creamos este archivo llamado bluetooth4.py en Python, con el siguiente contenido...
- El puerto debe ser el establecido en port = 22 ya que anteriormente escribimos esta orden:
sudo sdptool add --channel=22 SP
- Si apagamos el sistema y lo arrancamos, debemos volver a establecer ese channel=22
bluetooth4.py |
import bluetooth
server_sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
port = 22
server_sock.bind(("",port))
server_sock.listen(1)
client_sock,address = server_sock.accept()
print ("Conexion realizada con: ", address)
while True:
recvdata = client_sock.recv(1024)
print ("Informacion recibida: %s" % recvdata)
if (recvdata == "Q"):
print ("Finalizado.")
break
client_sock.close()
server_sock.close()
|
__________________________
5.- Ejecución del Script.
- Ahora lo ejecutamos desde el terminal de Raspberry:
python2 bluetooth4.py
(con python3, ver más abajo)
- Después pulsamos el Botón de inicio de la aplicación de App Inventor, debemos obtener:
- Se pueden conectar varios Bluetooth a la vez al servidor del Raspberry.
_______________________
- Con Python3
sudo apt-get install bluetooth libbluetooth-dev
sudo python3 -m pip install pybluez
__________________________
6.- Otro ejemplo.
- Cuando recibe el dato 0 o el 1, apaga o enciende el LED 21
https://circuitdigest.com/ microcontroller-projects/ controlling-raspberry-pi-gpio- using-android-app-over- bluetooth
bluetooth4.py |
import bluetooth
import RPi.GPIO as GPIO #calling for header file which helps in using GPIOs of PI
LED=21
GPIO.setmode(GPIO.BCM) #programming the GPIO by BCM pin numbers. (like PIN40 as GPIO21)
GPIO.setwarnings(False)
GPIO.setup(LED,GPIO.OUT) #initialize GPIO21 (LED) as an output Pin
GPIO.output(LED,0)
server_socket=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
port = 22
server_socket.bind(("",port))
server_socket.listen(1)
client_socket,address = server_socket.accept()
print "Accepted connection from ",address
while 1:
data = client_socket.recv(1024)
print "Received: %s" % data
if (data == "0"): #if '0' is sent from the Android App, turn OFF the LED
print ("GPIO 21 LOW, LED OFF")
GPIO.output(LED,0)
if (data == "1"): #if '1' is sent from the Android App, turn OFF the LED
print ("GPIO 21 HIGH, LED ON")
GPIO.output(LED,1)
if (data == "Q"):
print ("Quit")
break
client_socket.close()
server_socket.close()
|
- Observa que parará cuando reciba la letra "Q".
__________________________
7.- Raspberry envía números a la aplicación cada segundo.
p9B3_recibir_RaspBerry.aia
- Con este código vamos a crear un temporizador, cada segundo se enviará el tiempo restante a la aplicación.
_____________________________________
- Bloques.
_____________________________________
- RaspBerry.
- Cuenta atrás de 4 minutos.
bluetooth5.py |
import time
import datetime
import bluetooth
server_sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
port = 22
server_sock.bind(("",port))
server_sock.listen(1)
client_sock,address = server_sock.accept()
print ("Conexion realizada con: ", address)
# Create class that acts as a countdown
def countdown(h, m, s):
# Calculate the total number of seconds
total_seconds = h * 3600 + m * 60 + s
# While loop that checks if total_seconds reaches zero
# If not zero, decrement total time by one second
while total_seconds > 0:
# Timer represents time left on countdown
timer = datetime.timedelta(seconds = total_seconds)
# Prints the time left on the timer
print(timer)
client_sock.send(str(timer))
client_sock.send("\n")
# Delays the program one second
time.sleep(1)
# Reduces total time by one second
total_seconds -= 1
print("Bzzzt! The countdown is at zero seconds!")
# Inputs for hours, minutes, seconds on timer
h = 0 #input("Enter the time in hours: ")
m = 4 #input("Enter the time in minutes: ")
s = 0 #input("Enter the time in seconds: ")
countdown(int(h), int(m), int(s))
|
- Ahora lo ejecutamos desde el terminal de Raspberry:
python2 bluetooth5.py
- Primero ejecutamos el script y después pulsamos el botón "Inicio - Start" en la aplicación.
__________________________
8.- La aplicacion envía un número, Raspberry le devuelve el doble de ese número.
p9B3_enviar_recibirRaspBerry3.aia
- Escribimos un número, pulsamos el botón "Enviar", llegará por Bluetooth al Raspberry y éste nos devolverá el doble del número enviado.
_____________________________________
- Bloques.
_____________________________________
- RaspBerry.
- Recibe un número y devuelve el doble.
bluetooth6.py |
import bluetooth
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
port = 22
server_sock.bind(("",port))
server_sock.listen(1)
client_sock,address = server_sock.accept()
print ("Conexion realizada con: ", address)
while True:
recvdata = client_sock.recv(1024)
print ("Recibe: %s" % recvdata)
doble = 2 * float(recvdata)
print ("Enviar doble: %s" % doble)
client_sock.send(str(doble))
client_sock.send("\n")
if (recvdata == "0"):
print ("Finalizado.")
break
client_sock.close()
server_sock.close()
|
- Ahora lo ejecutamos desde el terminal de Raspberry:
python2 bluetooth6.py
- Primero ejecutamos el script y después pulsamos el botón "Inicio - Start" en la aplicación.
_____________________________________________________
- Errores.
Si te sale este error:
bluetooth.error: (98, 'Address already in use')
significa que ya existe una conexión por ese puerto.
Escribimos en el terminal:
sudo ps aux | grep bluetooth
o también
sudo ps -fA | grep python
Observamos el PID del Bluetooth y lo cerramos.
sudo kill -9 1164
-[También puedes cerrar el Terminal y abrir otro]
-----------------------------------------------------
- Error al escribir la orden
service bluetooth status
- Lo ignoramos.
_____________________________________________________
- Instalación más fácil.
https://howchoo.com/pi/bluetooth-raspberry-pi
___________________________________________________
|