diff --git a/micropython/examples/galactic_unicorn/light_sensor.py b/micropython/examples/galactic_unicorn/light_sensor.py index 8f1bbf1c..e0416776 100644 --- a/micropython/examples/galactic_unicorn/light_sensor.py +++ b/micropython/examples/galactic_unicorn/light_sensor.py @@ -30,6 +30,9 @@ MAX_LS_VALUE = 295 # 4095 to use the full range MIN_RANGE = 0.1 MAX_RANGE = 1 +# Rate of display change +TRANSITION_RATE = 1.0 / 32.0 + # perform linear interpolation to map a range of values to discrete def map_range( @@ -45,9 +48,14 @@ def map_range( # gets the light sensor value from onboard sensor and interpolates it -# clamps the brightness values -def calculate_brightness(current_lsv): - brightness_val = map_range(current_lsv) +# clamps the brightness value it outside the ranges specified +def calculate_brightness(prev_brightness_val): + current_lsv = gu.light() + current_brightness_val = map_range(current_lsv) + + # uses the previous value to smooth out display changes reducing flickering + brightness_diff = current_brightness_val - prev_brightness_val + brightness_val = prev_brightness_val + (brightness_diff * TRANSITION_RATE) if brightness_val > 1: brightness_val = 1 elif brightness_val < 0.1: @@ -59,7 +67,7 @@ def calculate_brightness(current_lsv): # draws percentage icon def draw_percentage(x, y): graphics.rectangle(x + 1, y + 1, 2, 2) - graphics.line(x, y + 6, x + 6, y) + graphics.line(x + 1, y + 5, x + 6, y) graphics.rectangle(x + 4, y + 4, 2, 2) @@ -69,17 +77,17 @@ def clear(): graphics.clear() -mode = "auto" +mode = "auto" # set auto brightness on last = time.ticks_ms() +brightness_value = MIN_RANGE # set the initial brightness level to the minimum while True: current = time.ticks_ms() - # get light sensor value from the sensor - ls_value = gu.light() - brightness_value = calculate_brightness(ls_value) + # set the display brightness + brightness_value = calculate_brightness(brightness_value) gu.set_brightness(brightness_value) - # calculate brightness percentage - bp = (brightness_value / MAX_RANGE) * 100 + + bp = (brightness_value / MAX_RANGE) * 100 # gets brightness value in percentage relative to the MAX_LS_VALUE set # deactivate auto brightness by pressing A if gu.is_pressed(GalacticUnicorn.SWITCH_A): @@ -110,10 +118,11 @@ while True: # draw the text graphics.set_pen(CURRENT_COLOUR) graphics.text("BRT: ", 0, 1, scale=1) + # measure the rest of the text before drawing to right align it - text_width = graphics.measure_text(f"{bp:.0f}/°", scale=1) + text_width = graphics.measure_text(f"{bp:.0f} ", scale=1) graphics.text(f"{bp:.0f}", WIDTH - text_width, 1, scale=1) - draw_percentage((WIDTH - text_width) + 10, 1) + draw_percentage((WIDTH - 8), 1) # draw a bar for the background graphics.set_pen(GREY)