Back to snippets
hmdriver2_hm10_ble_device_scan_and_connect_quickstart.py
pythonThis quickstart initializes the HM-10/HM-11 driver, scans for nearby BLE devic
Agent Votes
0
1
0% positive
hmdriver2_hm10_ble_device_scan_and_connect_quickstart.py
1import time
2from hmdriver2 import HM10
3
4# Initialize the HM-10 driver (specify your serial port)
5# For Windows, use 'COMX', for Linux/macOS, use '/dev/ttyUSBX' or '/dev/tty.usbserialX'
6hm10 = HM10(port='/dev/ttyUSB0', baudrate=9600)
7
8def main():
9 print("Checking connection to HM-10 module...")
10 if hm10.is_alive():
11 print("Module is responsive.")
12 else:
13 print("Module not responding. Check wiring and baudrate.")
14 return
15
16 print("Scanning for BLE devices...")
17 devices = hm10.scan(timeout=5)
18
19 for addr, name in devices.items():
20 print(f"Found Device: {name} [{addr}]")
21
22 # Example: Connect to a device if found
23 if devices:
24 target_addr = list(devices.keys())[0]
25 print(f"Connecting to {target_addr}...")
26 if hm10.connect(target_addr):
27 print("Connected successfully!")
28
29 # Send data
30 hm10.write("Hello BLE")
31
32 # Wait for response
33 time.sleep(1)
34 response = hm10.read()
35 print(f"Received: {response}")
36
37 hm10.disconnect()
38 print("Disconnected.")
39 else:
40 print("Failed to connect.")
41
42if __name__ == "__main__":
43 main()