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)
效果视频