Can someone show me the simplest way to just print received bluetooth stream?
I need to verify that a computer receives data that a mobile phone sends via bluetooth.
I have something lik this:
import serial
import time
import sys
port = serial.Serial('COM6', 19200, timeout=2)
while True:
line = port.readline()
line = line.split()
print >>output, line
output.flush()
But I am not sure if it is correct for bluetooth.
PyBluez should be enough for WindowsXP, provided you have a compatible dongle.
It has examples for what you need.
Related
I am doing an instrument integration where the instrument name is Horiba ES60. I am using an RS232 port for communicating for PC and instrument.
I have tested the PC and instrument connection through the Advance Serial Port logger and am getting the monitor result.
I have confirmed that the instrument setting and my script setting are the same.
I have written a simple script in python to read the port data. below is the script.
import time
import serial
sSerialPort = serial.Serial(port = "COM1", baudrate=9600,
bytesize=8, timeout=1, stopbits=serial.STOPBITS_ONE)
sSerialString = "" # Used to hold data coming over UART
print("Connected to : ",sSerialPort.name)
while(True):
# Wait until there is data waiting in the serial buffer
if(sSerialPort.in_waiting > 0):
# Read data out of the buffer until a carraige return / new line is found
sSerialString = sSerialPort.readline()
# Print the contents of the serial data
print(sSerialString)
Output:
b'\x05'
b'\x04'
The expected output is different and I am getting the above one.
Can someone please help to understand what's going wrong?
how to deal with port data in python.
I want to send data from one pi to another with UART communication. The first Raspberry model is Raspberry Pi 4, and the second one Raspberry Pi 3. To do this communication Im connecting both Raspberry pins in this way:
Pi 4 -> Pi 3
Tx -> Rx
Rx -> Tx
Ground -> Ground
I have already activated both Pis serial connection on the raspberry configuration following the steps of this link: https://iot4beginners.com/raspberry-pi-configuration-settings/. In order to write and send the data I have created the next python program:
import time
import serial
ser = serial.Serial(
port='/dev/ttyS0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.SEVENBITS)
counter=0
while True:
ser.write(str.encode(str(counter)))
time.sleep(1)
counter += 1
To read and print the data received I have created the next program:
import time
import serial
ser = serial.Serial(
port='/dev/ttySO', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.SEVENBITS
)
counter=0
while 1:
x = ser.readline()
print(x)
Finally when I run the reading program I get the next error:
Traceback (most recent call last):
File "serial_read.py", line 14, in <module>
x = ser.readline()
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 501, in read
'device reports readiness to read but returned no data '
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
I'm new to Raspberry communication and I will be thankful for any suggestion.
Python 2.7 is officially dead, so I would recommend using Python3 - especially for new projects such as yours.
So, rather than run your script with:
python3 YourScript.py
you could put a proper shebang at the start so it automatically uses the correct Python version you intended:
#!/usr/bin/env python3
import ...
Then make the script executable with:
chmod +x YourScript.py
Now you can run it with:
./YourScript.py
and be happy it will use Python3, and also even if someone else uses it.
The actual issue, I think, is that the readline() on the receiving end is looking for a newline that you didn't send. So I would try adding one:
ser.write(str.encode(str(counter) + '\n'))
Personally, I find f-strings to be much easier than the older % and .format() stuff, so maybe try:
ser.write(str.encode(f'{counter}\n'))
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.
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)
I am trying to write a very basic script which will allow me to have full control over a device via serial. I can send data (and I know the device receives it, leaving screen open on the device allows me to see the input appearing).
But I cannot receive data, with screen open, and inputting data via screen I get the error:
Traceback (most recent call last): File "serialRec.py", line 4, in
for line in ser: File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 456, in
read
raise SerialException('device reports readiness to read but returned no data (device disconnected?)')
serial.serialutil.SerialException: device reports readiness to read
but returned no data (device disconnected?)
There is no error if I open the port waiting for a message without screen.
My application as I said sends data no problem... What can I do? How can I get this reading? I am running this script on a Ubuntu 12.04 installation... Screen works fine on the device the Ubuntu laptop is attatched to
The sys arguments are: argv[1] = device (/dev/ttyUSB0) and argv[2] = braud rate (e.g. 9600).
import serial
import sys
import time
def enterdata():
ser = serial.Serial(sys.argv[1], sys.argv[2])
scom = raw_input("type away:" )
incli = str(scom)
time.sleep(.2)
if (incli == "exit the app"):
print ("Exiting the data send, nothing was sent from the exit command")
else:
while True:
print ser.readline()
enterdata()
print ("Welcome to the serial CLI")
enterdata()
UPDATE:
I now have it working, but limited and ugly it prints the return on multiple lines from sending one command. Though for this I am going to try a few things out. I will post and share some nice working code once i get it to a good place.
import serial
import sys
import time
def enterdata():
ser = serial.Serial(sys.argv[1], sys.argv[2])
scom = raw_input()
incli = str(scom)
if (incli == "exit the app"):
print ("Exiting the data send, nothing was sent from the exit command")
else:
ser.write(incli+"\r\n")
time.sleep(0.5)
while True:
data = ser.read(ser.inWaiting())
if (len(data) > 0):
for i in range(len(data)):
sys.stdout.write(data[i])
break
ser.close()
enterdata()
print ("Welcome to the serial CLI, hit enter to activate:")
enterdata()
This is the changes I have made, it works. Though it seems to always print double or maybe send an extra character
You might want to try with a listener first, but you have to make sure that your device is sending data to your serial port at the correct baudrate.
import serial, sys
port = your_port_name
baudrate = 9600
ser = serial.Serial(port,baudrate,timeout=0.001)
while True:
data = ser.read(1)
data+= ser.read(ser.inWaiting())
sys.stdout.write(data)
sys.stdout.flush()
I'm trying to send and receive messages between two Linux running laptops via serial communication using Python. The receiver system must see the message "waiting for the message" until it receives the message from the sender. I was searching for sample code to test this. The sample code I have for the sender is as follows:
import serial
com = serial.Serial('/dev/ttyUSB0',baudrate=115200)
com.write('2')
com.close()
But I cannot figure out what to put for the receiver code, where it will display a message on the receivers display as "waiting" and once the message is received it should display "received".
Does anyone have a sample code to work this out?
Reading a serial device is as easy as reading a file:
import serial
com = serial.Serial('/dev/ttyUSB0',baudrate=115200)
print "Waiting for message"
char = com.read(1)
print char
com.close()