光中斷器

光中斷器

MicroPython 程式碼範例 運行在 Raspberry Pi Pico 2 W 微控制器上 在麵包板上,​​連接光電斷路器模組、RGB LED 模組和 OLED 顯示模組 (SSD1306)。 每次光電中斷器光束中斷時,顯示幕上的計數增加。

光電斷路器模組會將紅外線光束從發射器發送到接收器(模組上的兩個黑色方塊),並偵測該光束何時被遮蔽。. 它用於檢測3D列印機、CNC機床和機器人的行程終點。. 它也用於計算旋轉的開槽圓盤的脈衝數,從而計算機器人和智慧汽車中的馬達或車輪速度。. 印表機可以偵測紙張是否存在。.

在 Thonny 中建立一個名為 photo_interrupter.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
49
50
print("\nPhoto Interrupter")

# DESCRIPTION

# A photo interrupter module sends infrared light beam from an emitter to a receiver 
# (the two black blocks on the module), and detects when this beam is blocked. 
# It is used to detect end-of-travel in 3D printers, CNC machines and robots. It is
# also used to count the pulses of a slotted disc rotating to calculate motor or wheel
# speed in robotics and smart cars. In a printer, it detects when a paper is present.

# CONNECTIONS REQUIRED

# Connect Photo Interrupter (KY-010) module (labeled 'IR Switch')
#   Pins: GND => GND, VCC => VCC, S => GP28

from machine import Pin
from oled import OLED
from rgbled import RGBLED
from buzzer import Buzzer

sensor = Pin(28, Pin.IN, Pin.PULL_UP)
oled = OLED(scl_pin=15, sda_pin=14)
buzzer = Buzzer(pwm_pin=16)
rgbled = RGBLED(red_pin=12, green_pin=11, blue_pin=10)

counter = 0

try:
    while True:
        rgbled.reset()
        
        # loop while nothing detected
        while sensor.value() == 0: pass
        
        # sensor value is no longer zero => object detected
        counter += 1
        oled.print(f"Counter: {counter}")
        rgbled.set_color(b=255)
        buzzer.play_tone(600)
        
        # loop while object is still present
        while sensor.value() == 1: pass

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

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

回到頂部

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