Firmware SDK
twr_ramp.c
1 #include <twr_ramp.h>
2 
3 static float _twr_ramp_interpolate(twr_tick_t x, twr_tick_t x_min, twr_tick_t x_max, float y_min, float y_max);
4 
5 void twr_ramp_init(twr_ramp_t *self, float start, float stop, twr_tick_t duration)
6 {
7  memset(self, 0, sizeof(*self));
8 
9  self->_start = start;
10  self->_stop = stop;
11  self->_now = start;
12 
13  self->_duration = duration;
14 }
15 
16 void twr_ramp_start(twr_ramp_t *self)
17 {
18  self->_tick_start = twr_tick_get();
19  self->_tick_end = self->_tick_start + self->_duration;
20 
21  self->_active = true;
22 }
23 
24 float twr_ramp_get(twr_ramp_t *self)
25 {
26  if (twr_tick_get() >= self->_tick_end)
27  {
28  self->_active = false;
29  }
30 
31  if (!self->_active)
32  {
33  return self->_stop;
34  }
35 
36  return _twr_ramp_interpolate(twr_tick_get(), self->_tick_start, self->_tick_end, self->_start, self->_stop);
37 }
38 
39 static float _twr_ramp_interpolate(twr_tick_t x, twr_tick_t x_min, twr_tick_t x_max, float y_min, float y_max)
40 {
41  if (x < x_min) { x = x_min; }
42  if (x > x_max) { x = x_max; }
43 
44  return (float) (x - x_min) * (y_max - y_min) / (float) (x_max - x_min) + y_min;
45 }
float twr_ramp_get(twr_ramp_t *self)
Get current ramp value.
Definition: twr_ramp.c:24
void twr_ramp_init(twr_ramp_t *self, float start, float stop, twr_tick_t duration)
Initialize ramp instance.
Definition: twr_ramp.c:5
void twr_ramp_start(twr_ramp_t *self)
Start ramp sequence.
Definition: twr_ramp.c:16
twr_tick_t twr_tick_get(void)
Get absolute timestamp since start of program.
Definition: twr_tick.c:7
uint64_t twr_tick_t
Timestamp data type.
Definition: twr_tick.h:16