example for using the rgb_color_sensor class

Dependencies:   mbed rgb_sensor

main.cpp

Committer:
meriac
Date:
2014-06-28
Revision:
6:236bee733ec3
Parent:
5:1b0f9427be32

File content as of revision 6:236bee733ec3:

/* Discrete RGB color sensor
 *
 * - uses single-channel light-dependent resistor (via ADC)
 *   and a RGB LED.
 * -  compensates background light
 *
 * Copyright (c) 2014 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <mbed.h>
#include "rgb_sensor.h"

#define COUNT(x) (sizeof(x)/sizeof(x[0]))
#define RGB_VALUES 250

/* serial console */
static uint32_t g_buffer_pos;
static TRGB g_buffer[RGB_VALUES];
static Serial console(USBTX, USBRX);

static bool rgb_callback(const TRGB &color)
{
    if(g_buffer_pos>=RGB_VALUES)
        return false;

    g_buffer[g_buffer_pos++] = color;
    return true;
}

static void rgb_print(const TRGB &color)
{
    int i;

    console.printf("\t[");
    for(i=0; i<COUNT(color.data); i++)
        console.printf("%s%4i", i?",":"", color.data[i] / RGB_OVERSAMPLING);
    console.printf("]");
}

int main() {
    int i;
    TRGB color;

    console.baud(115200);

    /* R,G,B pins and ADC for light dependent resistor */
    RGB_Sensor rgb(p23,p24,p25,p20);

    /* detect a single RGB value to demo synchronous API */
    rgb.capture(color);
    rgb_print(color);
    console.printf(";\r\n");

    /* needed for time measurement */
    Timer timer;

    g_buffer_pos = 0;

    while(1) {

        /* start four channel RGB conversion */
        timer.reset();
        timer.start();

        g_buffer_pos = 0;
        rgb.capture(rgb_callback);

        rgb.wait();

        /* stop time measurement */
        timer.stop();

        console.printf("// captured %i values in %i ms (%i/s)\r\nvar test = [\r\n",
            RGB_VALUES,
            timer.read_ms(),
            (RGB_VALUES*1000UL)/timer.read_ms());

        for(i=0; i<RGB_VALUES; i++)
        {
            rgb_print(g_buffer[i]);
            console.printf(i<(RGB_VALUES-1) ? ",\r\n":"];\r\n\r\n");
        }

        /* visible intersection between captures */
        wait_ms(100);
    }
}