Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read and write from a COM Port using PySerial?

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?

like image 331
Neil Dey Avatar asked May 18 '17 20:05

Neil Dey


1 Answers

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

like image 140
Ali Hussein Avatar answered Nov 03 '22 00:11

Ali Hussein