碰撞传感器

碰撞传感器

MicroPython 代码示例 运行在 Raspberry Pi Pico 2 W 微控制器上 在面包板上,连接着碰撞传感器模块(带限位开关)、RGB LED 模块和 OLED 显示模块 (SSD1306)。 检测到碰撞时,改变 LED 指示灯颜色并在显示屏上显示碰撞状态。

碰撞传感器使用限位开关. 这可以与硬限位器配合使用,以检测机械臂等机构何时达到其运动极限并触发限位开关。. 它也用于烤箱和冰箱门上,以便在门打开时打开内部照明灯。.

在 Thonny 中创建一个名为 crash_sensor.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
print("\nCrash Sensor")

# DESCRIPTION

# A crash sensor uses a limit switch. This can be used with a hard stop to detect 
# when a mechanism, such as a robotic arm, reaches the limit of its motion and
# trigger a limit switch. It is also used in oven and refrigerator doors to turn 
# on the internal light when the door is opened.

# CONNECTIONS REQUIRED

# Connect Crash Sensor (KY-021) module 
#   Pins: GND => GND, VCC => VCC, S => GP28

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

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)

try:
    while True:
        
        # Sensor value is 1 => No crash detected.
        # Loop while no crash detected
        oled.reset()
        rgbled.set_color(g=255)
        while sensor.value() == 1: pass
        
        # Sensor value is no longer 1 => Crash detected.
        # Loop while crash detected
        oled.print("Crash")
        rgbled.set_color(r=255)
        buzzer.play_tone(200)
        while sensor.value() == 0: pass

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

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

返回顶部

让教师和学生更容易参与动手发明创造.
© 2026 Inventor Pi, Inc.
Inventor Pi, Inc.是一家注册的 501(c)(3) 非营利组织