Sine from PWM dutycycle modulation

Dependencies:   mbed

Files at this revision

API Documentation at this revision

Comitter:
wim
Date:
Tue Feb 18 20:08:15 2014 +0000
Commit message:
PWM SINE Test;

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r d274003b52e7 main.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Tue Feb 18 20:08:15 2014 +0000
@@ -0,0 +1,60 @@
+#include "mbed.h"
+
+//Number of dutycycle steps for output wave
+#define SINE_STEPS        32
+//Frequency of output sine in Hz
+#define SINE_OUT_FREQ     1000
+
+//Constants to compute the sine waveform
+#define PI                 3.141592f
+#define SINE_STEPS_RAD    (2.0f * PI / (float)SINE_STEPS)
+
+//Table to generate the sine waveform using dutycycles
+float sine_duty[SINE_STEPS];
+
+
+//Frequency of Pulse Width Modulated signal in Hz
+#define PWM_FREQ          200000
+
+//PWM pin
+PwmOut PwmPin (p22);
+
+//Heartbeat LED
+DigitalOut myled(LED1);
+
+
+//Ticker to update the PWM dutycycle
+Ticker pwm_ticker;
+
+//Ticker calls this fucntion to update the PWM dutycycle
+void pwm_duty_updater() {
+  static int idx=0;
+  
+  PwmPin.write(sine_duty[idx]);  // Set the dutycycle % to next value in array
+  idx++;                         // Increment the idx
+  if (idx == SINE_STEPS) idx=0;  // Reset the idx when teh end has been reached  
+
+}
+  
+int main() {
+  int i;
+  
+  // Init the duty cycle array
+  for (i=0; i<SINE_STEPS; i++) {
+    sine_duty[i] = ( sin(i * SINE_STEPS_RAD) + 1.0f ) / 2.0f;  // convert sine (-1.0 .. +1.0) into dutycycle (0.0 .. 1.0)
+  }  
+    
+  // Set PWM frequency to 200 KHz (period = 5 us)
+  PwmPin.period( 1.0f / (float) PWM_FREQ);
+
+  // Init the Ticker to call the dutycyle updater at the required interval
+  // The update should be at (SINE_STEPS * SINE_OUT_FREQ) 
+  pwm_ticker.attach(&pwm_duty_updater, 1.0f / (float)(SINE_STEPS * SINE_OUT_FREQ));
+
+  while(1){ //infinite loop
+    myled = !myled; 
+    wait(0.5);  
+  }
+       
+} 
+
diff -r 000000000000 -r d274003b52e7 mbed.bld
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Tue Feb 18 20:08:15 2014 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/a9913a65894f
\ No newline at end of file