UBISS2024exam: Difference between revisions

From Sketching with Hardware at LMU Wiki
Jump to navigation Jump to search
Created page with "=== Solution Task 1.2 Control external RGB === <syntaxhighlight lang="python" line='line'> # Blinky example import time from machine import Pin # This is the only LED pin av..."
 
No edit summary
 
(10 intermediate revisions by the same user not shown)
Line 1: Line 1:
=== Solution Task 1.2 Control external RGB ===
<syntaxhighlight lang="python" line='line'>
<syntaxhighlight lang="python" line='line'>
# Blinky example


import time
from machine import Pin, ADC
from machine import Pin
from time import sleep
 
# Initialize the light sensor (LDR) and LED
ldr = ADC(Pin(12))
led = Pin(20, Pin.OUT)
 
def get_duty_cycle(light_value):
    # Map the light value to the duty cycle
    # Completely dark (350) -> 90% on, 10% off
    # Completely bright (790) -> 10% on, 90% off
    min_light = 350
    max_light = 790
    min_duty = 90
    max_duty = 10
   
    duty_cycle = min_duty + (max_duty - min_duty) * ((light_value - min_light) / (max_light - min_light))
    return duty_cycle
 
while True:
    # Read the light value
    light_value = ldr.read_u16()  # Read the analog value (16-bit)
    light_value = (light_value / 65535) * (790 - 350) + 350  # Scale to 350-790 range
 
    # Calculate the duty cycle
    duty_cycle = get_duty_cycle(light_value)
   
    # Calculate on and off times
    on_time = duty_cycle / 100.0
    off_time = 1.0 - on_time
   
    # Control the LED
    led.on()
    sleep(on_time)
    led.off()
    sleep(off_time)


# This is the only LED pin available on the Nano RP2040,
# other than the RGB LED connected to Nano WiFi module.
led = Pin(6, Pin.OUT)


while (True):
  led.on()
  time.sleep_ms(250)
  led.off()
  time.sleep_ms(200)
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 13:54, 13 June 2024

from machine import Pin, ADC
from time import sleep

# Initialize the light sensor (LDR) and LED
ldr = ADC(Pin(12))
led = Pin(20, Pin.OUT)

def get_duty_cycle(light_value):
    # Map the light value to the duty cycle
    # Completely dark (350) -> 90% on, 10% off
    # Completely bright (790) -> 10% on, 90% off
    min_light = 350
    max_light = 790
    min_duty = 90
    max_duty = 10
    
    duty_cycle = min_duty + (max_duty - min_duty) * ((light_value - min_light) / (max_light - min_light))
    return duty_cycle

while True:
    # Read the light value
    light_value = ldr.read_u16()  # Read the analog value (16-bit)
    light_value = (light_value / 65535) * (790 - 350) + 350  # Scale to 350-790 range

    # Calculate the duty cycle
    duty_cycle = get_duty_cycle(light_value)
    
    # Calculate on and off times
    on_time = duty_cycle / 100.0
    off_time = 1.0 - on_time
    
    # Control the LED
    led.on()
    sleep(on_time)
    led.off()
    sleep(off_time)