Difference between revisions of "UBISS2024exam"

From Sketching with Hardware at LMU Wiki
Jump to navigation Jump to search
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
<syntaxhighlight lang="python" line='line'>
 
<syntaxhighlight lang="python" line='line'>
from sklearn.model_selection import train_test_split
+
 
X = df[["X", "Y", "Z"]].diff().iloc[1:].values
+
from machine import Pin, ADC
y = df.Label.iloc[1:].values
+
from time import sleep
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
+
 
 +
# 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)
 +
 
 +
 
 
</syntaxhighlight>
 
</syntaxhighlight>

Latest revision as of 12:54, 13 June 2024

 1 from machine import Pin, ADC
 2 from time import sleep
 3 
 4 # Initialize the light sensor (LDR) and LED
 5 ldr = ADC(Pin(12))
 6 led = Pin(20, Pin.OUT)
 7 
 8 def get_duty_cycle(light_value):
 9     # Map the light value to the duty cycle
10     # Completely dark (350) -> 90% on, 10% off
11     # Completely bright (790) -> 10% on, 90% off
12     min_light = 350
13     max_light = 790
14     min_duty = 90
15     max_duty = 10
16     
17     duty_cycle = min_duty + (max_duty - min_duty) * ((light_value - min_light) / (max_light - min_light))
18     return duty_cycle
19 
20 while True:
21     # Read the light value
22     light_value = ldr.read_u16()  # Read the analog value (16-bit)
23     light_value = (light_value / 65535) * (790 - 350) + 350  # Scale to 350-790 range
24 
25     # Calculate the duty cycle
26     duty_cycle = get_duty_cycle(light_value)
27     
28     # Calculate on and off times
29     on_time = duty_cycle / 100.0
30     off_time = 1.0 - on_time
31     
32     # Control the LED
33     led.on()
34     sleep(on_time)
35     led.off()
36     sleep(off_time)