Continuously vary LED brightness between completely dark and fully lite.

Committer:
sitti
Date:
Thu Dec 30 04:22:45 2010 +0000
Revision:
1:eef7593bdcc5
Parent:
0:26c09c4aba81
2010-12-29 Remove a member variable and revise the example.

Who changed what in which revision?

UserRevisionLine numberNew contents of line
sitti 0:26c09c4aba81 1 #include "mbed.h"
sitti 0:26c09c4aba81 2 #include "math.h"
sitti 0:26c09c4aba81 3 #include "Glowing.h"
sitti 0:26c09c4aba81 4
sitti 0:26c09c4aba81 5 Glowing::Glowing(PinName pin, float period, int steps, int offset) {
sitti 0:26c09c4aba81 6 // Set the constants
sitti 0:26c09c4aba81 7 s_port = new PwmOut(pin);
sitti 0:26c09c4aba81 8 s_steps = steps;
sitti 0:26c09c4aba81 9 s_step_offset = offset;
sitti 0:26c09c4aba81 10 c_step_time = period/steps;
sitti 1:eef7593bdcc5 11 c_step_gradient = 2*acos(-1.0)/steps; // 2 PI/steps
sitti 0:26c09c4aba81 12 s_running = false;
sitti 0:26c09c4aba81 13 }
sitti 0:26c09c4aba81 14
sitti 0:26c09c4aba81 15 Glowing::~Glowing() {
sitti 0:26c09c4aba81 16 Stop();
sitti 0:26c09c4aba81 17 }
sitti 0:26c09c4aba81 18
sitti 0:26c09c4aba81 19 int Glowing::scale(float x) {
sitti 0:26c09c4aba81 20 // Scaling the input value from [-1.0 - 1.0] to [0 - 1000]
sitti 0:26c09c4aba81 21 return (int)((x + 1.0)*1000/2);
sitti 0:26c09c4aba81 22 }
sitti 0:26c09c4aba81 23 void Glowing::next(void) {
sitti 0:26c09c4aba81 24 // Set the PWM value
sitti 0:26c09c4aba81 25 s_port->pulsewidth_us(s_next_v);
sitti 0:26c09c4aba81 26 // Calculate the next step and the corresponding PWM value
sitti 0:26c09c4aba81 27 s_next_n = (s_next_n + 1) % s_steps;
sitti 0:26c09c4aba81 28 s_next_v = scale(cos(s_next_n * c_step_gradient));
sitti 0:26c09c4aba81 29 }
sitti 0:26c09c4aba81 30
sitti 0:26c09c4aba81 31 void Glowing::Start(void) {
sitti 0:26c09c4aba81 32 s_port->period_ms(1);
sitti 0:26c09c4aba81 33 s_next_v = 0.0;
sitti 0:26c09c4aba81 34 s_next_n = s_steps/2 + s_step_offset;
sitti 0:26c09c4aba81 35 attach(this, &Glowing::next, c_step_time);
sitti 0:26c09c4aba81 36 s_running = true;
sitti 0:26c09c4aba81 37 }
sitti 0:26c09c4aba81 38
sitti 0:26c09c4aba81 39 void Glowing::Stop(void) {
sitti 0:26c09c4aba81 40 if (s_running) {
sitti 0:26c09c4aba81 41 detach();
sitti 0:26c09c4aba81 42 }
sitti 0:26c09c4aba81 43 }