close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to read and write from a COM Port using PySerial in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    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().

  2. read and write from a COM Port using PySerial

    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().

Method 1

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.

Method 2

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read