Nicholas Outram
/
Task524Solution
Task 5.2.3 Solution
main.cpp@0:f3eff68b603f, 2015-09-24 (annotated)
- Committer:
- noutram
- Date:
- Thu Sep 24 12:32:02 2015 +0000
- Revision:
- 0:f3eff68b603f
Initial version 24-09-2015
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
noutram | 0:f3eff68b603f | 1 | #include "mbed.h" |
noutram | 0:f3eff68b603f | 2 | |
noutram | 0:f3eff68b603f | 3 | //Global PWM object |
noutram | 0:f3eff68b603f | 4 | PwmOut pwmRed(D7); |
noutram | 0:f3eff68b603f | 5 | |
noutram | 0:f3eff68b603f | 6 | int T = 100; //100uS |
noutram | 0:f3eff68b603f | 7 | volatile int Tmark = 0; //0us |
noutram | 0:f3eff68b603f | 8 | volatile int delta = 1; //1us |
noutram | 0:f3eff68b603f | 9 | int n=0; |
noutram | 0:f3eff68b603f | 10 | |
noutram | 0:f3eff68b603f | 11 | //Timer |
noutram | 0:f3eff68b603f | 12 | Ticker t; |
noutram | 0:f3eff68b603f | 13 | |
noutram | 0:f3eff68b603f | 14 | //Function prototype |
noutram | 0:f3eff68b603f | 15 | void doTwinkle(); |
noutram | 0:f3eff68b603f | 16 | |
noutram | 0:f3eff68b603f | 17 | int main() { |
noutram | 0:f3eff68b603f | 18 | |
noutram | 0:f3eff68b603f | 19 | //Initial PWM state |
noutram | 0:f3eff68b603f | 20 | pwmRed.period_us(T); |
noutram | 0:f3eff68b603f | 21 | pwmRed.pulsewidth_us(Tmark); |
noutram | 0:f3eff68b603f | 22 | |
noutram | 0:f3eff68b603f | 23 | //Start timer |
noutram | 0:f3eff68b603f | 24 | t.attach(doTwinkle, 0.01); |
noutram | 0:f3eff68b603f | 25 | |
noutram | 0:f3eff68b603f | 26 | while(1) { |
noutram | 0:f3eff68b603f | 27 | sleep(); |
noutram | 0:f3eff68b603f | 28 | |
noutram | 0:f3eff68b603f | 29 | //Update PWM |
noutram | 0:f3eff68b603f | 30 | pwmRed.pulsewidth_us(Tmark); |
noutram | 0:f3eff68b603f | 31 | |
noutram | 0:f3eff68b603f | 32 | //printf("Tmark = %d\n", Tmark); //Debug |
noutram | 0:f3eff68b603f | 33 | } |
noutram | 0:f3eff68b603f | 34 | } |
noutram | 0:f3eff68b603f | 35 | |
noutram | 0:f3eff68b603f | 36 | //ISR for Timer |
noutram | 0:f3eff68b603f | 37 | void doTwinkle() |
noutram | 0:f3eff68b603f | 38 | { |
noutram | 0:f3eff68b603f | 39 | //Update n |
noutram | 0:f3eff68b603f | 40 | n++; |
noutram | 0:f3eff68b603f | 41 | |
noutram | 0:f3eff68b603f | 42 | //Calculate t |
noutram | 0:f3eff68b603f | 43 | float t = (float)n / (float)T; |
noutram | 0:f3eff68b603f | 44 | float y = sin(2.0f*3.1415926f*t); //Range -1...+1 |
noutram | 0:f3eff68b603f | 45 | Tmark = (int)(0.5f*(y+1.0f)*T); //Range 0..T |
noutram | 0:f3eff68b603f | 46 | } |