Full Examples of Using Pyserial Package

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

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.

pySerial write() won't take my string

It turns out that the string needed to be turned into a bytearray and to do this I editted the code to

ser.write("%01#RDD0010000107**\r".encode())

This solved the problem

Python Serial Read

First of all the ser.readline() command is the infinite loop. It waits until there is a \n Charakter in the input buffer. You can avoid the loop by specifying a timeout in the initialization of the serial.Serial Object like this (timeout in seconds)

ser = serial.Serial('/dev/ttyUSB2',115200,timeout=2)

Now to the part that there is nothing that you receive from the modem. This might have different reasons and cannot be properly answered by the informations you have provided.
First there might be something wrong with your usb to serial adapter. Then you might have incorrectly wired something or your modem might have a problem electrically or with its software.

pySerial - Only reading one byte

Your read statement is explicitly requesting 1 byte:

ser.read(1)

If you know how many bytes to read, you can specify here. If you are unsure, then you can specify a larger number. For example, doing

ser.read(10)

will read up to 10 bytes. If only 8 are available, then it will only return 8 bytes (following the timeout, see below).

It is also worth setting a timeout to prevent the program from hanging. Just add a timeout parameter to your Serial constructor. The following will give you a 2 second timeout:

ser = serial.Serial(
port='COM1',
baudrate=115200,
parity=serial.PARITY_EVEN,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=2
)

The documentation states:

read(size=1) Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.

So if you do not know how many bytes to expect, then set a small timeout (if possible) so your code does not hang.

If your code does not return the full number of bytes expected, then it is likely the device you are connected to is not sending all the bytes you are expecting. Since you have verified it should be working separately, have you verified the data you are sending is correct? Perhaps encode to bytes first using struct.pack(). As an example, to send a byte with a decimal value of 33 (hex 0x21)

import struct
bytes_to_send = struct.pack('B', 33)

I have also never found it necessary to append the end of line chars \r\n to a message before sending



Related Topics



Leave a reply



Submit