简体   繁体   中英

Que while loop loops

Im pretty new to programming and im making a program where I want to use a rotary encoder to change the temperature in a car OTA with the cars API. Im coding in Python on a Raspberry Pi. The code looks something like this:

Que=0
While True:
      If encoder turns right:
         Que =+ 1
      if encoder turn left:
         Que =- 1
       
      while Que != 0
       if Que>0:
          Send request to car to turn up the temperature by 0.5 degrees
          Que =- 1
       if Que<0
          Send request to car to turn down the temperature by 0.5 degrees 
          Que =+ 1

This works great when I turn it one click and then wait. However, the API uses about 0,5 second to complete the request to the car and exit the while loop. Therefore, if you turn the encoder 4 clicks to the right it only sends one request.

How do I solve this?

This is hard to answer without the specific implementation, maybe some unoptimized code, function, or similar is being called?

A trivial answer seems to be to use a faster language like C, or C++ if speed is the issue.

If you want to improve python code itself, I would suggest looking into multithreading. One for adding operations, and one for executing the current total of operations (aka probably a sum over the operations) in one change by +/- x temp . Check multithreading with observer pattern as a starting point.

One possible speed-up is to combine operations. Why issue it multiple operations of increase/decrease value, can you do this in one?

Que=0
while True:
      if encoder turns right:
         Que =+ 1
      if encoder turn left:
         Que =- 1
       
      if Que != 0
       if Que>0:
          Send request to car to turn up the temperature by 0.5 degrees * Que
       elif Que<0
          Send request to car to turn down the temperature by 0.5 degrees * Que 
       Que = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM