Python while 循环在定义的时间后没有终止

Python while loop not terminating after defined amount of time

对于这个项目,我一直在制作一个振动测量装置,该装置绘制由电机控制的高速振动。这是下面的代码:

# Import the modules
from __future__ import division
import spidev, datetime, time
from sys import exit
import RPi.GPIO as GPIO

# Setup SPI
spi = spidev.SpiDev()
spi.open(0, 0)
spi.mode = 3

# Constants
accres, accrate = 1, 15

# Set GPIO chip select pins
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
cs1, cs2, motor = 23, 24, 18
GPIO.setup(cs1, GPIO.OUT)
GPIO.setup(cs2, GPIO.OUT)
GPIO.setup(motor, GPIO.OUT)

# Note: the duty cycle goes from 0.0 to 100.0, with 100.0 being no motor movement,
# and 0.0 being the maximum motor speed.
motor_output = GPIO.PWM(motor, 60)

# Initialize the ADXL345
def initadxl345():
    # Set data rate (accrate=15 -> 3200 Hz, 14=1600 Hz, 13=800 Hz, 12=400 Hz, 11=200 Hz, 10=100 Hz etc.)
    spi.xfer2([44, accrate])

    # Enable full range (10 bits resolution) and +/- 16g 4 LSB
    spi.xfer2([49, accres])

# Read the first ADXL x-y-z axes
def readadxl345_1():
    # Chip select pin ensures that the first sensor is being read by grounding its pin
    GPIO.output(cs1, 0)
    GPIO.output(cs2 ,1)

    rx = spi.xfer2([242, 0, 0, 0, 0, 0, 0])
    out = [rx[1] | (rx[2] << 8), rx[3] | (rx[4] << 8), rx[5] | (rx[6] << 8)]
    # Format x-axis
    if (out[0] & (1 << 16 - 1 )):
        out[0] = out[0] - (1 << 16)
    # Format y-axis
    if (out[1] & (1 << 16 - 1 )):
        out[1] = out[1] - (1<<16)
    # Format z-axis
    if (out[2] & (1 << 16 - 1 )):
        out[2] = out[2] - (1 << 16)
    # Return human readable values
    return out

# Read the second ADXL x-y-z axes
def readadxl345_2():
    # Chip select pin ensures that the first sensor is being read by grounding its pin
    GPIO.output(cs1, 1)
    GPIO.output(cs2 ,0)

    rx = spi.xfer2([242, 0, 0, 0, 0, 0, 0])
    out = [rx[1] | (rx[2] << 8), rx[3] | (rx[4] << 8), rx[5] | (rx[6] << 8)]
    # Format x-axis
    if (out[0] & (1 << 16 - 1 )):
        out[0] = out[0] - (1 << 16)
    # Format y-axis
    if (out[1] & (1 << 16 - 1 )):
        out[1] = out[1] - (1<<16)
    # Format z-axis
    if (out[2] & (1 << 16 - 1 )):
        out[2] = out[2] - (1 << 16)
    # Return human readable values
    return out

print("Vibration Reader Initializing...")
time.sleep(1)
print(GPIO.RPI_INFO)
time.sleep(1)

response = input("Proceed measurements? [Y, n] ")

if response == "Y" or "y":
    filename = input("Filename: ")
    pwm_speed = float(input("Motor PWM value: "))
    # Initialize the ADXL345 accelerometer
    print("Initializing ADXL345s...")
    initadxl345()
    motor_output.start(pwm_speed)
    print("Motor is up and running at {}".format(pwm_speed))
    time.sleep(1)

    timeout = 0.0003125 / 2 # timeout=1/samplerate=>not sufficient measurements. Half the time is sufficient (don't know why!)

    timetosend = 1

    while True:
       with open('/proc/uptime', 'r') as f: # get uptime
           uptime_start = float(f.readline().split()[0])
       uptime_last = uptime_start
       active_file_first = filename + '.csv'
       file = open('/var/log/sensor/' + active_file_first, 'w')
       while uptime_last < uptime_start + timetosend:

           time1 = str(datetime.datetime.now().strftime('%S.%f'))
           sensor1 = readadxl345_1()
           sensor2 = readadxl345_2()
           file.write(str(sensor1[0]) + ',' + str(sensor1[1]) + ',' + str(sensor1[2]) + ',' + str(sensor2[0]) + ',' + str(sensor2[1]) + ',' + str(sensor2[2]) + ',' + time1 + '\n')

           # Print data every "timeout" second
           elapsed = time.process_time()
           current = 0
           while(current < timeout):
               current = time.process_time() - elapsed

    motor_output.stop
    print("Motor shutting off and cleaning up GPIO.")
    GPIO.cleanup()

elif response == "N" or "n":
    print("Quitting...")
    time.sleep(1)
    quit()

由此惹上麻烦。问题是,一旦我选择继续,打印语句 Motor is up and running at 100.0 就会显示,直到我按下键盘上的随机键

之前什么也没有发生
Traceback (most recent call last):
  File "accelerometer.py", line 116, in <module>
    current = time.process_time() - elapsed
KeyboardInterrupt

好像打印语句后面的代码根本不存在,或者解释器完全忽略了它。有没有人对这些问题有一个连贯的解释?

让我们退后一步,想想这段代码在做什么:

while True:

   ### Block 1 ###
   with open('/proc/uptime', 'r') as f: # get uptime
       uptime_start = float(f.readline().split()[0])
   uptime_last = uptime_start
   active_file_first = filename + '.csv'
   file = open('/var/log/sensor/' + active_file_first, 'w')

   ### Block 2 ###
   while uptime_last < uptime_start + timetosend:

       time1 = str(datetime.datetime.now().strftime('%S.%f'))
       sensor1 = readadxl345_1()
       sensor2 = readadxl345_2()
       file.write(str(sensor1[0]) + ',' + str(sensor1[1]) + ',' + str(sensor1[2]) + ',' + str(sensor2[0]) + ',' + str(sensor2[1]) + ',' + str(sensor2[2]) + ',' + time1 + '\n')
       # Print data every "timeout" second
       elapsed = time.process_time()
       current = 0

       ### Block 3 ###
       while(current < timeout):

           current = time.process_time() - elapsed

块 1 检查正常运行时间文件,读取时间,然后打开 file。然而,如果这个 uptime_start 变量永远不会改变,那么我们可以只在顶部 while 循环之外(而不是)设置它一次。块 2 然后检查 uptime_last < uptime_start + x,但在前几行中,您定义了 uptime_last = uptime_start。这意味着只要 timetosend 不为负,除非满足内部中断条件,否则此循环将无限执行。块 2 将传感器数据写入文件。块 3 在满足条件之前进行时间计算,但实际上并未对这些信息执行任何操作。

我猜测什么可能是一个好的答案是这样的:

### Block 1 ###
with open('/proc/uptime', 'r') as f: # get uptime
    uptime_start = float(f.readline().split()[0])
file = open('/var/log/sensor/' + filename + '.csv', 'w')
time_elapsed = 0
time_start = time.process_time()

### Block 2 ###
while time_elapsed < uptime_start:

   time1 = str(datetime.datetime.now().strftime('%S.%f'))
   sensor1 = readadxl345_1()
   sensor2 = readadxl345_2()
   file.write(str(sensor1[0]) + ',' + str(sensor1[1]) + ',' + str(sensor1[2]) + ',' + str(sensor2[0]) + ',' + str(sensor2[1]) + ',' + str(sensor2[2]) + ',' + time1 + '\n')

   time_elapsed = time.process_time() - time_start