Allan Wang
/
rgbfade
See http://mbed.org/users/allanw/notebook/controlling-high-power-rgb-led/
Embed:
(wiki syntax)
Show/hide line numbers
main.cpp
00001 #include "mbed.h" 00002 #include <cmath> 00003 00004 #define PERIOD 2000 00005 00006 float analog_avg(AnalogIn ain, int samples); 00007 float exp_curve(float x, float a); 00008 void HSVtoRGB( float *r, float *g, float *b, float h, float s, float v ); 00009 00010 AnalogIn pot(p20); 00011 PwmOut red(p23); 00012 PwmOut green(p21); 00013 PwmOut blue(p22); 00014 PwmOut sync(p25); 00015 DigitalOut out1(p30); 00016 00017 int main() { 00018 int period = PERIOD; 00019 float r, g, b; 00020 00021 red.period_us(period); 00022 green.period_us(period); 00023 blue.period_us(period); 00024 sync.period_us(period); 00025 sync.pulsewidth_us(period/2); 00026 while (1) { 00027 /*float h = pot * 360.0f; 00028 HSVtoRGB(&r, &g, &b, h, 1, 0.1); 00029 red.pulsewidth_us(r * PERIOD); 00030 green.pulsewidth_us(g * PERIOD); 00031 blue.pulsewidth_us(b * PERIOD);*/ 00032 00033 for (float h = 0; h < 360; h += 0.1) { 00034 out1 = 1; 00035 out1 = 0; 00036 HSVtoRGB(&r, &g, &b, h, 1, exp_curve(analog_avg(pot,3), 4)); 00037 00038 red.pulsewidth_us(exp_curve(r,1.5) * PERIOD); 00039 green.pulsewidth_us(exp_curve(g,1.5) * PERIOD); 00040 blue.pulsewidth_us(exp_curve(b,1.5) * PERIOD); 00041 00042 wait_us(1000); 00043 } 00044 } 00045 } 00046 00047 float analog_avg(AnalogIn ain, int samples) { 00048 int sum = 0; 00049 00050 for (int i = 0; i < samples; i++) { 00051 sum += ain.read_u16(); 00052 } 00053 00054 return (sum / samples) / ((float)0xFFFF); 00055 } 00056 00057 // returns a value between 0.0 and 1.0 for an input x of 0.0 to 1.0 00058 // a affects how "exponential" this curve will be 00059 float exp_curve(float x, float a) { 00060 return (exp(x*a)-1)/(exp(a) - 1); 00061 } 00062 00063 00064 void HSVtoRGB( float *r, float *g, float *b, float h, float s, float v ) 00065 { 00066 int i; 00067 float f, p, q, t; 00068 if( s == 0 ) { 00069 // achromatic (grey) 00070 *r = *g = *b = v; 00071 return; 00072 } 00073 h /= 60; // sector 0 to 5 00074 i = floor( h ); 00075 f = h - i; // factorial part of h 00076 p = v * ( 1 - s ); 00077 q = v * ( 1 - s * f ); 00078 t = v * ( 1 - s * ( 1 - f ) ); 00079 switch( i ) { 00080 case 0: 00081 *r = v; 00082 *g = t; 00083 *b = p; 00084 break; 00085 case 1: 00086 *r = q; 00087 *g = v; 00088 *b = p; 00089 break; 00090 case 2: 00091 *r = p; 00092 *g = v; 00093 *b = t; 00094 break; 00095 case 3: 00096 *r = p; 00097 *g = q; 00098 *b = v; 00099 break; 00100 case 4: 00101 *r = t; 00102 *g = p; 00103 *b = v; 00104 break; 00105 default: // case 5: 00106 *r = v; 00107 *g = p; 00108 *b = q; 00109 break; 00110 } 00111 }
Generated on Wed Jul 13 2022 20:50:39 by 1.7.2