logo

初始化高电平引脚,想让检测到特点颜色时能将引脚变成低电平,看看是代码问题吗?

2025-04-30 11:08
B
ltuc
import sensor
import time
import math
from machine import Pin
from pyb import LED

# 初始化LED灯对应的引脚,初始化为高电平(熄灭状态)
red_led = Pin('P0', Pin.OUT, value=1)
green_led = Pin('P1', Pin.OUT, value=1)
blue_led = Pin('P2', Pin.OUT, value=1)
# 初始化用于发白光的LED
red_led_rgb = LED(1)  # 红色LED
green_led_rgb = LED(2)  # 绿色LED
blue_led_rgb = LED(3)  # 蓝色LED

# Color Tracking Thresholds (L Min, L Max, A Min, A Max, B Min, B Max)
# The below thresholds track in general red/green things. You may wish to tune them...
thresholds = [
    (30, 100, 15, 127, 15, 127),  # generic_red_thresholds
    (30, 100, -64, -8, -32, 32),  # generic_green_thresholds
    (0, 15, 0, 40, -80, -20),
]  # generic_blue_thresholds
# You may pass up to 16 thresholds above. However, it's not really possible to segment any
# scene with 16 thresholds before color thresholds start to overlap heavily.

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False)  # must be turned off for color tracking
sensor.set_auto_whitebal(False)  # must be turned off for color tracking
clock = time.clock()

# 同时点亮红、绿、蓝三色LED以发出白光并保持常亮
red_led_rgb.on()
green_led_rgb.on()
blue_led_rgb.on()

# 每个像素对应的实际面积(单位:平方厘米),需要根据实际情况调整
pixel_area = 0.01
# 设定的面积阈值(单位:平方厘米)
area_threshold_cm2 = 25

# Only blobs that with more pixels than "pixel_threshold" and more area than "area_threshold" are
# returned by "find_blobs" below. Change "pixels_threshold" and "area_threshold" if you change the
# camera resolution. Don't set "merge=True" because that will merge blobs which we don't want here.

while True:
    clock.tick()
    # 先关闭红、绿、蓝三个用于颜色指示的LED灯,设置为高电平
    red_led.value(1)
    green_led.value(1)
    blue_led.value(1)

    img = sensor.snapshot()
    # 获取图像的宽度和高度
    width = img.width()
    height = img.height()
    # 定义中间区域的大小(这里设置为图像的中心 50%)
    center_x = width // 4
    center_y = height // 4
    center_width = width // 2
    center_height = height // 2
    center_region = (center_x, center_y, center_width, center_height)

    for blob in img.find_blobs(thresholds, pixels_threshold=200, roi=center_region):
        # 计算色块的实际面积(单位:平方厘米)
        blob_area_cm2 = blob.pixels() * pixel_area

        # 检查色块面积是否达到设定阈值
        if blob_area_cm2 >= area_threshold_cm2:
            # 这些值依赖于色块不是圆形,否则它们会不稳定。
            img.draw_rectangle(blob.rect())
            img.draw_cross(blob.cx(), blob.cy())
            # 注意 - 色块旋转角度仅在0 - 180度之间。
            print(blob.code())

            # 根据识别到的颜色点亮对应的LED灯,设置为低电平
            if blob.code() == 1:  # 红色
                red_led.value(0)
            elif blob.code() == 2:  # 绿色
                green_led.value(0)
            elif blob.code() == 4:  # 蓝色
                blue_led.value(0)

    # print(clock.fps())

麻烦大家帮我看下代码,我初始化高电平引脚,然后检测到对应颜色想将引脚变为低电平,但是没成功,是我代码原因,还是硬件原因呢,求指点了。