<p>如果轮子没有转动,那么<code>calculate_elapse</code>就不会被调用。这意味着<code>elapse</code>将永远不会被设置为“大”(>;=3)值,因此您的<code>mps = 0</code>短路将永远不会被触发。你知道吗</p>
<p>你对globals的使用让我很不安,所以我有机会重写这个。。。这是未经测试,但希望你会看到为什么这是一个更好的:</p>
<pre><code>import math
import time
import RPi.GPIO as GPIO # This is my best guess :-)
SENSOR_ID = 5
WHEEL_RADIUS_CM = 3.4
class UnknownRotationError(Exception):
pass
class WheelTimer:
MAX_ACCEPTABLE_DURATION = 3.0
def __init__(self, wheel_radius_cm):
self.wheel_radius_cm = wheel_radius_cm
self._wheel_circ_m = ((2 * math.pi) * self.wheel_radius_cm) / 100
self.num_full_rotations = 0
self.total_distance_m = 0.0
self.last_rotation_duration_s = None
self._rotation_started_time = time.time()
def complete_rotation(self):
"""Record a completed revolution."""
self.num_full_rotations += 1
self.total_distance_m = self._wheel_circ_m * self.num_full_rotations
now = time.time()
self.last_rotation_duration_s = self.rotation_started_time - now
self._rotation_started_time = now
@property
def current_rotation_duration(self):
return self.rotation_started_time - time.time()
def _validate_rotation(self):
if not self.last_rotation_duration_s:
raise UnknownRotationError()
if self.last_rotation_duration_s > self.MAX_ACCEPTABLE_DURATION:
raise UnknownRotationError()
if self.current_rotation_duration > self.MAX_ACCEPTABLE_DURATION:
raise UnknownRotationError()
@property
def current_speed_ms(self):
self._validate_rotation()
return self._wheel_circ_m / self.last_rotation_duration_s
@property
def current_rpm(self):
self._validate_rotation()
return (1.0 / self.last_rotation_duration_s) * 60.0
def init_GPIO(): # initialize GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(SENSOR_ID, GPIO.IN, GPIO.PUD_UP)
def init_interrupt(callback_func):
GPIO.add_event_detect(SENSOR_ID, GPIO.FALLING, callback=callback_func, bouncetime=20)
if __name__ == '__main__':
init_GPIO()
wheel_timer = WheelTimer(WHEEL_RADIUS_CM)
init_interrupt(callback_func=wheel_timer.complete_rotation)
while True:
time.sleep(0.1)
try:
print('{0:.0f}rpm {1:.2f}m/s {2:.2f}m Counter:{3}'.format(
wheel_timer.current_rpm,
wheel_timer.current_speed_ms,
wheel_timer.total_distance_m,
wheel_timer.num_full_rotations,
))
except UnknownRotationError:
print("Wheel moving too slowly to measure!")
</code></pre>