2b

Dependencies:   mbed

main.cpp

Committer:
NiallCunningham
Date:
2016-09-23
Revision:
0:ee2cf7a77b73

File content as of revision 0:ee2cf7a77b73:

//RGB LED Colour variation program
//The pogram varies the colour of the RGB LED based on the analogue input value of POT2


#include "mbed.h"
Serial pc(USBTX, USBRX);    // USB serial interface
AnalogIn A_in(p20);         // analogue input pin for reference values
//DigitalOut myled(LED1);     // onboard LED to indicate activity
PwmOut Rled(p23);           // red component of application board RGB LED
PwmOut Gled(p24);           // green component of application board RGB LED
PwmOut Bled(p25);           // blue component of application board RGB LED
#define NUMREADINGS 1000
#define BRIGHTNESS 8.0      // RGB LED brightness divider (higher number -> dimmer light)
int main() {
float AIreadings=0.0;       // variable to hold cumulative analogue input values
float AIavg=0.0;            // average analogue input value (0.0-1.0)
float colour_level[11][4]={{0.09,1.0,0.0,0.0},
{0.18,1.0,0.5,0.0},
{0.27,1.0,1.0,0.0},
{0.36,0.5,1.0,0.0},
{0.45,0.0,1.0,0.0},
{0.54,0.0,1.0,0.5},
{0.63,0.0,1.0,1.0},
{0.72,0.0,0.5,1.0},
{0.81,0.0,0.0,1.0},
{0.90,0.5,0.0,1.0},
{1.00,1.0,0.0,1.0}};        // analogue input values vs. RGB levels
float Rval=1.0;
float Gval=1.0;
float Bval=1.0;
int i=0;
// set the USB serial interface baud rate
pc.baud(921600);

while(1) {
AIreadings = 0;
// myled = 1; // turn on indicator LED and take first half of the readings
for (i=0; i<NUMREADINGS/2; i++) {
AIreadings = AIreadings + A_in.read();
}
wait(0.050);
// myled = 0; // turn off indicator LED and take second half of the readings
for (i=NUMREADINGS/2; i<NUMREADINGS; i++) {
AIreadings = AIreadings + A_in.read();
}
wait(0.050);
AIavg = AIreadings/NUMREADINGS; // take the average of the NUMREADINGS analogue values
// set the RGB LED colour based on the average analogue input value
// 0.0 ------------------------------------------------------------------------> 1.0
// RED ORANGE YELLOW LIGHT-GREEN GREEN GREEN-BLUE CYAN LIGHT-BLUE BLUE VIOLET FUSCHA

i=0;
while(AIavg>colour_level[i][0]){
i++;
}
// the RGB LED uses reverse logic for brightness: 0.0 = bright; 1.0 = off
// Rled = 1.0 - colour_level[i][1]/BRIGHTNESS;
// Gled = 1.0 - colour_level[i][2]/BRIGHTNESS;
// Bled = 1.0 - colour_level[i][3]/BRIGHTNESS;
Rval = cos(AIavg*2*3.14159)/2+0.5;
Gval = sin(AIavg*2*3.14159)/2+0.5;
Bval = AIavg;
Rled = 1.0 - Rval/BRIGHTNESS;
Gled = 1.0 - Gval/BRIGHTNESS;
Bled = 1.0 - Bval/BRIGHTNESS;
// export the readings to a terminal program via the USB cable
pc.printf("Average: %6.4f, R: %6.4f G: %6.4f B: %6.4f\r", AIavg,Rval,Gval,Bval);
}
}