为什么python不在ser.read()循环中打印?

2024-04-26 18:47:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法理解while循环中的print函数为什么不起作用。程序会一直等到Serial.read()的值改变

我也尝试过在ser.read()之后打印。那没什么区别

 ## import the serial library
import serial

## Boolean variable that will represent 
## whether or not the arduino is connected
connected = False

## open the serial port that your arduino 
## is connected to.
ser = serial.Serial("/dev/ttyACM0", 9600)

## loop until the arduino tells us it is ready
while not connected:
    serin = ser.read()
    connected = True
    print('Arduino is now ready')

## Tell the arduino to blink!
ser.write('1'.encode())
print('Just told the Arduino to blink')

## Wait until the arduino tells us it 
## is finished blinking
while ser.read() == '1':
    print('Still getting a 1 on serial')  #This part is not printing
    ser.read()                            #This does seem to work

## close the port and end the program
print('Closing the port')                 #This part works as expected
ser.close()                               #The program quits successfully

澄清: 这段代码有很多错误,但是while ser.read()=='1'循环实际上是有效的。因为我看到它在打印“关闭端口”之前等待。但它从来没有打印“序列号仍然是1”。这很让人困惑


Tags: thetoimportreadisportserialnot