Continuously vary LED brightness between completely dark and fully lite.
Diff: Glowing.cpp
- Revision:
- 0:26c09c4aba81
- Child:
- 1:eef7593bdcc5
diff -r 000000000000 -r 26c09c4aba81 Glowing.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Glowing.cpp Wed Dec 29 03:32:39 2010 +0000 @@ -0,0 +1,44 @@ +#include "mbed.h" +#include "math.h" +#include "Glowing.h" + +Glowing::Glowing(PinName pin, float period, int steps, int offset) { + // Set the constants + s_port = new PwmOut(pin); + s_steps = steps; + s_step_offset = offset; + c_circle = 2*acos(-1.0); // 2 PI + c_step_time = period/steps; + c_step_gradient = c_circle/steps; + s_running = false; +} + +Glowing::~Glowing() { + Stop(); +} + +int Glowing::scale(float x) { + // Scaling the input value from [-1.0 - 1.0] to [0 - 1000] + return (int)((x + 1.0)*1000/2); +} +void Glowing::next(void) { + // Set the PWM value + s_port->pulsewidth_us(s_next_v); + // Calculate the next step and the corresponding PWM value + s_next_n = (s_next_n + 1) % s_steps; + s_next_v = scale(cos(s_next_n * c_step_gradient)); +} + +void Glowing::Start(void) { + s_port->period_ms(1); + s_next_v = 0.0; + s_next_n = s_steps/2 + s_step_offset; + attach(this, &Glowing::next, c_step_time); + s_running = true; +} + +void Glowing::Stop(void) { + if (s_running) { + detach(); + } +} \ No newline at end of file