Search code examples
pythonpython-3.xbluetoothpybluez

How to recieve data from BT module (HC-05) by using python on Windows 10?


I am trying to receive GPS data from my HC-05 bluetooth module. I can see complete data in any serial plotter program, however I need to use Python executable for my Raspberry PI.

I have tried below code that I found from internet;

"""
A simple Python script to receive messages from a client over 
Bluetooth using PyBluez (with Python 2). 
"""

import bluetooth

hostMACAddress = 'C8:09:A8:56:11:EC'  # The MAC address of a Bluetooth adapter on the server. The server might have
# multiple Bluetooth adapters.
port = 9
backlog = 1
size = 1024
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.bind((hostMACAddress, port))
s.listen(backlog)
try:
    client, clientInfo = s.accept()
    while 1:
        data = client.recv(size)
        if data:
            print(data)
            client.send(data)  # Echo back to client
except:
    print("Closing socket")
    client.close()
    s.close()

However It gives me error below, for the line "s.bind((hostMACAddress, port))". I have run "ipconfig /all" in cmd window to see bluetooth adapter MAC Adress, and checked advanced settings in "bluetooth devices" of my computer to find corresponding port.

Other problem I suspect is that I am using Python 3.8 while in comment area it says written with Python 2. I am not sure if 3.xx is backward backward compatible with 2.xx.

C:\Users\aliul\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/aliul/PycharmProjects/pythonProject/main.py
Traceback (most recent call last):
  File "C:/Users/aliul/PycharmProjects/pythonProject/main.py", line 14, in <module>
    s.bind((hostMACAddress, port))
  File "C:\Users\aliul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\bluetooth\msbt.py", line 84, in bind
    bt.bind (self._sockfd, addr, port)
OSError: G

I am new to python and any help would be highly appreciated! Thanks.


Solution

  • I've figured out recieving data importing "serial" package instead of "bluetooth" of pybluez. Source code is below, all you need to do is to find the serial port adress of your socket and setting baudrate, timeout, parity and stopbits parameters according to the bluetooth module you have!

    import serial
    
    serialPort = serial.Serial(port='COM8', baudrate=9600, timeout=0, parity=serial.PARITY_EVEN, stopbits=1)
    size = 1024
    
    while 1:
        data = serialPort.readline(size)
    
        if data:
            print(data)