简体   繁体   中英

How to read input from port and print to terminal

here's the situation:

I have two stamps, one connected to port: /dev/ttyUSB1, and one external one, unconnected. The external one has a (Contiki based) program on it to send (every 2 seconds) a single letter across to the stamp that is plugged into the computer. stamp plugged into the computer has a program, also Contiki based, which reads this information via a radio signal.

Now, I have written a python program, making use of pyserial, which aims to read the information coming into the port and display it in terminal. I know the message is arriving correctly as I can print the message from the stamp connected via USB to terminal fine. But I am having trouble reading the information from the python code.

import serial, time, threading

ser = serial.Serial()
ser.port = "/dev/ttyUSB1"
ser.baudrate = 9600
ser.bytesize = serial.SEVENBITS 
ser.parity = serial.PARITY_EVEN 
ser.timeout = 0.1     
ser.rtscts = 1

try: 
    ser.open()
except Exception, e:
    print "error open serial port: " + str(e)
    exit()
if ser.isOpen():
try:
    numOfLines = 0
    while True:
        print ser.read()
        numOfLines = numOfLines + 1
        time.sleep(2)
        if (numOfLines >= 50):
            break
    ser.close()
except Exception, e1:
    print "error communicating...: " + str(e1)
else:
    print "cannot open serial port "

When run, instead of printing the expected letter sent from the stamp every couple of seconds, it will print a few consistent, yet random letters. For example:

w
z
z
w
g
z
g
z
z
z
w
z
w

There is no output from the program when I remove the USB connected to the stamp. So it must be reading something from the port... Any help would be much appreciated.

It sounds like it could be a problem with the baudrate. you didn't post the code that does this:

ser = serial.Serial('/dev/ttyUSB1', timeout=1, baudrate=9600, rtscts=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM