3

I've just started using pyserial as I will eventually need to read/save information coming from a particular port. Using the following code I am merely printing the port used and then trying to write and then read in some text ("hello"). The port is printing fine, but the output of my string is coming out as 5. Any idea why this is?

import serial
import sys
from time import sleep

try:
  ser = serial.Serial('\\.\COM8', 9600,timeout=None, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)

except:
    sys.exit("Error connecting device")

print ser.portstr

x = ser.write("hello")
print x

ser.close()  

Output:

>>> 
\.\COM8
5
>>> 

Also, is there a simple way for me to mimic a stream of text information coming through the port so that I can test reading in/saving the incoming info?

I am using Python 2.7, and 'virtual serial port driver 8.0' [Eltima VSPD] to emulate a port for testing this stuff.

Thanks, Steve

Steve
  • 327
  • 2
  • 3
  • 15

2 Answers2

3

you can do it this way to test it. Firstly create a pair of ports in manage ports

First port: COM199 Second Port: COM188

Click Add Pair

On one console/script do the below steps:

>>> import serial
>>> ser = serial.Serial('COM196', 9600,timeout=None, parity=serial.PARITY_NONE, stopbits=serial.S
BITS_ONE, bytesize=serial.EIGHTBITS)
>>> print ser.portstr
COM196
>>> x = ser.read(5) # It will be waiting till it receives data
>>> print x
hello

On the other console, perform below steps:

>>> import serial
>>> s = serial.Serial('COM188')
>>> s.write("hello")
5L

you can test it this way (or) by creating python programs for each of the ports

be_good_do_good
  • 4,311
  • 3
  • 28
  • 42
  • Thank you, that's very helpful. You've used port196 in the code, but this port was not initially setup (you created pair 199&188). Is it mean to be this way? – Steve Aug 05 '16 at 15:52
0
x = ser.write("hello")
print x

You writing this as sended. It's not recieved info. Probably it writes the lenght of string you have sended. First you need to have a client side script which will response your sended information.

And you have to use something like this on it.

...     x = ser.read()          # read one byte
...     s = ser.read(10)        # read up to ten bytes (timeout)
...     line = ser.readline()   # read a '\n' terminated line
Turquase
  • 83
  • 1
  • 12
  • Thanks. Is there a way to emulate incoming information to test? – Steve Aug 05 '16 at 14:17
  • Okay there's a video shows how to connect with TCP UDP not serial but it's same logic. You need client and server script both should be running. https://www.youtube.com/watch?v=XiVVYfgDolU – Turquase Aug 06 '16 at 16:36