Member-only story
MicroPython Tutorial XIV
Lets move forward to the most interesting of all the sensors you get with the LEGO MINDSTORMS sets, the colour sensor. It is if you have extra budget the one to buy more of since it is the most versatile by far.
Some background. The colour sensor, you need to spell it the American way in your code has four modes in MicroPython. Color, which returns one of 9 colours excluding “noneType” which means it can’t tell. Ambient, which returns a grey scale going form zero [dark] to 100 [bright]. Reflection which also returns a scale going from 0 [no reflection] to 100 [highly reflective]. And finally rgb, the most flexible, and difficult to configure a tupple with red, green and blue light intensities figures ranging from 0.0 to 100.0
How do you use it, firstly its much like all the others, you need to name it in the devices and then declare in your code where it is plugged in.
from pybricks.ev3devices import ColorSensor
colourScanner = ColorSensor(Port.S1)
Notice I how I spelt color, the American spelling. Beyond that you need simply call one of the methods in the class mentioned. Here a quick script showing it reading a colored set of lines.
#!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.parameters import Color, Port
from pybricks.tools import wait
from pybricks.ev3devices import ColorSensor, MotorcolorScanned = ColorSensor(Port.S1)
colorSeen = colorScanned.color()