[Digi-Key Follow Me 3rd Edition] Task 6: Comprehensive Practice (Sub-task 3: Light Reminder)
[Copy link]
Task 6: Comprehensive Practice (Sub-task 3: Light Reminder)
This task requires the user to monitor the ambient light intensity. If the light is too dark, the user is reminded to turn on the light through the screen and buzzer to protect eyesight. After we have completed the previous tasks, it is relatively easy to complete this task.
That is to say, based on Task 5, remove the temperature and humidity part and add the buzzer part.
First, add a buzzer
Then add the illumination value judgment obtained by the photosensitivity below. When it is less than a certain value, the buzzer sounds and the prompt of Turn Light On is displayed on the OLED screen. If the illumination is greater than this value, the buzzer turns off and the OLED does not prompt the content.
The operation effect is as follows
When the illumination is greater than a certain value
When the illumination is less than this value
The complete code is as follows
from machine import Pin, SoftI2C, ADC, PWM
import ssd1306
import utime
import time
# Buzzer settings
buzzer_pin = Pin(5, Pin.OUT)
buzzer_pwm = PWM(buzzer_pin, freq=440, duty=0) # 初始频率为440 Hz,初始占空比为0
i2c = SoftI2C(scl=Pin(7), sda=Pin(6))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# 清空屏幕,并显示任务要求
oled.fill(0)
oled.text("Task 6-3", 0, 0)
oled.text("Light:", 0, 16)
oled.show()
# 光照部分
adc = ADC(Pin(2))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT) #4095
while True:
light_adc = adc.read()
# 计算光照强度单位Lux
light_lux = light_adc * 350 * 1.0 / 4095
# 算出电阻值单位K
light_res = (4095 - light_adc) * 10.0 / light_adc
print("Light(lux):");
print('{:.2f}'.format(light_lux))
print("Light(K):");
print('{:.2f}'.format(light_res))
# 清除变化部分的内容
oled.fill_rect(64,16,64,48,0)
oled.fill_rect(0,48,128,16,0)
oled.text('{:.2f}'.format(light_lux), 64, 16)
if light_lux < 66:
print("We need to turn the light on\n");
oled.text("Turn Light On", 0, 48)
buzzer_pwm.duty(512)
else:
buzzer_pwm.duty(0)
# 在此处更新显示
oled.show()
# 延时1秒
time.sleep(1)
Effect video
task-6_3
|