Wheel IDE

Online demo »

Light and color sensor

Powered Up Light and color sensor example

This example shows how to detect a color and change the color of the light accordingly.

If you are using a Move Hub then this exemple expects the light sensor to be connected to port "C". If you are using the Hub -which has only two ports- then you can change the inputPort value POWERED_UP_PORT_C to POWERED_UP_PORT_A and connect the sensor to port "A"...

Code

#project "Powered Up Light and color sensor example"

#include "lib/modules/standard.whl"
#include "lib/modules/device.whl"
#include "lib/modules/poweredUp.whl"
#include "lib/modules/light.whl"
#include "lib/modules/sensor.whl"

#display "Hub"

proc main()
    ; Select the Powered Up device in the IDE...
    selectDevice(DEVICE_POWERED_UP)

    number inputPort = POWERED_UP_PORT_C

    sensorLayerSetMode(LAYER_1, inputPort, POWERED_UP_SENSOR_MODE_COLOR)

    number lastValue = -1

    repeat
        ; Read the color value:
        number value = sensorLayerRead(LAYER_1, inputPort)

        ; Check if the value is changed:
        if value != lastValue
            ; The value is changed!
            lastValue = value

            ; Set the light to the detected color...
            select value
                case COLOR_BLUE:
                    light(LIGHT_PU_BLUE)
                case COLOR_GREEN:
                    light(LIGHT_PU_GREEN)
                case COLOR_YELLOW:
                    light(LIGHT_PU_YELLOW)
                case COLOR_RED:
                    light(LIGHT_PU_RED)
                case COLOR_WHITE:
                    light(LIGHT_PU_WHITE)
                case COLOR_BLACK:
                    light(LIGHT_PU_BLACK)
                case COLOR_NONE:
                    light(LIGHT_PU_NONE)
            end
        end
    end
end