- Arduino (s)
- cc2541 – BLE module(s) for Arduino
- Raspberry Pi
- Bluetooth 4.0 USB dongle for raspberry pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|from bluepy.btle import Scanner, DefaultDelegate, Peripheral|
|def __init__(self, number):|
|self.number = number|
|def handleNotification(self, cHandle, data):|
|bt_addrs = ['00:15:83:00:45:98', '00:15:83:00:86:72']|
|connections = |
|connection_threads = |
|scanner = Scanner(0)|
|class ConnectionHandlerThread (threading.Thread):|
|def __init__(self, connection_index):|
|self.connection_index = connection_index|
|connection = connections[self.connection_index]|
|connection.writeCharacteristic(37, 'Thank you for the notification!')|
|devices = scanner.scan(2)|
|for d in devices:|
|if d.addr in bt_addrs:|
|p = Peripheral(d)|
|t = ConnectionHandlerThread(len(connections)–1)|
Arduino Code can be seen in:
The main thread of the program keeps scanning the existing unconnected Bluetooth devices using the Scanner object.
If the devices have address existing in the bt_arrs array, we start a connection with it by initiating the Peripheral object and add it into the connections array.
To avoid the searching being blocked by the communication of each connection, every connection will be handled by a separate ConnectionHandler Thread.
Within the connection thread, the communications between the Pi and the Arduino(s) are handled by using waitForNotification and writeCharacteristic function of the bluepy library.
Why do we write data to handler 37?:
By looking at the documentation of the BLE module, we know that both data sending from and to the BLE module are stored in the same places (20 Bytes). Therefore by observing the data sent from the BLE module, we know the data should be written to Handler 37.
The output below is showing 1 Arduino with 2 BLE modules and the Arduino is doing:
- send count via BLE modules #0
- count ++
- send count via BLE modules #1
- count ++
- and loop
From the output of the program, we can see
- It is continuously scanning devices
- It is able to communicate with Connection 0 & Connection 1.
- All notifications are from handler 37.