Basic PWM Control in Digital Port that does not have PWM function. I use the RGB LED on board.
Dependencies: mbed
main.cpp@0:c7e6fec3dbe9, 2014-08-07 (annotated)
- Committer:
- NghiaJenius
- Date:
- Thu Aug 07 12:20:10 2014 +0000
- Revision:
- 0:c7e6fec3dbe9
Publish Code;
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
NghiaJenius | 0:c7e6fec3dbe9 | 1 | #include "mbed.h" |
NghiaJenius | 0:c7e6fec3dbe9 | 2 | //Basic PWM Led Control In Digital Port |
NghiaJenius | 0:c7e6fec3dbe9 | 3 | |
NghiaJenius | 0:c7e6fec3dbe9 | 4 | //DigitalOut RLED(PTB22); |
NghiaJenius | 0:c7e6fec3dbe9 | 5 | //DigitalOut GLED(PTE26); |
NghiaJenius | 0:c7e6fec3dbe9 | 6 | DigitalOut BLED(PTB21); |
NghiaJenius | 0:c7e6fec3dbe9 | 7 | float period=0.01;//Config. Period of PWM |
NghiaJenius | 0:c7e6fec3dbe9 | 8 | float t_on; |
NghiaJenius | 0:c7e6fec3dbe9 | 9 | float t_off; |
NghiaJenius | 0:c7e6fec3dbe9 | 10 | double duty=0; //Duty Cycle (%) |
NghiaJenius | 0:c7e6fec3dbe9 | 11 | unsigned int count=0; |
NghiaJenius | 0:c7e6fec3dbe9 | 12 | |
NghiaJenius | 0:c7e6fec3dbe9 | 13 | int main() |
NghiaJenius | 0:c7e6fec3dbe9 | 14 | { |
NghiaJenius | 0:c7e6fec3dbe9 | 15 | BLED=0; |
NghiaJenius | 0:c7e6fec3dbe9 | 16 | //Calculate on and off time |
NghiaJenius | 0:c7e6fec3dbe9 | 17 | t_on= period*duty; |
NghiaJenius | 0:c7e6fec3dbe9 | 18 | t_off= period - t_on; |
NghiaJenius | 0:c7e6fec3dbe9 | 19 | |
NghiaJenius | 0:c7e6fec3dbe9 | 20 | while (true) |
NghiaJenius | 0:c7e6fec3dbe9 | 21 | { |
NghiaJenius | 0:c7e6fec3dbe9 | 22 | if(count<=2)//Time between changes in brightness = count*period |
NghiaJenius | 0:c7e6fec3dbe9 | 23 | count++; |
NghiaJenius | 0:c7e6fec3dbe9 | 24 | else |
NghiaJenius | 0:c7e6fec3dbe9 | 25 | { |
NghiaJenius | 0:c7e6fec3dbe9 | 26 | count=0; |
NghiaJenius | 0:c7e6fec3dbe9 | 27 | if(duty<1) |
NghiaJenius | 0:c7e6fec3dbe9 | 28 | duty+=0.01;//Adjust dimming speed |
NghiaJenius | 0:c7e6fec3dbe9 | 29 | else |
NghiaJenius | 0:c7e6fec3dbe9 | 30 | { |
NghiaJenius | 0:c7e6fec3dbe9 | 31 | duty=0; |
NghiaJenius | 0:c7e6fec3dbe9 | 32 | } |
NghiaJenius | 0:c7e6fec3dbe9 | 33 | t_on= period*duty; |
NghiaJenius | 0:c7e6fec3dbe9 | 34 | t_off= period - t_on; |
NghiaJenius | 0:c7e6fec3dbe9 | 35 | } |
NghiaJenius | 0:c7e6fec3dbe9 | 36 | //LED control |
NghiaJenius | 0:c7e6fec3dbe9 | 37 | wait(t_on); |
NghiaJenius | 0:c7e6fec3dbe9 | 38 | BLED=1; |
NghiaJenius | 0:c7e6fec3dbe9 | 39 | |
NghiaJenius | 0:c7e6fec3dbe9 | 40 | wait(t_off); |
NghiaJenius | 0:c7e6fec3dbe9 | 41 | BLED=0; |
NghiaJenius | 0:c7e6fec3dbe9 | 42 | } |
NghiaJenius | 0:c7e6fec3dbe9 | 43 | |
NghiaJenius | 0:c7e6fec3dbe9 | 44 | } |