31 lines
768 B
Python
31 lines
768 B
Python
from machine import Pin, ADC, I2C
|
||
import time
|
||
from ssd1306 import SSD1306_I2C
|
||
|
||
# ----- ADC (Grove Light Sensor) -----
|
||
light_adc = ADC(Pin(1))
|
||
light_adc.atten(ADC.ATTN_11DB) # 0–3.3V range
|
||
light_adc.width(ADC.WIDTH_12BIT) # 0–4095
|
||
|
||
# ----- I2C (OLED) -----
|
||
i2c = I2C(0, scl=Pin(9), sda=Pin(8), freq=400000)
|
||
oled = SSD1306_I2C(128, 64, i2c)
|
||
|
||
def read_light(samples=8):
|
||
total = 0
|
||
for _ in range(samples):
|
||
total += light_adc.read()
|
||
time.sleep_ms(5)
|
||
return total // samples
|
||
|
||
while True:
|
||
raw = read_light()
|
||
percent = int((raw / 4095) * 100)
|
||
|
||
oled.fill(0)
|
||
oled.text("Light Sensor", 0, 0)
|
||
oled.text("Raw: {}".format(raw), 0, 20)
|
||
oled.text("Level: {}%".format(percent), 0, 40)
|
||
oled.show()
|
||
|
||
time.sleep(0.5) |