Added a customizable pwm "animate" function. Added color types. Added a
[cerebrum.git] / pwm.c
blob493c92f2f71f2a33f8561c77575708a639b95055
2 #include "pwm.h"
3 #include "led.h"
4 #include "util.h"
5 #ifdef HAS_PWM_SUPPORT
7 void pwm_loop(){
8 #ifdef PWM_ANIMATE
9 pwm_animate();
10 #endif//PWM_ANIMATE
13 void pwm_setup(){
14 //s/w "BCM"(<== "Binary Code Modulation") timer setup
15 TCCR0A |= _BV(WGM01);
16 TCCR0B |= _BV(CS02);
17 TIMSK0 |= _BV(OCIE0A);
18 OCR0A = 1;
19 pwm_output_setup();
22 ISR(TIMER0_COMPA_vect){
23 pwm_unset_outputs();
24 pwm_cycle<<=1;
25 if(!pwm_cycle){
26 pwm_cycle = 1;
28 uint8_t Q = 0;
29 Q |= (pwm_val[0] & pwm_cycle)?1:0;
30 Q |= (pwm_val[1] & pwm_cycle)?2:0;
31 Q |= (pwm_val[2] & pwm_cycle)?4:0;
32 Q |= (pwm_val[3] & pwm_cycle)?8:0;
33 Q |= (pwm_val[4] & pwm_cycle)?16:0;
34 Q |= (pwm_val[5] & pwm_cycle)?32:0;
35 Q |= (pwm_val[6] & pwm_cycle)?64:0;
36 Q |= (pwm_val[7] & pwm_cycle)?128:0;
37 pwm_set_outputs(Q);
38 TCNT0 = 0;
39 OCR0A = pwm_cycle;
42 uint8_t pwm_cycle = 1;
43 uint8_t pwm_val[8];
45 rgb_value_t hsv_to_rgb(hsv_value_t k){
46 //The following algorithm is loosely based on http://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB
47 uint16_t c_ = (uint16_t)k.v * (uint16_t)k.s;
48 uint8_t c = c_>>8;
49 uint8_t m = k.v - c;
50 rgb_value_t ret = {0, 0, 0};
51 uint8_t branch;
52 uint8_t h_;
53 if(k.h<128){
54 if(k.h<85){
55 if(k.h<43){
56 h_ = k.h;
57 branch = 0;
58 }else{
59 h_ = 43-k.h;
60 branch = 1;
62 }else{
63 h_ = k.h-128;
64 branch = 2;
66 }else{
67 if(k.h<171){
68 h_ = 171-k.h;
69 branch = 3;
70 }else{
71 if(k.h<213){
72 h_ = k.h-171;
73 branch = 4;
74 }else{
75 h_ = 255-k.h;
76 branch = 5;
80 uint16_t x_ = c * (uint16_t)h_;
81 uint8_t x = x_>>8;
82 switch(branch){
83 case 0:
84 ret.r += c;
85 ret.g += x;
86 break;
87 case 1:
88 ret.r += x;
89 ret.g += c;
90 break;
91 case 2:
92 ret.g += c;
93 ret.b += x;
94 break;
95 case 3:
96 ret.g += x;
97 ret.b += c;
98 break;
99 case 4:
100 ret.r += x;
101 ret.b += c;
102 break;
103 case 5:
104 ret.r += c;
105 ret.b += x;
106 break;
108 return ret;
111 #else//HAS_PWM_SUPPORT
113 void pwm_setup(){}
114 void pwm_loop(){}
116 #endif//HAS_PWM_SUPPORT