pythonraspberry-pimicropythonraspberry-pi-pico

How to fix python time function rounding numbers


from picozero import RGBLED, Button
import time
import random

rgb = RGBLED(red =18, green =17, blue =16)
button = Button(15)

times = []
index = 0

print("Press the button to start")

while not button.is_pressed:
    time.sleep(0.01)
    
while index != 5:
    rand_num = random.randrange(2, 4)
    index += 1
            
    rgb.color = (255, 0, 0)
    print("Wait for the green light")
    time.sleep(rand_num)
    
    rgb.color = (0, 255, 0)
    start_time = time.time()
            
    while not button.is_pressed:
        time.sleep(0.01)
        
    reaction_time = time.time() - start_time
    times.append(reaction_time)
    rgb.color = (255, 0, 0)
    reaction_time = str(reaction_time)
    print(times)
    print("Reaction Time: " + reaction_time +"seconds")

I want it do display an accurate time. Right now it will display 0 seconds or 1 second or 2 seconds (i am clicking way faster than 2 seconds)


Solution

  • In Micropython time.time() returns an int.

    You can use time.time_ns() to get resolution of nanoseconds, so divide that by 1e9 to get seconds