简体   繁体   中英

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?

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.

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