I have been trying to connect my hc 05 bt module with my laptop and to achieve a communication with Idle.
At first i connected my bt device manually from laptop's bluetooth settings and then I was able to get the module's bt address by using the following code:
import bluetooth
target_name = "HC-05"
target_address = None
nearby_devices = bluetooth.discover_devices()
for bdaddr in nearby_devices:
if target_name == bluetooth.lookup_name( bdaddr ):
target_address = bdaddr
break
if target_address is not None:
print "found target bluetooth device with address ", target_address
else:
print "could not find target bluetooth device nearby"
I received the bluetooth address as "98:D3:31:70:7D:2D"
Now i wrote the following code to connect HC-05 via python..
bd_addr = "98:D3:31:70:7D:2D"
port = 20
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))
sock.send("1")
sock.close()
Now i browse through my laptop's bluetooth comm port settings and found 2 things
1st...
COM19
Direction--- Incoming...
Name--- HC-05
2nd...
COM20
Direction--- Outgoing
...
Name--- HC-05 'Dev B'
Hence I chose COM20 as I want to transmit data from Python.
When I run this code i get error:
Traceback (most recent call last):
File "C:\Python27\TestBluetooth.py", line 26, in <module>
sock.connect((bd_addr, port))
File "C:\Python27\lib\site-packages\bluetooth\msbt.py", line 72, in connect
bt.connect (self._sockfd, addr, port)
IOError: A socket operation failed because the destination host was down.
I tried both COM19 and COM20 but got the same error.
My Bluetooth is connected via TX pin to arduino's RX pin and the arduino is connected to my PC so there is no error of COM port sharing that occurs sometimes.
Also when I connect my bluetooth module with laptop bluetooth and open Bluetooth Serial terminal and transmit data from there it works fine.
So there's some problem in my understanding and writing of Python code.
Please help...
Related
I am making app in python, that connects with Arduino. I want this app to work on different computers, when arduino is connected to any port. I was trying to do a function that checks to which port is arduino connected to:
def arduinoConnect():
t=0
temp = 0;
while 1:
i = str(t)
try:
temp = serial.Serial('com'+i, 9600)
if temp:
print("COM" + i + " Connected")
break
except:
print("COM" + i + " Empty")
t = t + 1
if t == 41:
break
return temp
But this code only sees if anything is connected, so when i am also using some bluetooth devices, or other microcontrolers, it takes the device that is connected to the com port with the lowest number.
Next idea was to take PID and VID number:
import serial
import serial.tools.list_ports
for port in serial.tools.list_ports.comports():
print(port.hwid)
But i have one more device connected to COM Port, that gives exactly the same numbers, only different location:
USB VID:PID=1A86:7523 SER= LOCATION=1-4
USB VID:PID=1A86:7523 SER= LOCATION=1-5
I also tried to get a specific id of a connected USB device:
import serial
def serial_ports():
ports = ['COM%s' % (i + 1) for i in range(256)]
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
print(s)
except (OSError, serial.SerialException):
pass
return result
if __name__ == '__main__':
print(serial_ports())
And it returns the ID of a device, which is unique to every device, but changes every time i disconnect and connect again the device.
My question is how to let my code recognize and connect one and only device I want? On any computer, connected to any port.
I understand your problem as such that you wish to have python code that can connect to an arduino device which is connected to any port, on any computer.
So the solution is to uniquely identify the arduino device even when other devices are plugged in.
It should work when you get the device serial number:
import serial
import serial.tools.list_ports
def get_arduino_serial_number():
for port in serial.tools.list_ports.comports():
if 'Arduino' in port.description:
return port.serial_number
return None
whether this works or not is dependent on port.description.
Change USB COM port description
Get ports by description
With the serial number of the Arduino device, you can then connect to it using:
ser = serial.Serial(port='COMx', baudrate=9600, timeout=1,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
Opening serial ports | pySerial
I found online multiple sources that said that discover_devices scans for active bluetooth devices, but for me it was printing all the bluetooth devices that remembered on my computer. Is there something wrong with my code/settings?
`
import bluetooth
nearby_devices = bluetooth.discover_devices(lookup_names=True)
print(nearby_devices)
for addr, name in nearby_devices:
print('\nname = ', name, "\naddress = ", addr)
`
Server code:
import bluetooth
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
port = 1
server_sock.bind(("",port))
server_sock.listen(1)
client_sock,address = server_sock.accept()
print ("Accepted connection from ",address)
data = client_sock.recv(1024)
print ("received [%s]" % data)
client_sock.close()
server_sock.close()
client code:
import bluetooth
bd_addr = " 50:29:f5:36:ed:00 " #bluetooth address of mobile
port = 1
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr ,1))
sock.send("hello!!")
sock.close()
Iam getting OS error A which is as shown below
Traceback (most recent call last):
File "C:\Users\katrer2\Bluetooth_communication\Bluetooth\example2.py", line 9, in
sock.connect((bd_addr ,1))
File "C:\Users\katrer2\AppData\Local\Programs\Python\Python37\lib\site-packages\bluetooth\msbt.py"
line 96, in connect
bt.connect (self._sockfd,addr,port)
OSError: A
Python version 3.7.5.
Please help me to find out where I am going wrong or suggest any other solution via which I can connect to a device using Bluetooth.
It looks like it might be an issue with the pybluez library on Windows 10:
https://github.com/pybluez/pybluez/issues/349
I want to set up serial Bluetooth communication between a Raspberry Pi 3 with integrated Bluetooth module and a Windows 10 machine. The raspi is the server and runs a python script, that handles the connection and the data transmission. I have set it all up, following several tutorials in the internet and its working really good on the server side. I have tested the server with a serial terminal on my android phone and it was working as expected: All the messages were transferred correctly and it stayed connected as long as i wanted. Testing with my windows machine, on the other hand, caused a lot of problems. I have solved most of them and now i can connect my windows machine, over a serial terminal, to the raspi. My problem now is, that, after a short while, the connection dies, usually after 10 to 40 seconds, and i could not find a fix for that. The error message on windows is: cannot open COM4 and the error message on the raspi is: bluetooth.btcommon.BluetoothError: [Errno 110] Connection timed out.
Here is my python script, id that is actually the problem:
import serial, bluetooth, subprocess, select
serialPort0 = serial.Serial(
port = '/dev/serial0',
baudrate = 115200,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 1
)
server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
server_sock.bind(("", bluetooth.PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
bluetooth.advertise_service(server_sock, "bluetoth_server", service_id=uuid,
service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
profiles=[bluetooth.SERIAL_PORT_PROFILE],
# protocols=[bluetooth.OBEX_UUID]
)
print("Waiting for connection on RFCOMM channel", port[1], ", addr", port[0])
client_sock, client_info = server_sock.accept()
print("Accepted connection from", client_info)
client_sock.setblocking(0)
while True:
if not serialPort0.isOpen:
raise Exception("Serial port closed unexpected")
break
ready = select.select([client_sock], [], [], 0.5)
if ready[0]:
blu_data = client_sock.recv(4096)
if not blu_data:
break
serialPort0.write(blu_data)
ser_data = serialPort0.readline().decode("utf-8")
client_sock.send(ser_data)
client_sock.close()
server_sock.close()
It reads data from a serial port and from a serial Bluetooth port and sends it to the other one respectively.
I am at a point, where i don't know what else to try and I would really appreciate some help. Thank you in advance.
Your description related to timeout would be pointed to
/etc/bluetooth/main.conf
Bluetooth configuration file.
You will need to uncomment the pairabletimeout=0 that will prevent the timeout problems.
You may want to see Raspberry Bluetooth configuration (recent answer) for details.
Bluetooth Serial Configuration
I am trying to open a connection with a Lego EV3 brick, whose serial port is /dev/tty.EV3-SerialPort, I am on mac 10.6.8. I get a Resource busy when I do this, yet when I use other API's to connect (writing to the serial port not through pyserial) it does not show an error. I would like to find a way to get around this error. Why is it busy, all other bluetooth applications are disabled. Here is my code:
test.py:
import serial
import time
ser = serial.Serial('/dev/tty.EV3-SerialPort', 19200, timeout=1) # open first serial port
ser.close()
ser.open()
time.sleep(1)
ser.close()
print "closed"
Here is the error it outputs:
File "test.py", line 7, in <module>
ser.open()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/serial/serialposix.py", line 289, in open
self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)
OSError: [Errno 16] Resource busy: '/dev/tty.EV3-SerialPort'
A popup also presents itself saying:
A Bluetooth serial failure has occurred.
Failed to open an RFCOMM serial channel.
Check if authentication needs to be enabled in your device
I have been able to communicate with the EV3 by just opening the serial port as a file rather than using the serial module.
with open('/dev/tty.EV3-SerialPort', 'w+', 0) as bt:
See https://bricks.stackexchange.com/a/4257/3498 for a complete example.
I used exactly your example and works to me, check out (in my case the connection name is different as shown below:).
EV3 = serial.Serial('/dev/tty.EV3-N1-SerialPort', 19200, timeout=1)