[ev3dev × Python] Color sensor

This article is for anyone who wants to work with ev3 in Python. This time, I would like to perform various operations using the color sensor.

table of contents

  1. What to prepare
  2. Color sensor program

0. What to prepare

◯ ev3 (tank), color sensor, touch sensor ◯ Personal computer (VS Code) ◯ bluetooth ◯ microSD ◯ Material (It is recommended to proceed while watching this.)

1. Color sensor program (Document p.33)

1-0. Program to do when the color sensor detects a color

colorsensor00.py


#!/usr/bin/env python3
from ev3dev2.sensor.lego import ColorSensor
from ev3dev2.sound import Sound

cs = ColorSensor()
spkr = Sound()

while True:
    if cs.color == 5:
        spkr.speak('Red is detected')

** Point **: A program that says "Red has been detected" when the color sensor responds to red.

** Point **: Colors are defined in advance corresponding to numbers, and colors are treated as numbers in the program.

color Color detected by the sensor, categorized by overall value. • 0: No color • 1: Black • 2: Blue • 3: Green • 4: Yellow • 5: Red • 6: White • 7: Brown

1-1. Line trace program ①

colorsensor01.py


#!/usr/bin/env python3
from ev3dev2.motor import MoveTank,OUTPUT_A,OUTPUT_B
from ev3dev2.sensor.lego import ColorSensor

tank_drive = MoveTank(OUTPUT_A,OUTPUT_B)
cs = ColorSensor()

while True:
    if cs.reflected_light_intensity < 15:
        tank_drive.on(10,0)
    else:
        tank_drive.on(0,10)

** Point **: A program that runs along the line, depending on the reflectance of the light detected by the color sensor.

** Point **: Line trace Light reflectance is different between black and white. White reflects light well, and black reflects less light. It is a common line trace to run while detecting a black line on a white field by taking advantage of the different reflectance.

1-2. Line trace program ②

colorsensor02.py


#!/usr/bin/env python3
from ev3dev2.motor import MoveTank,OUTPUT_A,OUTPUT_B
from ev3dev2.sensor.lego import ColorSensor
from ev3dev2.sensor import INPUT_1,INPUT_2

tank_drive = MoveTank(OUTPUT_A,OUTPUT_B)
cs_1 = ColorSensor(INPUT_1)
cs_2 = ColorSensor(INPUT_2)

while True:
    if cs_1.reflected_light_intensity > 15:
        if cs_2.reflected_light_intensity > 15:
            tank_drive.on(10,10)
        else:
            tank_drive.on(10,0)
    else:
        if cs_2.reflected_light_intensity > 15:
            tank_drive.on(0,10)
        else:
            tank_drive.on(-10,10)

** Point **: Line trace program using two color sensors

** Point **: Program image

cs_1 detects white and cs_2 detects white: go straight cs_1 detects white and cs_2 detects black: go to the right cs_1 detects black and cs_2 detects white: go left cs_1 detects black and cs_2 detects black: rotate on the fly (search for lines)

1-3. Line trace program ③

colorsensor03.py


#!/usr/bin/env python3
from ev3dev2.motor import OUTPUT_A, OUTPUT_B, MoveTank, SpeedPercent, follow_for_ms
from ev3dev2.sensor.lego import ColorSensor
tank = MoveTank(OUTPUT_A, OUTPUT_B)
tank.cs = ColorSensor()
try:
    tank.follow_line(
    kp=11.3, ki=0.05, kd=3.2,
    speed=SpeedPercent(30),
    follow_for=follow_for_ms,
    ms=4500
    )
except LineFollowErrorTooFast:
    tank.stop()
    raise

** Point **: Line trace program using PID control

** Point **: PID control PID control is a type of feedback control that controls the input value so that the output value approaches the target value.

Output value: Light reflectance Target value: Light reflectance near the line Input value: Motor rotation speed (When line tracing with one color sensor)

Point : follow_line(kp, ki, kd, speed, target_light_intensity=None, follow_left_edge=True, white=60,off_line_count_max=20, sleep_time=0.01, follow_for=,**kwargs)

