How to read and write from a COM port using PySerial?
Asked Answered
S

2

24

I have Python 3.6.1 and PySerial installed. I am able to get a list of COM ports connected. I want to send data to the COM port and receive responses:

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)

From PySerial documentation:

>>> 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 get an error from ser = serial.Serial('/dev/ttyUSB0') because '/dev/ttyUSB0' makes no sense in Windows. What can I do in Windows?

Shirker answered 18/5, 2017 at 20:2 Comment(4)
Yes, silly me. Should have researched a bit. I can mark yours as an answer if you answer.Shirker
It's ok to ask for help like that when you've at least tried it as you did :)Barbershop
Can you please keep that link shared to that you had earlier?Shirker
Its in my answerBarbershop
B
19

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.

Barbershop answered 18/5, 2017 at 20:7 Comment(0)
R
15

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:
    # 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

Rueful answered 15/2, 2021 at 19:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.