Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pySerial write() won't take my string

Using Python 3.3 and pySerial for serial communications.

I'm trying to write a command to my COM PORT but the write method won't take my string. (Most of the code is from here Full examples of using pySerial package

What's going on?

import time import serial   ser = serial.Serial(     port='\\\\.\\COM4',     baudrate=115200,     parity=serial.PARITY_ODD,     stopbits=serial.STOPBITS_ONE,     bytesize=serial.EIGHTBITS ) if ser.isOpen():     ser.close() ser.open() ser.isOpen()  ser.write("%01#RDD0010000107**\r") out = '' # let's wait one second before reading output (let's give device time to answer) time.sleep(1) while ser.inWaiting() > 0:     out += ser.read(40)  if out != '':     print(">>" + out)   ser.close() 

Error is at ser.write("%01#RDD0010000107**\r") where it gets Traceback is like this data = to_bytes(data) b.append(item) TypeError: an integer is required.

like image 666
Garvin Avatar asked Mar 08 '14 21:03

Garvin


People also ask

Does PySerial work on Linux?

pySerial 1.21 is compatible with Python 2.0 on Windows, Linux and several un*x like systems, MacOSX and Jython. On Windows, releases older than 2.5 will depend on pywin32 (previously known as win32all).

How do I know if PySerial is installed?

To check that it is installed, start Pyzo and at the command prompt type in: import serial If it just gives you another >>> prompt, all is good. Checking that it is really working.

Is PySerial full duplex?

Yes serial port hardware is full duplex. Yes, you can use threads to do Rx and Tx at the same time. Alternatively, you can use a single thread loop that does reads with a short timeout and alternates between reading and writing.


2 Answers

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

like image 117
Garvin Avatar answered Sep 28 '22 08:09

Garvin


You have found the root cause. Alternately do like this:

ser.write(bytes(b'your_commands')) 
like image 25
Murphy Meng Avatar answered Sep 28 '22 08:09

Murphy Meng