Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

How do I use python to read a serial value from the serial port of a Cardinal Scale head?

If I use Putty to connect with serial to COM1, 1200 baud I get a black screen but when I type Ctlr-E on the keyboard I get the value that I'm looking to record. If I use serial.tools.miniterm and I type Ctrl-E on the keyboard I get the proper value. When I use the following code it seems as though I connect and there is nothing waiting in the buffer:

import serial

ser = serial.Serial(
    port='com1',
    baudrate=1200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
        timeout=0)
        
print(ser.flush())
print(ser.flushInput())
print(ser.reset_input_buffer())
print(ser.flushOutput())
print(ser.reset_output_buffer())
print(ser.in_waiting)
print(ser.out_waiting)
print(ser.readline())
print(ser.read())
print(ser.read(1))
    
ser.close()

I get back on screen:
None
None
None
None
0
0
b''
b''
b''

I was expecting one of these results to be the value I get in Putty and Miniterm.

What am I doing wrong? After connecting with Python can I send that same key sequence that is sent by Putty when I type Ctrl-E?

question from:https://stackoverflow.com/questions/65661885/how-do-i-use-python-to-read-a-serial-value-from-the-serial-port-of-a-cardinal-sc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I figured out what was needed / missing partially due to a post from here on Oct 2nd, 2013 by Chaosphere2112. I need to both send an encapsulated x05 (thanks barny) but also wait and then read the value in the buffer.

here is the code that worked in the end:

import serial
import time

ser = serial.Serial(
    port='com1',
    baudrate=1200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=0)

ser.write('x05'.encode('utf-8'))
time.sleep(1)
read_val = ser.read(size=64)
if read_val != '':
    print(read_val)
ser.close()

Thank you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...