光敏電阻

光敏電阻

MicroPython 程式碼範例 運行在 Raspberry Pi Pico 2 W 微控制器上 在麵包板上,​​連接到光敏電阻模組、RGB LED 模組和 OLED 顯示模組 (SSD1306)。 根據光敏電阻測量的環境光變化,調整 LED 的亮度或亮度。

光敏電阻表面受光量越大,通過的電流就越大;受光量越小,通過的電流就越小。. 它用於在光線較暗的環境下調暗手機螢幕,並在戶外陽光強烈時調亮螢幕。. 有些電視利用這項技術來調暗螢幕,使其與室內環境光線相匹配,看起來就像印刷在牆上的藝術品一樣。. 循線機器人利用它來區分深色線條和淺色表面。.

在 Thonny 中建立一個名為 photoresistor.py 的新檔案。. 將以下程式碼複製並貼上到您建立的文件中。.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
print("\nPhotoresistor")

# DESCRIPTION

# A photoresister allows more electricity to flow when more light hits its surface,
# and less electricity to flow when less light hits its surface. It is used to dim a 
# phone screen in low light, and brighten it when outdoors under bright sunlight. Some TVs
# use it to dim the display to match the ambient room light, to appear like printed wall art.
# Line tracking robots use it to distinguish between a dark line and a light surface.

# CONNECTIONS REQUIRED

# Connect Photoresistor (KY-018) module 
# (labeled 'Analog Sensor' with a small round head with squiggly line)
#   Pins: GND => GND, VCC => VCC, S => GP28

from time import sleep
from machine import Pin, ADC
from oled import OLED
from buzzer import Buzzer
from rgbled import RGBLED
from value_filter import ValueFilter

sensor = ADC(Pin(28))
value_filter = ValueFilter(filter="SMA", window_size=10)
oled = OLED(scl_pin=15, sda_pin=14)
buzzer = Buzzer(pwm_pin=16)
rgbled = RGBLED(red_pin=12, green_pin=11, blue_pin=10)

sensor_max = 65535

try:
    while True:
        # Use Simple Moving Average filter to smooth out readings
        value = value_filter.update(sensor.read_u16())
        fraction = value / sensor_max
        white = round(fraction * fraction * 255) # use fraction squared to visualize change in light
        rgbled.set_color(w=white)
        oled.print(f"Intensity: {fraction * 100:0.0f}%")
        sleep(0.05)

except KeyboardInterrupt:
    print("\nInterrupted by user!")

finally:
    oled.reset()
    rgbled.reset()
    buzzer.reset()

回到頂部

讓教師和學生更容易參與動手發明創造.
© 2026 Inventor Pi, Inc.
Inventor Pi, Inc.是一家註冊的 501(c)(3) 非營利組織