In this project we will create a system allowing to turn on and off a lamp (by bluetooth) using ESP32 and a computer.
This is why we are going to create two programs: one for the computer and the other for ESP32.
Here is the program which allows you to connect the ESP32 to the HC-06 bluetooth module and to receive a message containing the order to turn the lamp on or off.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
from machine import UART from machine import Pin import time import utime lampe=Pin(23,Pin.OUT)# R猫gle la broche D23 de la carte ESP32 en mode sortie uart = UART(2, 9600) uart.init(9600, bits=8, parity=None, stop=1) print(uart) while True: if uart.any(): while uart.any(): buf = uart.read() if str(buf,'utf-8')=='allumer' : lampe.value(1) # Allumer la lampe else: lampe.value(0) # Allumer la lampe print('received:',buf) utime.sleep_ms(15) utime.sleep_ms(10) try: uart.write("OK") print('sent response') except OSError: pass |
Here is the program which allows the computer to connect and send data to the HC-06 bluetooth module.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import serial import time from pynput import keyboard evenement="" print("Start") port="COM20" #This will be different for various devices and on windows it will probably be a COM port. bluetooth=serial.Serial(port, 9600)#Start communications with the bluetooth unit print("Connected") bluetooth.flushInput() #This gives the bluetooth a little kick result = str(0)+'\n' def on_key_pressed(key): global result print('pressed %s' % key) result1 ='%s' % key if result1=='<97>' : # if you press 1 on the keyboard result = 'allumer'+'\n' print(result) if result1=='<96>' : # if you press 0 on the keyboard result = 'eteindre'+'\n' print(result) result_bytes = result.encode('utf_8') bluetooth.write(result_bytes) with keyboard.Listener(on_press=on_key_pressed) as listener: listener.join() |