![](/media/cache/profiles/cc38c8ffd23cef2e3e5c21d20c1db636.jpg.50x50_q85.png)
all publish
main.cpp@0:d04469a1b180, 2019-05-06 (annotated)
- Committer:
- daikinect
- Date:
- Mon May 06 00:20:37 2019 +0000
- Revision:
- 0:d04469a1b180
all publish
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
daikinect | 0:d04469a1b180 | 1 | #include "mbed.h" |
daikinect | 0:d04469a1b180 | 2 | |
daikinect | 0:d04469a1b180 | 3 | Timeout timer; |
daikinect | 0:d04469a1b180 | 4 | DigitalOut my_led(LED1); |
daikinect | 0:d04469a1b180 | 5 | DigitalOut my_pwm(D10); // IO used by pwm_io function |
daikinect | 0:d04469a1b180 | 6 | |
daikinect | 0:d04469a1b180 | 7 | int on_delay = 0; |
daikinect | 0:d04469a1b180 | 8 | int off_delay = 0; |
daikinect | 0:d04469a1b180 | 9 | |
daikinect | 0:d04469a1b180 | 10 | void toggleOff(void); |
daikinect | 0:d04469a1b180 | 11 | |
daikinect | 0:d04469a1b180 | 12 | void toggleOn(void) { |
daikinect | 0:d04469a1b180 | 13 | my_pwm = 1; |
daikinect | 0:d04469a1b180 | 14 | timer.attach_us(toggleOff, on_delay); |
daikinect | 0:d04469a1b180 | 15 | } |
daikinect | 0:d04469a1b180 | 16 | |
daikinect | 0:d04469a1b180 | 17 | void toggleOff(void) { |
daikinect | 0:d04469a1b180 | 18 | my_pwm = 0; |
daikinect | 0:d04469a1b180 | 19 | timer.attach_us(toggleOn, off_delay); |
daikinect | 0:d04469a1b180 | 20 | } |
daikinect | 0:d04469a1b180 | 21 | |
daikinect | 0:d04469a1b180 | 22 | // p_us = signal period in micro_seconds |
daikinect | 0:d04469a1b180 | 23 | // dc = signal duty-cycle (0.0 to 1.0) |
daikinect | 0:d04469a1b180 | 24 | void pwm_io(int p_us, float dc) { |
daikinect | 0:d04469a1b180 | 25 | timer.detach(); |
daikinect | 0:d04469a1b180 | 26 | if ((p_us == 0) || (dc == 0)) { |
daikinect | 0:d04469a1b180 | 27 | my_pwm = 0; |
daikinect | 0:d04469a1b180 | 28 | return; |
daikinect | 0:d04469a1b180 | 29 | } |
daikinect | 0:d04469a1b180 | 30 | if (dc >= 1) { |
daikinect | 0:d04469a1b180 | 31 | my_pwm = 1; |
daikinect | 0:d04469a1b180 | 32 | return; |
daikinect | 0:d04469a1b180 | 33 | } |
daikinect | 0:d04469a1b180 | 34 | on_delay = (int)(p_us * dc); |
daikinect | 0:d04469a1b180 | 35 | off_delay = p_us - on_delay; |
daikinect | 0:d04469a1b180 | 36 | toggleOn(); |
daikinect | 0:d04469a1b180 | 37 | } |
daikinect | 0:d04469a1b180 | 38 | |
daikinect | 0:d04469a1b180 | 39 | int main() { |
daikinect | 0:d04469a1b180 | 40 | |
daikinect | 0:d04469a1b180 | 41 | pwm_io(20000, 0.25); // 20ms - 25% |
daikinect | 0:d04469a1b180 | 42 | |
daikinect | 0:d04469a1b180 | 43 | while(1) { |
daikinect | 0:d04469a1b180 | 44 | my_led = !my_led; |
daikinect | 0:d04469a1b180 | 45 | wait(0.5); |
daikinect | 0:d04469a1b180 | 46 | } |
daikinect | 0:d04469a1b180 | 47 | } |
daikinect | 0:d04469a1b180 | 48 |