This component of code shows how to use a sawtooth to generate a PWM signal. The example compares a sinewave to a triangle waveform. The PWM signal generated is the output of the comparator.
This code has been designed to run in a single-cycle timed loop, but also contains a clock deriver that allows the code to run at an integer fraction of the base clock frequency (defined by the "Divisor" control). There is also a boolean to reset the clock deriver. The following images shows an example of the PWM generator being used with a 5kHz sinewave as well as the block diagram to go with it. The attached files include the PWM generator block itself as well as an example of its use in a single-cycle timed loop.
If a DC signal is fed to the comparator, the output is a PWM signal with a constant duty cycle that is equal to the ratio of the DC signal to the peak value of the triangle wave. If some other analog waveform is sent to the comparator, the PWM output varies to correspond to the analog waveform.
This code could be extended to a different version of a PWM generator by replacing the triangle wave with various versions of a sawtooth look-up table.
NOTE: the test code in "TriangleWavePWMGen test.vi" is to demonstrate the behavior of the block on a Windows-based system. It won't directly compile to FPGA without some changes. However, the code in "simple FPGA test.vi" will compile and will generate an indicator that cycles through the PWM range at 0.5Hz.
Steps to Execute Code
LabVIEW Development Environment
Open the TrianglePWM.lvproj file
Open the TriangleWavePWMGenTest.vi
Run the VI
Notice that the correct PWM wave being generated from the two signals on the top plot.
Update the FPGA target to match your configuration
Compile and run the Simple FPGA Test.vi
LabVIEW 2010 FPGA Module "or compatible"
Additional Information or References
**This document has been updated to meet the current required format for the NI Code Exchange. For more details visit this discussion thread**
Example code from the Example Code Exchange in the NI Community is licensed with the MIT license.