PID line follower kp, ki, and kd are the PID constants.

** Point **: Reference article about PID control

PID control of line trace car

** Point **: Reference article about python exception handling

Python exception handling (try, except, else, finally)

1-4. A program that matches colors with lists

colorsensor04.py


#!/usr/bin/env python3
from ev3dev2.sensor.lego import ColorSensor,TouchSensor
from ev3dev2.display import Display

cs = ColorSensor()
ts = TouchSensor()
dsp = Display()
color_list = [1,2,4,5]

while True:
    dsp.update()
    if ts.is_pressed:
        if cs.color in color_list:
            dsp.text_pixels(cs.color_name  + ' is detected',True,0,52,font = 'helvB' + '12')
        else:
            dsp.text_pixels('No such color in the color_list',True,0,52,font = 'helvB' + '10')
    else:
        dsp.text_pixels('please set the color !!!!',True,0,52,font = 'helvB' + '12') 

** Point **: Hold down the touch sensor and hold the color. If the color you hold at that time is a color that exists in color_list

Point :

python


 Processing `` `


 ** A program called ** that executes processing if element a is included in b (list in this case)

 Reference article
 [Determine whether a list etc. contains a specific element with the Python in operator]
(https://note.nkmk.me/python-in-basic/)








### 1-5. A program that saves colors in a list

#### **`colorsensor05.py`**
```py

#!/usr/bin/env python3
from ev3dev2.motor import OUTPUT_A,OUTPUT_B,MoveTank
from ev3dev2.sensor.lego import ColorSensor,TouchSensor
from ev3dev2.sound import Sound
from time import sleep

cs = ColorSensor()
ts = TouchSensor()
spkr = Sound()
tank_drive = MoveTank(OUTPUT_A,OUTPUT_B)
color_list = []

for i in range(4):
    ts.wait_for_bump()
    sleep(0.1)
    color_list.append(cs.color)
    spkr.speak(cs.color_name)
for c in color_list:
    sleep(1)
    if c == 1:
        spkr.speak('turn left')
        tank_drive.on_for_rotations(0,50,2)
    if c == 2:
        spkr.speak('go forward')
        tank_drive.on_for_rotations(50,50,2)
    if c == 4:
        spkr.speak('turn right')
        tank_drive.on_for_rotations(50,0,2)
    if c == 5:
        spkr.speak('go back')
        tank_drive.on_for_rotations(-10,-10,2)

** Point **: Add the color that was held up when the touch sensor was pressed to the empty color_list. After adding, the process associated with the color is executed in order from the top of the list.

Point : append() You can add elements to the end of the list

Reference article Append, extend, insert to add an element to a list (array) in Python

Finally

Thank you for reading! !! Next time, I would like to write about ultrasonic sensors!

I want to make a better article ◯ This is easier to understand ◯ This is difficult to understand ◯ This is wrong ◯ I want you to explain more here We appreciate your opinions and suggestions.

Recommended Posts

[ev3dev × Python] Color sensor
[ev3dev × Python] Ultrasonic sensor
[ev3dev × Python] Touch sensor
[ev3dev × Python] Gyro sensor
[ev3dev × Python] Intelligent block button
blender, python, spiral staircase, color
[Python] Adjusting the color bar
[ev3dev × Python] Build ev3dev development environment
Blender 2.9, Python, hexadecimal color specification
[ev3dev × Python] Single motor control
[ev3dev × Python] Control of multiple motors
Python
[python] Clock that changes color (animation)
[Python] Adjusted the color map standard
Python colorama Color memo (Cmder environment)
Data formatting for Python / color plots
[ev3dev × Python] Display, audio, LED control
Blender 2.9, Python background light color test
Try to reproduce color film with Python
Get keystrokes from / dev / input (python evdev)
Output color characters to pretty with python
100 image processing by Python Knock # 6 Color reduction processing
[ev3dev × Python] SSH Control (remote control with keyboard)
[Python] Get the main color from the screenshot