Color recognition sensor ・ 颜色识别
Colorユニット(TCS3472)で色を読み取り、識別します。
この構成をエディタで開く・編集する →| 部品 | 役割 | ポート | リンク・価格 |
|---|---|---|---|
| M5Stack Core2 | Controller | grove_i2c, grove_analog, grove_uart, mbus | official page — $46.9 |
| Unit Color | Color sensor | grove_i2c | official page — $11.5 |
M5Stack Core2とColor Unit(TCS3472)を使って、色を読み取って識別する装置です。Color Unitが対象物のRGB値を測定し、Core2の画面に色名を表示します。I2C通信でデータをやり取りするので、配線はとても簡単です。
# M5Stack Core2 + Color Unit (TCS3472) - Color recognition
# Wiring: Color Unit -> Core2 red Port.A (I2C)
import time
from machine import Pin, I2C
from m5stack import lcd
# Initialize I2C on Port.A (Core2: scl=22, sda=21)
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=100000)
# TCS3472 I2C address is 0x29
TCS3472_ADDR = 0x29
# Register addresses
REG_ENABLE = 0x80
REG_ATIME = 0x81
REG_CONTROL = 0x8F
REG_RGBC_DATA = 0x94
# Enable register bits
ENABLE_PON = 0x01
ENABLE_AEN = 0x02
# Initialize sensor
def init_sensor():
# Power on
i2c.writeto(TCS3472_ADDR, bytes([REG_ENABLE, ENABLE_PON]))
time.sleep(0.01)
# Enable ADC
i2c.writeto(TCS3472_ADDR, bytes([REG_ENABLE, ENABLE_PON | ENABLE_AEN]))
# Set integration time (ATIME = 0xFF -> 2.4ms, low resolution but fast)
i2c.writeto(TCS3472_ADDR, bytes([REG_ATIME, 0xFF]))
# Set gain (CONTROL = 0x00 -> 1x gain)
i2c.writeto(TCS3472_ADDR, bytes([REG_CONTROL, 0x00]))
time.sleep(0.01)
# Read RGBC data (clear, red, green, blue) as 16-bit values
def read_rgbc():
data = i2c.readfrom_mem(TCS3472_ADDR, REG_RGBC_DATA, 8)
c = data[0] | (data[1] << 8)
r = data[2] | (data[3] << 8)
g = data[4] | (data[5] << 8)
b = data[6] | (data[7] << 8)
return r, g, b, c
# Simple color name based on normalized RGB
def color_name(r, g, b):
total = r + g + b
if total == 0:
return "Black"
# Normalize to 0-1
rn = r / total
gn = g / total
bn = b / total
if rn > 0.6 and gn < 0.3 and bn < 0.3:
return "Red"
if gn > 0.6 and rn < 0.3 and bn < 0.3:
return "Green"
if bn > 0.6 and rn < 0.3 and gn < 0.3:
return "Blue"
if rn > 0.4 and gn > 0.4 and bn < 0.2:
return "Yellow"
if rn > 0.3 and gn < 0.3 and bn > 0.3:
return "Purple"
if rn < 0.2 and gn < 0.2 and bn < 0.2:
return "Black"
if rn > 0.3 and gn > 0.3 and bn > 0.3:
return "White"
return "Unknown"
init_sensor()
while True:
r, g, b, c = read_rgbc()
name = color_name(r, g, b)
lcd.clear()
lcd.print('R: %d' % r, 10, 20)
lcd.print('G: %d' % g, 10, 40)
lcd.print('B: %d' % b, 10, 60)
lcd.print('Color: %s' % name, 10, 80)
time.sleep(1)
この作り方はAIが構成から生成したものです(未検証)。通電前に配線とコードをご確認ください。
この構成はAIが実在するM5Stack部品から設計し、ポート互換をサーバで検証したものです。編集・共有できます。
エディタで開く →UnitKit は M5Stack® 製品向けの非公式ツール。作りたいものを書くと、部品リストと配線図が出ます。