Task 5.2.3 Solution

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 
00003 //Global PWM object
00004 PwmOut pwmRed(D7);
00005 
00006 int T = 100;    //100uS
00007 volatile int Tmark = 0; //0us
00008 volatile int delta = 1; //1us
00009 int n=0;
00010 
00011 //Timer
00012 Ticker t;
00013 
00014 //Function prototype 
00015 void doTwinkle();
00016 
00017 int main() {
00018     
00019     //Initial PWM state
00020     pwmRed.period_us(T);
00021     pwmRed.pulsewidth_us(Tmark);
00022     
00023     //Start timer
00024     t.attach(doTwinkle, 0.01);
00025     
00026     while(1) {
00027         sleep();
00028         
00029         //Update PWM
00030         pwmRed.pulsewidth_us(Tmark);
00031         
00032         //printf("Tmark = %d\n", Tmark);    //Debug
00033     }
00034 }
00035 
00036 //ISR for Timer
00037 void doTwinkle()
00038 {
00039     //Update n
00040     n++;
00041     
00042     //Calculate t 
00043     float t = (float)n / (float)T;
00044     float y = sin(2.0f*3.1415926f*t); //Range -1...+1
00045     Tmark = (int)(0.5f*(y+1.0f)*T);   //Range 0..T
00046 }