In this project, we are going to create a system allowing to turn on and off a lamp (by bluetooth) using the Micro: bit card and a computer.
This is why we are going to create two programs: one for the computer and the other for the Micro:bit card.
Here is the makecode program which allows you to connect the Micro: bit card to the HC-06 bluetooth module and to receive a message containing the order to turn the lamp on or off.
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 28 29 30 31 32 33 34 35 36 37 38 |
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_release(key): global result #print('released %s' % key) #result ='released %s' % key+'\n' if result != str(0)+'\n': #or result == str(2)+'\n' or result == str(3)+'\n' or result == str(4)+'\n': result = str(0)+'\n' print(result) result_bytes = result.encode('utf_8') bluetooth.write(result_bytes) def on_key_pressed(key): global result print('pressed %s' % key) result1 ='%s' % key if result == str(0)+'\n': if result1=='<97>' : # if you press the 1 key on the keyboard result = str(1)+'\n' print(result) if result1=='<96>' : # if you press the 0 key on the keyboard result = str(2)+'\n' print(result) result_bytes = result.encode('utf_8') bluetooth.write(result_bytes)#envoi des données au module HC-06 with keyboard.Listener(on_release = on_key_release,on_press=on_key_pressed) as listener: listener.join() |