min ji Kim
/
Nucleo_digtal_pwm
Make PWM pulse use digital output with Timer
main.cpp@0:eb891a3bc014, 2016-01-27 (annotated)
- Committer:
- Kmj
- Date:
- Wed Jan 27 04:55:43 2016 +0000
- Revision:
- 0:eb891a3bc014
This is remake version of Nucleo_pwm3.
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
Kmj | 0:eb891a3bc014 | 1 | #include "mbed.h" |
Kmj | 0:eb891a3bc014 | 2 | |
Kmj | 0:eb891a3bc014 | 3 | Timeout timer; |
Kmj | 0:eb891a3bc014 | 4 | InterruptIn my_button(USER_BUTTON); |
Kmj | 0:eb891a3bc014 | 5 | DigitalOut my_pwm(LED1); // IO used by pwm_io function |
Kmj | 0:eb891a3bc014 | 6 | |
Kmj | 0:eb891a3bc014 | 7 | int on_delay = 0; |
Kmj | 0:eb891a3bc014 | 8 | int off_delay = 0; |
Kmj | 0:eb891a3bc014 | 9 | float duty[5]={0.2f,0.4f,0.6f,0.8f,1.0f}; |
Kmj | 0:eb891a3bc014 | 10 | int i=0; |
Kmj | 0:eb891a3bc014 | 11 | void toggleOff(void); |
Kmj | 0:eb891a3bc014 | 12 | |
Kmj | 0:eb891a3bc014 | 13 | void toggleOn(void) { |
Kmj | 0:eb891a3bc014 | 14 | my_pwm = 1; |
Kmj | 0:eb891a3bc014 | 15 | timer.attach_us(toggleOff, on_delay); |
Kmj | 0:eb891a3bc014 | 16 | } |
Kmj | 0:eb891a3bc014 | 17 | |
Kmj | 0:eb891a3bc014 | 18 | void toggleOff(void) { |
Kmj | 0:eb891a3bc014 | 19 | my_pwm = 0; |
Kmj | 0:eb891a3bc014 | 20 | timer.attach_us(toggleOn, off_delay); |
Kmj | 0:eb891a3bc014 | 21 | } |
Kmj | 0:eb891a3bc014 | 22 | |
Kmj | 0:eb891a3bc014 | 23 | // p_us = signal period in micro_seconds |
Kmj | 0:eb891a3bc014 | 24 | // dc = signal duty-cycle (0.0 to 1.0) |
Kmj | 0:eb891a3bc014 | 25 | void pwm_io(int p_us, float dc) { |
Kmj | 0:eb891a3bc014 | 26 | timer.detach(); |
Kmj | 0:eb891a3bc014 | 27 | if ((p_us == 0) || (dc == 0)) { |
Kmj | 0:eb891a3bc014 | 28 | my_pwm = 0; |
Kmj | 0:eb891a3bc014 | 29 | return; |
Kmj | 0:eb891a3bc014 | 30 | } |
Kmj | 0:eb891a3bc014 | 31 | if (dc >= 1) { |
Kmj | 0:eb891a3bc014 | 32 | my_pwm = 1; |
Kmj | 0:eb891a3bc014 | 33 | return; |
Kmj | 0:eb891a3bc014 | 34 | } |
Kmj | 0:eb891a3bc014 | 35 | on_delay = (int)(p_us * dc); |
Kmj | 0:eb891a3bc014 | 36 | off_delay = p_us - on_delay; |
Kmj | 0:eb891a3bc014 | 37 | toggleOn(); |
Kmj | 0:eb891a3bc014 | 38 | } |
Kmj | 0:eb891a3bc014 | 39 | void pressed() |
Kmj | 0:eb891a3bc014 | 40 | { if(i>=5) |
Kmj | 0:eb891a3bc014 | 41 | i=0; |
Kmj | 0:eb891a3bc014 | 42 | |
Kmj | 0:eb891a3bc014 | 43 | pwm_io(20000,duty[i]); |
Kmj | 0:eb891a3bc014 | 44 | i++; |
Kmj | 0:eb891a3bc014 | 45 | } |
Kmj | 0:eb891a3bc014 | 46 | |
Kmj | 0:eb891a3bc014 | 47 | int main() { |
Kmj | 0:eb891a3bc014 | 48 | my_button.fall(&pressed); |
Kmj | 0:eb891a3bc014 | 49 | pwm_io(20000, 0.25); // 20ms - 25% |
Kmj | 0:eb891a3bc014 | 50 | |
Kmj | 0:eb891a3bc014 | 51 | while(1) { |
Kmj | 0:eb891a3bc014 | 52 | |
Kmj | 0:eb891a3bc014 | 53 | } |
Kmj | 0:eb891a3bc014 | 54 | } |
Kmj | 0:eb891a3bc014 | 55 |