example for using the rgb_color_sensor class

Dependencies:   mbed rgb_sensor

main.cpp

Committer:
meriac
Date:
2014-06-27
Revision:
4:fbbc729f4152
Parent:
3:3649eaf4f954
Child:
5:1b0f9427be32

File content as of revision 4:fbbc729f4152:

/* 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 500

/* 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%04i", i?",":"", color.data[i] / RGB_OVERSAMPLING);
    console.printf("]\n\r");
}

int main() {
    int i,j;
    TRGB color, *p;

    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);

    /* 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\n\rvar test = [\n\r", g_buffer_pos, timer.read_ms());
        for(j=0; j<RGB_VALUES; j++)
        {
            p = &g_buffer[j];
            for(i=0; i<COUNT(color.data); i++)
                console.printf("%s%+04i", i?",":"\t[", p->data[i] / RGB_OVERSAMPLING);
            if(j<(RGB_VALUES-1))
                console.printf("],\n\r");
        }
        console.printf("]];\n\r\n\r");

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