PWM to Generate Analog Waveforms

The PWM outputs may be used to generate low frequency analog waveforms by modulating the dutycycle of a higher frequency digital square wave signal. This is the technique used to generate three phase sinewaves for a variable frequency motordrive. You can do this as follows to generate a 1 KHz sine wave:

  1. Declare a float array of something like 32 entries.
  2. Fill the array with sine values between 0 and 2pi in 32 equal steps. The sine values will be between -1.0 and 1.0 scale these sine values to match the duty cycle values needed for PWM to a range of 0.0 through 1.0 This may be done by val = (sine + 1.0) / 2.0
  3. In your main set up a PWM pin with period to match the desired 200Khz
  4. in your main set up a Ticker with a rate of 32x the desired low-freq signal of 1Khz
  5. Attach the Ticker to a function that sets the duty cycle using the next entry in the sine table, increment the index for the table and reset it to 0 when it becomes 32
  6. In your main you can now run an idle loop or do something useful. The main code will be interrupted at regular intervals to generate the sine.

You need a low-pass filter on the PWM output to get a smooth sine. Note that the sinewave voltage is between 0 and 3.3V. You may use an OpAmp or a simple capacitor to shift the avarage level up or down for example to create a sine with negative and positive amplitudes.

Here is example code:

Import programSineFromPWM

Sine from PWM dutycycle modulation

The output looks like this:

/media/uploads/wim/screenshot_pwm_sine.jpg You can see the dutycyle variation 0..1..0 and it is repeated at 1 ms (1 KHz)

The carrierwave is 200KHz /media/uploads/wim/screenshot_pwm_sine2.jpg

You could generate other waveforms by changing the values in the dutycyle array. The frequency can be changed by modifying the Ticker rate. Multiple Phase shifted outputs can be generated by using multiple arrays or by adding a phase offset to the arrayindex of an output.


1 comment on PWM to Generate Analog Waveforms :

15 Jun 2016

Hi, can I ask a sample code to input a digital filter on PWM?

Please log in to post comments.