fbpixel
Étiquettes : , ,
5
(1)

Dans ce tutoriel, nous allons apprendre comment activer, gérer et tester le Bluetooth sur un ESP32 en utilisant le langage de programmation Arduino. Le Bluetooth est une technologie sans fil largement utilisée pour la communication entre dispositifs électroniques. Elle permet très rapidement de transformer votre système en objet connecté.

Matériels

  • Un module ESP32 (Bluetooth+Wifi embarqué)
  • Un ordinateur avec Python installé ou smartphone
  • Câble USB pour la connexion ESP32-ordinateur

Environnement et Configuration de l’IDE

Pour programmer votre ESP32 avec l’IDE Arduino, vous pouvez suivre ce tutoriel précédent.

Récupérer l’adresse MAC

Cette information n’est pas forcément nécessaire mais il est toujours bon de savoir comment récupérer l’adresse MAC sur l’ESP32

#include "esp_bt_main.h"
#include "esp_bt_device.h"
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

void printDeviceAddress() {
  const uint8_t* point = esp_bt_dev_get_address();
  for (int i = 0; i < 6; i++) {
    char str[3];
    sprintf(str, "%02X", (int)point[i]);
    Serial.print(str);
    if (i < 5){
      Serial.print(":");
    }
  }
}
void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32BT");
  Serial.print("MaxAddr : ");
  printDeviceAddress();

}

void loop() {}

Output

14:42:43.448 -> MaxAddr : 3C:61:05:31:5F:12

Communication Série via Bluetooth

La communication Bluetooth s’active comme la communication série. La méthode est similaire pour le module HC-06

#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32BT"); //Bluetooth device name
  Serial.println("The device started, now you can pair it with bluetooth!");
}

void loop() {
  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(20);
}

N.B.: Il semble qu’il y ait un moyen d’ajouter un code PIN mais impossible de le faire marcher.

SerialBT.setPin(pin);
SerialBT.begin("ESP32BT", true); //BT with PIN

Appairage

Une fois la configuration du module effectuée comme vous le désirez, vous pouvez appairé l’ESP32 avec le système de votre choix comme n’importe quel périphérique Bluetooth. Sélectionnez le nom dans la liste des périphériques détectés (nom ESP32BT)

Test de la communication Bluetooth à l’aide de Serial Bluetooth Terminal

Nous allons tester la communication bluetooth à l’aide de l’application Serial Bluetooth Terminal

Le message est bien échangé entre le téléphone et l’ESP32 via Bluetooth

Code pour récupérer la commande complète

Dans le code précédent, on faisait une copie byte par byte du message pour le renvoyer au moniteur. Ici nous allons enregistrer la commande complète dans un String msg. Cela vous permettra d’analyser la commande et de définir l’action correspondante (ex: allumer/éteindre une LED)

#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
String msg;

BluetoothSerial SerialBT;
const char *pin = "1234";

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32BT"); //Bluetooth device name
  Serial.println("ESP32BT device started, now you can pair it!");
}

void loop(){
  readSerialPort();
  
  // Send answer to master
  if(msg!=""){
    Serial.print("Master sent : " );
    Serial.println(msg);
    SerialBT.print("received : "+msg);
    msg=""; 
  }
}

void readSerialPort(){
 while (SerialBT.available()) {
   delay(10); 
   if (SerialBT.available() >0) {
     char c = SerialBT.read();  //gets one byte from serial buffer
     msg += c; //makes the string readString
   }
 }
 SerialBT.flush();
}

Communiquer entre ESP32 et Python via Bluetooth

Vous pouvez gérer la communication Bluetooth depuis votre PC.

Pour cela installer le paquets PyBluez

python -m pip install pybluez

Detect bluetooth devices

import bluetooth

target_name = "ESP32BT"
target_address = None

nearby_devices = bluetooth.discover_devices(lookup_names=True,lookup_class=True)
print(nearby_devices)
for btaddr, btname, btclass in nearby_devices:
	if target_name == btname:
		target_address = btaddr
		break

if target_address is not None:
	print("found target {} bluetooth device with address {} ".format(target_name,target_address))
else:
	print("could not find target bluetooth device nearby")

Output

[('88:C6:26:91:30:84', 'UE\xa0BOOM\xa02', 2360344), ('88:C6:26:7E:F2:7A', 'UE\xa0BOOM\xa02', 2360344), ('4C:EA:AE:D6:92:08', 'OPPO A94 5G', 5898764), ('41:42:DD:1F:45:69', 'MX_light', 2360344), ('3C:61:05:31:5F:12', 'ESP32BT', 7936)]
found target ESP32BT bluetooth device with address 3C:61:05:31:5F:12

Se connecter et communiquer avec l’ESP32

Voici un script Python pour se connecter automatiquement à l’appareil Bluetooth ESP32 depuis un PC

import bluetooth
import socket

target_name = "ESP32BT"
target_address = None

nearby_devices = bluetooth.discover_devices(lookup_names=True,lookup_class=True)
print(nearby_devices)
for btaddr, btname, btclass in nearby_devices:
	if target_name == btname:
		target_address = btaddr
		break

if target_address is not None:
	print("found target {} bluetooth device with address {} ".format(target_name,target_address))

	""" # With PyBluez NOT WORKING
	serverMACAddress = target_address
	port = 1
	s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
	s.connect((serverMACAddress, port))
	while 1:
		text = raw_input() # Note change to the old (Python 2) raw_input
		if text == "quit":
			break
		s.send(text)
		data = s.recv(1024)
		if data:
			print(data)
	sock.close()"""
	
	
	
	serverMACAddress = target_address
	port = 1
	s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
	s.connect((serverMACAddress,port))
	print("connected to {}".format(target_name))
	while 1:
		text = input()
		if text == "quit":
			break
		s.send(bytes(text, 'UTF-8'))
		data = s.recv(1024)
		if data:
			print(data)
	s.close()

else:
	print("could not find target bluetooth device nearby")



N.B.: Seul la libraire socket fonctionne pour la communication Bluetooth. Il semble y avoir un soucis de maintenance sur la librairie PyBluez

Applications

Sources

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?