import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyS0',
#port='/dev/ttyACM0',
baudrate=115200,
parity=serial.PARITY_ODD,
#stopbits=serial.STOPBITS_TWO,
#bytesize=serial.SEVENBITS
)
ser.isOpen() # returns true
time.sleep(1);
ser.write("some_command \n")
ser.close()
I have a embedded board. It has a serial port which is connected to my computer. I am running above script to access this serial port and run some board specific commands.
My problem
I open my serial port (using minicom in linux) separately and then run above script, It works. If I don't open serial port separately, Script doesn't work.
try
ser.write("some_command \n".encode())
alternatively try
ser.write(bytes(b"some_command \n"))
Related
I need help with a python code to connect with a Router or a Switch via serial port. I use pycharm from a Windows terminal.
This is what I tried:
import keyboard
ser = serial.Serial(port="COM1", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
while True:
ser.write('You got connected\r\n'.encode('Ascii'))
receive = ser.readline()
print(receive.decode('Ascii'))
if keyboard.is_pressed('q'):
print('User need to quit the app.')
break
ser.close()
Tried and I got errors.
What error do you get ?
This would be very helpful if you could copy/paste your errors in here.
I am Using a Python to access a serial port from ubuntu 20.4. I send and read data from the Connected serial port.
The code looks like :
import time
import serial
ser=serial.Serial("/dev/ttyACM0",115200)
ser.write(b'\xFA\x0B\x1B\x00\x00\x00\x00\x00\x00\xFB')
while True:
try:
#ser.write(command)
s2=ser.read(10).hex()
print(s2)
except KeyboardInterrupt:
ser.flushInput()
ser.flushOutput()
ser.close()
break
The issue is, whenever I try resetting the hardware device the "COM Port" Jumps to a new "port". So I need to manually change the port in the code frequently.
Is there a way to set a default "COM PORT" in Ubuntu for a serial port device (or) is there a way to automatically detect the "COM PORT" by my program!?
The thing I tried is:
import serial.tools.list_ports
import serial
print('Searching for ports...')
ports=serial.tools.list_ports.comports(include_links=False)
for port in ports:
if port.device=="/dev/ttyACM0" or port.device=="/dev/ttyACM1" or port.device=="/dev/ttyACM2":
ser=serial.Serial(port.device)
break
if ser.isOpen():
ser.close()
ser=serial.Serial(port.device,115200)
ser.flushInput()
ser.flushOutput()
print('Connected to :'+ser.name)
But this code doesn't provide the required output. The code sometimes doesn't select the correct "COM PORT".
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 developed a plugin for Domoticz on a RPi3B+. This plugin is in Python.
I want to send commands to a Arduino board using a USB serial port.
The plugin opens the serial port, sends a command and closes the serial port. It works well except after a reboot.
After a reboot, the port is open, and the command seems to be sent to the Arduino, but it doesn't understand it, just as if the baud rate were wrong. Arduino's Rx LED is blinking.
If I open the serial in parallel using minicom and exit minicom without resetting the parameters, then the plugin starts working properly.
Here's my code:
serialCmd = "gpio sh" + str( shutterId ) + "_" + order +" on for " + str( PULSE_DURATION_MS ) + "\r"
Domoticz.Debug( "Serial command : " + serialCmd )
# open serial port
try:
Domoticz.Debug( "Opening serial port : " + Parameters["SerialPort"] )
serialPort = serial.Serial( port = Parameters["SerialPort"],
baudrate = 115200,
bytesize = serial.EIGHTBITS,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
timeout = 1,
xonxoff = False,
rtscts = False,
dsrdtr = False )
except:
serialPort = None
if serialPort:
serialPort.write( serialCmd.encode( 'utf-8' ) )
serialPort.close()
serialPort = None
The serial port is /dev/ttyUSB0.
If I try to use exclusive = True in serial.Serial(...), it fails to open the port, as if the port were already open.
Another strange thing: when the Arduino board reboots, it sends some information to the serial port.
I can't read it with the plugin in Python with PySerial, but I can read it with minicom.
If I close minicom with resetting the parameters, each time I open minicom this information is read by minicom (without resetting the Arduino board) as if the input buffer has never been read, and the Python plugin still doesn't work.
How do I solve the problem?
This issue was because of Arduino nano schematic where DTR signal is connected to the reset signal which makes the Arduino to reset each time the serial port is open. This post made me search the right thing on the internet. That's why opening minicom and closing without resetting the port makes it work...
When the serial is not used anymore by a process the DTR line is reset so next time a process open the serial port the DTR is driven which makes the Arduino reboot.
A way to fix it is to modify the board or two disable the DTR handling. This can be done by dsiable the HUPCL bit of the terminal lib.
Some people manage to fix it with pySerial but it does not work for me so I had to do as below...found here and here.
import serial
import termios
port = '/dev/ttysUSB0'
f = open(port)
attrs = termios.tcgetattr(f)
attrs[2] = attrs[2] & ~termios.HUPCL
termios.tcsetattr(f, termios.TCSAFLUSH, attrs)
f.close()
se = serial.Serial()
se.baudrate = 115200
se.port = port
se.open()
I have Python 3.6.1 and PySerial Installed. I am trying the
I am able to get the list of comports connected. I now want to be able to send data to the COM port and receive responses back. How can I do that? I am not sure of the command to try next.
Code:
import serial.tools.list_ports as port_list
ports = list(port_list.comports())
for p in ports:
print (p)
Output:
COM7 - Prolific USB-to-Serial Comm Port (COM7)
COM1 - Communications Port (COM1)
I see from the PySerial Documentation that the way to open a COM Port is as below:
import serial
>>> ser = serial.Serial('/dev/ttyUSB0') # open serial port
>>> print(ser.name) # check which port was really used
>>> ser.write(b'hello') # write a string
>>> ser.close() # close port
I am running on Windows and I get an error for the following line:
ser = serial.Serial('/dev/ttyUSB0')
This is because '/dev/ttyUSB0' makes no sense in Windows. What can I do in Windows?
This could be what you want. I'll have a look at the docs on writing.
In windows use COM1 and COM2 etc without /dev/tty/ as that is for unix based systems. To read just use s.read() which waits for data, to write use s.write().
import serial
s = serial.Serial('COM7')
res = s.read()
print(res)
you may need to decode in to get integer values if thats whats being sent.
On Windows, you need to install pyserial by running
pip install pyserial
then your code would be
import serial
import time
serialPort = serial.Serial(
port="COM4", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE
)
serialString = "" # Used to hold data coming over UART
while 1:
# Wait until there is data waiting in the serial buffer
if serialPort.in_waiting > 0:
# Read data out of the buffer until a carraige return / new line is found
serialString = serialPort.readline()
# Print the contents of the serial data
try:
print(serialString.decode("Ascii"))
except:
pass
to write data to the port use the following method
serialPort.write(b"Hi How are you \r\n")
note:b"" indicate that you are sending bytes