Task 5.2.3 Solution

Committer:
noutram
Date:
Fri Sep 20 13:43:13 2019 +0000
Revision:
2:1261bfd4b52d
Parent:
0:f3eff68b603f
2019

Who changed what in which revision?

UserRevisionLine numberNew contents of line
noutram 0:f3eff68b603f 1 #include "mbed.h"
noutram 0:f3eff68b603f 2
noutram 0:f3eff68b603f 3 //Global PWM object
noutram 2:1261bfd4b52d 4 #ifdef TARGET_NUCLEO_F429ZI
noutram 2:1261bfd4b52d 5 PwmOut pwmRed(D6); //D7 is not a PWM output on the F429, so use D6 instead
noutram 2:1261bfd4b52d 6 #else
noutram 0:f3eff68b603f 7 PwmOut pwmRed(D7);
noutram 2:1261bfd4b52d 8 #endif
noutram 0:f3eff68b603f 9
noutram 0:f3eff68b603f 10 int T = 100; //100uS
noutram 0:f3eff68b603f 11 volatile int Tmark = 0; //0us
noutram 0:f3eff68b603f 12 volatile int delta = 1; //1us
noutram 0:f3eff68b603f 13 int n=0;
noutram 0:f3eff68b603f 14
noutram 0:f3eff68b603f 15 //Timer
noutram 0:f3eff68b603f 16 Ticker t;
noutram 0:f3eff68b603f 17
noutram 0:f3eff68b603f 18 //Function prototype
noutram 0:f3eff68b603f 19 void doTwinkle();
noutram 0:f3eff68b603f 20
noutram 0:f3eff68b603f 21 int main() {
noutram 0:f3eff68b603f 22
noutram 0:f3eff68b603f 23 //Initial PWM state
noutram 0:f3eff68b603f 24 pwmRed.period_us(T);
noutram 0:f3eff68b603f 25 pwmRed.pulsewidth_us(Tmark);
noutram 0:f3eff68b603f 26
noutram 0:f3eff68b603f 27 //Start timer
noutram 0:f3eff68b603f 28 t.attach(doTwinkle, 0.01);
noutram 0:f3eff68b603f 29
noutram 0:f3eff68b603f 30 while(1) {
noutram 0:f3eff68b603f 31 sleep();
noutram 0:f3eff68b603f 32
noutram 0:f3eff68b603f 33 //Update PWM
noutram 0:f3eff68b603f 34 pwmRed.pulsewidth_us(Tmark);
noutram 0:f3eff68b603f 35
noutram 0:f3eff68b603f 36 //printf("Tmark = %d\n", Tmark); //Debug
noutram 0:f3eff68b603f 37 }
noutram 0:f3eff68b603f 38 }
noutram 0:f3eff68b603f 39
noutram 0:f3eff68b603f 40 //ISR for Timer
noutram 0:f3eff68b603f 41 void doTwinkle()
noutram 0:f3eff68b603f 42 {
noutram 0:f3eff68b603f 43 //Update n
noutram 0:f3eff68b603f 44 n++;
noutram 0:f3eff68b603f 45
noutram 0:f3eff68b603f 46 //Calculate t
noutram 0:f3eff68b603f 47 float t = (float)n / (float)T;
noutram 0:f3eff68b603f 48 float y = sin(2.0f*3.1415926f*t); //Range -1...+1
noutram 0:f3eff68b603f 49 Tmark = (int)(0.5f*(y+1.0f)*T); //Range 0..T
noutram 0:f3eff68b603f 50 }