Serial Communication using Python Linux through BLE with Arduino HC-06

Kitsunetic·2020년 11월 26일
0

Bluetooth connection

Bluetooth settings

Turn on PC and Bluetooth module.

Update HC-06 BLE name and pin numbers(Search about HC-06 command)

Connect to the bluetooth with Linux settings.
If you want to do this part on Python, search about pybluez module.

Get bluetooth address

Get address of the module from settings.

Or you can find address with pybluez module.
This is source code to get bluetooth address.

import bluetooth

print("Performing BLE inquiry...")
nearby_devices = bluetooth.discover_devices(duration=8, lookup_names=True,
                                            flush_cache=True, lookup_class=False)

for addr, name in nearby_devices:
    print(addr, name)

This code referred to pybluez official example

rfcomm bind

Bind BLE with desktop with rfcomm command.

rfcomm bind 0 98:D3:31:FC:73:2D

0 is the port number.
98:D3:31:FC:73:2D is the address of my bluetooth module.

Check binding

Check weather the file /dev/rfcomm0 exist.
If your port number is N, the file name will be /dev/rfcommN

ls /dev

From now on, you can use /dev/rfcomm0 file like serial IO files /dev/ttyS.

Serial communication

import serial

DEVICE = '/dev/rfcomm0'
BAUD_RATE = 9600

# Connect to the device
s = serial.Serial(DEVICE, BAUD_RATE)
print('Connect to', DEVICE)

# Send data
s.write(b'hello\n')

# Receive data
data = s.read(3)
print(data)

0개의 댓글