<p>首先需要解决一些较小的问题:</p>
<ol>
<li><code>input = ser.read()</code><code>input</code>实际上是一个<a href="https://docs.python.org/3/library/functions.html" rel="nofollow noreferrer">builtin</a>,不应该用作变量名</li>
<li><code>int(yon)</code>什么也不做。您可以将其转换为<code>int</code>,但结果会丢失,因为您没有将结果重新分配给名称</li>
<li><code>if (z > 0.20)</code>和所有其他的{<cd6>}检查-括号在这里实际上什么都不做;你可以放下它们</李>
</ol>
<p>需要解决的一个更大的问题是:这个循环完全没有理由地在CPU核心上运行。每秒数千次,持续不断。您应该引入<code>time.sleep</code>来减少负载</p>
<p>鉴于此,您可以通过混合使用布尔标志和加速度计上次给出0值的记录来实现所需的输出</p>
<pre><code>import time
import datetime as dt
last_zeros = None
countdown_started = False
while True:
ser.flushInput()
ser.flushOutput()
x, y, z = sense.get_accelerometer_raw().values()
x = round(x, 2)
y = round(y, 2)
z = round(z, 2)
print("x=%s, y=%s, z=%s" % (x, y, z))
if x == 0 and y == 0 and z == 0:
if countdown_started:
duration = (dt.datetime.utcnow() - last_zeros_time).total_seconds()
if duration > 15:
# Do something to turn the light off here
continue
else:
countdown_started = True
last_zeros_time = dt.datetime.utcnow()
else:
countdown_started = False
sensor_input = ser.read()
yon = sensor_input.decode("utf-8")
if (z > 0.20):
fren()
else:
if (yon == "1"):
sag_ok()
elif (yon =="2"):
sol_ok()
else:
strobe()
time.sleep(0.5)
</code></pre>