Output a PWM signal on any IO using Timeout.

Dependencies:   mbed

Committer:
arostm
Date:
Wed Jun 07 13:32:38 2017 +0000
Revision:
1:5f0c04279fb9
Adding new mbed library

Who changed what in which revision?

UserRevisionLine numberNew contents of line
bcostm 0:8d83d0909665 1 #include "mbed.h"
bcostm 0:8d83d0909665 2
bcostm 0:8d83d0909665 3 Timeout timer;
bcostm 0:8d83d0909665 4 DigitalOut my_led(LED1);
bcostm 0:8d83d0909665 5 DigitalOut my_pwm(D10); // IO used by pwm_io function
bcostm 0:8d83d0909665 6
bcostm 0:8d83d0909665 7 int on_delay = 0;
bcostm 0:8d83d0909665 8 int off_delay = 0;
bcostm 0:8d83d0909665 9
bcostm 0:8d83d0909665 10 void toggleOff(void);
bcostm 0:8d83d0909665 11
bcostm 0:8d83d0909665 12 void toggleOn(void) {
bcostm 0:8d83d0909665 13 my_pwm = 1;
bcostm 0:8d83d0909665 14 timer.attach_us(toggleOff, on_delay);
bcostm 0:8d83d0909665 15 }
bcostm 0:8d83d0909665 16
bcostm 0:8d83d0909665 17 void toggleOff(void) {
bcostm 0:8d83d0909665 18 my_pwm = 0;
bcostm 0:8d83d0909665 19 timer.attach_us(toggleOn, off_delay);
bcostm 0:8d83d0909665 20 }
bcostm 0:8d83d0909665 21
bcostm 0:8d83d0909665 22 // p_us = signal period in micro_seconds
bcostm 0:8d83d0909665 23 // dc = signal duty-cycle (0.0 to 1.0)
bcostm 0:8d83d0909665 24 void pwm_io(int p_us, float dc) {
bcostm 0:8d83d0909665 25 timer.detach();
bcostm 0:8d83d0909665 26 if ((p_us == 0) || (dc == 0)) {
bcostm 0:8d83d0909665 27 my_pwm = 0;
bcostm 0:8d83d0909665 28 return;
bcostm 0:8d83d0909665 29 }
bcostm 0:8d83d0909665 30 if (dc >= 1) {
bcostm 0:8d83d0909665 31 my_pwm = 1;
bcostm 0:8d83d0909665 32 return;
bcostm 0:8d83d0909665 33 }
bcostm 0:8d83d0909665 34 on_delay = (int)(p_us * dc);
bcostm 0:8d83d0909665 35 off_delay = p_us - on_delay;
bcostm 0:8d83d0909665 36 toggleOn();
bcostm 0:8d83d0909665 37 }
bcostm 0:8d83d0909665 38
bcostm 0:8d83d0909665 39 int main() {
bcostm 0:8d83d0909665 40
bcostm 0:8d83d0909665 41 pwm_io(20000, 0.25); // 20ms - 25%
bcostm 0:8d83d0909665 42
bcostm 0:8d83d0909665 43 while(1) {
bcostm 0:8d83d0909665 44 my_led = !my_led;
bcostm 0:8d83d0909665 45 wait(0.5);
bcostm 0:8d83d0909665 46 }
bcostm 0:8d83d0909665 47 }
bcostm 0:8d83d0909665 48