Search code examples
pythonpython-3.xtimeraspberry-pipwm

don't add to value if condition hasn't been met for a time limit


I'm controlling the forwards speed of a robot based on pwm (speed is determined the same way servos are controlled 1.5ms being neutral, 2ms, and 1ms being forwards and backwards respectively)

I want add 100µs to pwm if not key.get_pressed()[K_w] has lasted more than 0.5s (add 100µs to pwm once w is pressed if w was unpressed for less than 0.5 seconds)

details: varible pwm is in units of µs, key.get_pressed()[K_w] returns the state of all keys (1 being pressed & 0 being not pressed)

bit of pseudocode:

while True:
  if key.get_pressed()[K_w]:
    pwm = pwm + 100 if w's time since last pressed has lasted < 0.5 seconds
    throttle(pwm)

I'm utterly sick of dealing with this I've been stuck on it for a week and I hate it.


Solution

  • I think this should work (haven't tested)

    import time
    last_press = 0
    if key.get_pressed()[K_w]:
      span = time.time() - last_press
      last_press = time.time()
      if span < 0.5:
        pwm += 100
        throttle(pwm)