简体   繁体   中英

Performing a task based in specific time interval in python

I am trying to switch on and off the LED based on a set set_car_id returning some value within a time interval. If the set returns some value, i want the LED to be brighter for 8 seconds. In the code shown below, once the set returns a value, the LED is switched on for 8 seconds. But, if the set returns a value at 5 second (within the 8 sec), then the LED won't be switched on till next 13 sec, it will be on for 3 more seconds and then suddenly switches off. I am showing only smaller part of the code. Any suggestions to solve?

last_bright_time = None            
last_dim_time = None
new_action = -1
def LED_control(set_car_id):
    global last_bright_time
    global last_dim_time
    curr_time = time.time()
    should_remain_bright = False
    should_remain_dim = False
    if (new_action == 0):      #new_action ==0 corresponds to set_car_id returning some value
        if last_bright_time == None:
            last_bright_time = time.time()
        if  (curr_time - last_bright_time) < 8:
        should_remain_bright = True
    if  ((len(set_car_id) > 0) or should_remain_bright = True):
        car_light(1)                # function to bright the LED
        last_dim_time = None
    else:
         car_light(0)               # function to dim the LED
         last_bright_time = None

Try this:

import time
while True:
    brighten()
    time.sleep(8)
    dim()
    time.sleep(8)

If you want something more precise:

import time
def sleep():
    time_start = time.time()
    while time.time() < time_start + 8000:
        pass
while True:
    brighten()
    sleep()
    dim()
    sleep()

In the pieces of code above, you have to define the brighten and dim functions.

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