Sine wave generation using dsPIC is a popular topic among engineers and hobbyists, because a clean sine wave is the heart of every pure sine wave inverter. In this article, we first look at what a dsPIC is and how it compares with PIC24 and STM32. Then we cover PWM, timers and the look-up table method. Finally, we build a working 50 Hz SPWM example step by step.

In this article
  • About dsPIC
  • dsPIC vs PIC24
  • dsPIC vs STM
  • Now, how to generate a sine wave using dsPIC?
  • SPWM look-up table
  • What is PLL
Advertisements

Working with electricity involves serious risk. Ensure you have the necessary skills and take proper safety precautions before attempting any electrical projects. Proceed at your own risk — the author assumes no responsibility for any damage, injury, or issues resulting from the use or misuse of the information provided.

All content on this website is original and protected by copyright. Please do not copy or reproduce content without permission. While most of the resources shared here are open-source and freely accessible for your learning and benefit, your respect for our intellectual effort is appreciated.

If you find our tutorials helpful, consider supporting us by purchasing related materials or sharing our work — it helps keep the content flowing.

Need help or have questions? Leave a comment below — the author is always happy to assist!

About dsPIC

dsPIC is Microchip’s family of digital signal controllers (DSCs). It is a 16-bit microcontroller with a built-in DSP engine. As a result, it suits signal processing and control work, such as motor control, power conversion and audio.

A dsPIC has one CPU, not two. The CPU is a 16-bit microcontroller core, and the DSP engine sits beside it. The DSP engine adds a single-cycle multiply-accumulate (MAC) unit, two 40-bit accumulators and a barrel shifter. These make filters, control loops and sine calculations fast.

At the same time, the device has all the usual microcontroller peripherals for general control tasks.

Key features of dsPIC devices include:

  • 16-bit CPU with a DSP engine (single-cycle MAC, two 40-bit accumulators)
  • Power-conversion peripherals: motor-control or high-resolution PWM, fast ADCs and comparators
  • Standard peripherals: timers, output compare, UART, SPI and I²C
  • CAN or CAN FD, and USB on selected devices
  • Speed: 40 MIPS (dsPIC33F), up to 70 MIPS (dsPIC33E) and up to 100 MIPS (dsPIC33C)

In short, a dsPIC is a flexible choice for any design that needs both fast maths and precise PWM.

Sine wave generation using dsPIC

There are similar devices on the market, but there are important differences. So let us compare them.

dsPIC vs PIC24

Both dsPIC and PIC24 come from Microchip, and they share the same 16-bit core, compiler (XC16) and most peripherals.

The main difference is the DSP engine. A dsPIC has it, while a PIC24 does not. In addition, many dsPIC33 devices add motor-control or power-supply PWM modules.

Sine wave generation using dsPIC – dsPIC vs PIC24Sine wave generation using dsPIC – dsPIC vs PIC24

A PIC24, on the other hand, is a general-purpose microcontroller. It suits control and data acquisition tasks that do not need heavy maths.

In practice, code written for a PIC24 often moves to a dsPIC with small changes, because the peripherals are very similar.

In summary, choose a dsPIC for signal processing, inverters and motor control. Choose a PIC24 for general control at a slightly lower cost.

dsPIC vs STM

dsPIC and STM32 come from two different makers: Microchip and STMicroelectronics.

As we saw above, a dsPIC is a 16-bit controller with a DSP engine, aimed at motor control, power conversion and signal processing.

STM32, by contrast, is STMicroelectronics’ family of 32-bit Arm Cortex-M microcontrollers. It covers almost every application, from simple control to industrial and automotive systems.

Several STM32 series, such as STM32F3, STM32F4 and STM32G4, use a Cortex-M4 core with DSP instructions and a floating-point unit. Some, such as the STM32F334 and STM32G474, also have a high-resolution timer (HRTIM) made for power conversion.

Sine wave generation using dsPIC – dsPIC vs STMSine wave generation using dsPIC – dsPIC vs STM

So the key difference is not “DSP or no DSP”. Both families can do DSP work. Instead, a dsPIC is a simpler 16-bit part with very mature motor-control and power-supply support, while an STM32 offers more speed, memory and peripherals in a 32-bit device.

In the end, both are good choices. The right one depends on your project, your tools and your experience.

This explains why dsPIC is still so popular for inverters and other signal generation work.

Now, how to generate a sine wave using dsPIC?

To generate a sine wave with a dsPIC, we use PWM. The PWM frequency stays fixed, but the duty cycle changes in a sine pattern. After a low-pass LC filter, the output becomes a smooth sine wave.

First, we set up a PWM output at a fixed frequency, for example 20 kHz. Then, at every PWM period, we load a new duty cycle value.

The easiest way to get these values is a look-up table. We calculate the sine values once, store them in an array and read them one by one in a timer interrupt.

Sine wave generation using dsPIC

Alternatively, you can use a dedicated sine wave generator IC. However, that adds cost and gives you less control.

Note that the quality of the sine wave depends on the PWM resolution, the number of samples per cycle and the output filter.

SPWM look-up table

An SPWM (sinusoidal pulse-width modulation) look-up table holds pre-calculated duty cycle values. When the PWM duty follows these values, the average output follows a sine wave. SPWM is used in inverters, UPS systems and motor drives.

The table usually lives in RAM or flash. In every PWM period, the code reads the next value and loads it into the duty cycle register.

You can calculate the values with a formula, a spreadsheet or an online tool. More samples per cycle give a smoother wave, but they use more memory.

To generate the SPWM look-up table use this

In short, an SPWM look-up table is simple to make. However, the values must be accurate, and the code must read them on time, every PWM period.

Before we write the code, let us look at two dsPIC features we need: the PLL and the timers.

What is PLL

A PLL (phase-locked loop) multiplies a low input frequency to produce a stable, higher clock frequency.

In a microcontroller, the PLL lets a slow crystal or internal oscillator run the CPU at full speed. For example, a dsPIC33FJ runs from its 7.37 MHz internal FRC oscillator at about 40 MIPS with the PLL.

PLLs are also used in radio, clock recovery and grid-tied inverters, where the inverter must lock to the mains phase.

PLL of dsPIC

For our project, the PLL simply gives the dsPIC a fast clock. As a result, the PWM has more resolution and the interrupt has more time to run.

Times of dsPIC

Like other microcontrollers, a dsPIC has several timers. They are used for:

  1. Timekeeping: measuring elapsed time or the time between two events.
  2. PWM time base: setting the period of the output compare PWM.
  3. Input capture and output compare: timing external events or triggering an output at a set count.
  4. Periodic interrupts: running code at a fixed rate.
  5. Real-time clock: Timer1 can run from a 32.768 kHz crystal.

The number of timers depends on the device. A typical dsPIC33 has:

  1. Timer1: a 16-bit timer that can also run asynchronously from a 32.768 kHz crystal.
  2. Timer2 and Timer3: 16-bit timers that you can join into one 32-bit timer.
  3. Timer4 and Timer5 (on larger devices): another 16-bit pair that can also form a 32-bit timer.
  4. Timer2 or Timer3 can be the time base for the output compare (OC) PWM.

Each timer has its own control, count and period registers. Which timer you use depends on your application and on the peripherals it must drive.

PWM generation with dsPIC

PWM (pulse-width modulation) produces a fixed-frequency signal with a variable duty cycle. A dsPIC can generate PWM in two ways. The simple way uses the output compare (OC) module with Timer2 or Timer3 as the time base. Motor-control dsPICs also have a dedicated PWM module with complementary outputs and dead time.

With the output compare module, the steps are:

  1. Set the timer period register (PR2) for the PWM frequency.
  2. Map the OC output to a pin with peripheral pin select (PPS).
  3. Select PWM mode in the OC control register and start the timer.
  4. Change the duty cycle by writing the OCxRS register. The new value loads at the start of the next period.

The exact register names differ slightly between dsPIC33F, dsPIC33E and dsPIC33C. Therefore, always check the datasheet and the family reference manual for your device.

For a sine output, we update the duty cycle from the look-up table in every PWM period.

In short, output compare PWM needs only a timer, a pin mapping and one register write per duty change.

Example code to generate PWM using dsPIC

The example below runs on a dsPIC33FJ128MC802 at 39.61 MIPS. It sets up a fixed 20 kHz PWM on OC1 with Timer2:

/* Fixed 50 % PWM on OC1 (RP2) - dsPIC33FJ128MC802, XC16
 * Use clock_init() and the #pragma config lines from the full SPWM example below.
 * Fcy = 39.61 MIPS, Timer2 1:1 -> PR2 = 1979 gives 20 kHz. */
#include <xc.h>
#include <stdint.h>

#define PWM_PERIOD  1979U

static void pwm_init(void)
{
    AD1PCFGL = 0xFFFF;           /* all pins digital */
    RPOR1bits.RP2R = 18;         /* OC1 -> RP2 */

    T2CON = 0;                   /* Timer2 off, Fcy clock, 1:1 prescale */
    TMR2  = 0;
    PR2   = PWM_PERIOD;

    OC1CON = 0;
    OC1R   = 0;
    OC1RS  = (PWM_PERIOD + 1U) / 2U;   /* 50 % duty */
    OC1CONbits.OCTSEL = 0;       /* Timer2 time base */
    OC1CONbits.OCM    = 0b110;   /* PWM mode, fault pin disabled */
    T2CONbits.TON = 1;
}

/* duty in 0.1 % steps (0 ... 1000) */
static void pwm_set_duty(uint16_t permille)
{
    if (permille > 1000U) permille = 1000U;
    OC1RS = (uint16_t)(((uint32_t)(PWM_PERIOD + 1U) * permille) / 1000U);
}

int main(void)
{
    /* clock_init(); */
    pwm_init();
    pwm_set_duty(500);
    while (1) { }
    return 0;
}

Here, Timer2 runs at Fcy with a 1:1 prescaler. Therefore, PR2 = 39.61 MHz / 20 kHz − 1 = 1979 gives 20 kHz, with about 11 bits of duty resolution. The function pwm_set_duty() takes the duty in 0.1 % steps.

Note that this is an example. Check the pin map of your device, because the OC1 output can go to any RPn pin. Also check the OC1 function code for PPS (18 on this device).

In addition, use the correct device header and configuration bit settings for your exact part.

Next, we need a timer interrupt that changes the duty cycle at every PWM period. This is the step that turns PWM into SPWM.

Timer interrupt code example with dsPIC

The following code adds the Timer2 interrupt. As a test, it ramps the duty cycle from 0 to 100 %:

/* Add to the PWM example: Timer2 interrupt once per PWM period (20 kHz).
 * Here it ramps the duty from 0 to 100 % every 49.5 ms (990 steps x 50 us). */
#include <xc.h>
#include <stdint.h>

#define PWM_PERIOD  1979U

static void pwm_irq_init(void)
{
    IPC1bits.T2IP = 5;           /* priority 5 */
    IFS0bits.T2IF = 0;           /* clear the flag before enabling */
    IEC0bits.T2IE = 1;
}

void __attribute__((__interrupt__, no_auto_psv)) _T2Interrupt(void)
{
    static uint16_t duty = 0;

    IFS0bits.T2IF = 0;
    duty += 2U;
    if (duty > PWM_PERIOD + 1U) {
        duty = 0;
    }
    OC1RS = duty;                /* loaded at the start of the next period */
}

Timer2 now interrupts once per PWM period, every 50 µs. Each time, the ISR raises the duty by 2 counts. As a result, the duty ramps from 0 to 100 % every 49.5 ms. You can watch this ramp on an oscilloscope.

Always clear the interrupt flag first in the ISR. Otherwise, the interrupt fires again as soon as it returns.

Also, keep the ISR short. At 20 kHz and 39.61 MIPS, you have about 1980 instruction cycles per period for everything.

Now we only need to replace the ramp with values from a sine table.

SPWM generation code example with dsPIC

Here is the complete code for a 50 Hz SPWM output with a dsPIC33FJ128MC802:

/*
 * 50 Hz SPWM on one Output Compare pin - dsPIC33FJ128MC802, XC16
 * Clock: internal FRC 7.37 MHz + PLL -> Fcy = 39.61 MIPS
 * PWM:   OC1 on RP2, Timer2 time base, 20 kHz
 * Sine:  400 samples per 50 Hz cycle, updated every PWM period in the Timer2 ISR
 * Check the #pragma config names, RPn pin and OC1 function code (18)
 * against your exact device datasheet before use.
 */
#include <xc.h>
#include <stdint.h>
#include <math.h>

#pragma config FNOSC = FRC        /* start on FRC, switch to FRC+PLL in software */
#pragma config FCKSM = CSECMD     /* clock switching on, fail-safe monitor off   */
#pragma config POSCMD = NONE
#pragma config OSCIOFNC = ON
#pragma config FWDTEN = OFF
#pragma config JTAGEN = OFF

#define FCY_HZ        39613750UL                  /* 7.37 MHz * 43 / (2*2) / 2     */
#define PWM_FREQ_HZ   20000UL
#define SINE_FREQ_HZ  50UL
#define PWM_PERIOD    ((uint16_t)(FCY_HZ / PWM_FREQ_HZ - 1UL))   /* = 1979 */
#define SINE_N        ((uint16_t)(PWM_FREQ_HZ / SINE_FREQ_HZ))   /* = 400  */
#define MOD_INDEX     0.90f                       /* keep below 1.0 (no overmodulation) */
#define PI_F          3.14159265f

static uint16_t sine_tab[SINE_N];
static volatile uint16_t sine_idx = 0;

static void clock_init(void)
{
    PLLFBD = 41;                     /* M  = 43 */
    CLKDIVbits.PLLPOST = 0;          /* N2 = 2  */
    CLKDIVbits.PLLPRE  = 0;          /* N1 = 2  */
    __builtin_write_OSCCONH(0x01);   /* new oscillator: FRC with PLL */
    __builtin_write_OSCCONL(OSCCON | 0x01);
    while (OSCCONbits.COSC != 0x01) { }
    while (OSCCONbits.LOCK != 1) { }
}

static void sine_table_init(void)
{
    uint16_t i;
    const float half = (float)(PWM_PERIOD + 1U) / 2.0f;
    for (i = 0; i < SINE_N; i++) {
        float s = sinf(2.0f * PI_F * (float)i / (float)SINE_N);
        sine_tab[i] = (uint16_t)(half * (1.0f + MOD_INDEX * s));   /* 99 ... 1881 */
    }
}

static void pwm_init(void)
{
    AD1PCFGL = 0xFFFF;               /* all pins digital */
    RPOR1bits.RP2R = 18;             /* OC1 -> RP2 */

    T2CON = 0;                       /* Timer2 off, Fcy clock, 1:1 prescale */
    TMR2  = 0;
    PR2   = PWM_PERIOD;

    OC1CON = 0;
    OC1R   = sine_tab[0];
    OC1RS  = sine_tab[0];
    OC1CONbits.OCTSEL = 0;           /* Timer2 time base */
    OC1CONbits.OCM    = 0b110;       /* PWM mode, fault pin disabled */

    IPC1bits.T2IP = 5;
    IFS0bits.T2IF = 0;
    IEC0bits.T2IE = 1;               /* one interrupt per PWM period */
    T2CONbits.TON = 1;
}

/* Runs at 20 kHz: about 1980 instruction cycles available per call */
void __attribute__((__interrupt__, no_auto_psv)) _T2Interrupt(void)
{
    IFS0bits.T2IF = 0;
    OC1RS = sine_tab[sine_idx];      /* loaded at the start of the next period */
    if (++sine_idx >= SINE_N) {
        sine_idx = 0;
    }
}

int main(void)
{
    clock_init();
    sine_table_init();
    pwm_init();
    while (1) {
        /* free for ADC, protection and UI tasks */
    }
    return 0;
}

The table holds 400 samples, because 20 kHz / 50 Hz = 400. With a modulation index of 0.9, the duty swings between 99 and 1881 counts around the mid-point. Filter the OC1 output with a low-pass filter. For a quick test, an RC filter of 1 kΩ and 1 µF works. For a real inverter, however, you need a full H-bridge with dead time, so use the motor-control PWM module and an LC filter.

You may read other articles:

End

I hope this article helps you generate SPWM with a dsPIC. In a later article, I will show how to build a complete sine wave inverter with a dsPIC. If you need help with your own inverter or dsPIC project, contact us on WhatsApp.

Liked this article? Subscribe to our newsletter:

Loading

or,

Visit LabProjectsBD.com for more inspiring projects and tutorials.

Thank you!

The first draft of this article was written with the help of ChatGPT. Its text and code have since been reviewed and corrected.

Have a project in mind? LabProjectsBD designs power electronics, embedded firmware, IoT devices and production-ready PCBs for clients. Message us on WhatsApp, use the contact form, or see our services and portfolio.


MKDas

Mithun K. Das. B.Sc. in Electrical and Electronic Engineering (EEE) from KUET. Senior Embedded Systems Designer at a leading international company. Welcome to my personal blog! I share articles on various electronics topics, breaking them down into simple and easy-to-understand explanations, especially for beginners. My goal is to make learning electronics accessible and enjoyable for everyone. If you have any questions or need further assistance, feel free to reach out through the Contact Us page. Thank you for visiting, and happy learning!

8 Comments

Ajape · 29/01/2023 at 2:12 am

Thank you for this new articles on dspic spwm sir. Pls. We still need more help on how to include feedback, and pls again write articles on how to use this spwm to charge batteries. Thanks.

    MKDas · 29/01/2023 at 2:28 pm

    buck-boost switching.

Osman · 05/05/2023 at 10:31 pm

Hi sir,
I reviewed the content you prepared and amazing. I’m a graduate student and I’m working on spwm in my thesis. Some of the dspic spwm code you shared at the end of the article is not visible. Could you please send me the code to use in my research?

    MKDas · 06/05/2023 at 12:41 pm

    sorry for that missing. added it. you can check it now.

Dan · 15/05/2024 at 2:39 pm

Hi! In the ISR, why is TMR3H used? and what register is that exactly? I cant find it in the datasheet.

Right now, the code uses RP2 as the output pin for the PWM, but what if you want to drive 4 mosfets, 2 legs. You only need to invert the RP2 output? How the code would change in that case?

Thanks!

    MKDas · 16/05/2024 at 1:56 pm

    based on the MCU, it differs a bit.

codemaster11 · 05/12/2024 at 11:01 pm

the code used for feedback have variable “fb_constant = 0.8” i didn’t understand
how you select 0.8 why not 0.9 or 0.7 how it is changing duty cycle?

also need a little explanation how output is regulating with below code lines here.

if(output<100)
{
if(fb_constant115)
{
if(fb_constant>0.5)fb_constant-=0.1;
}

    MKDas · 06/12/2024 at 12:17 pm

    that is a way to correct the output. you need to create a feedback circuit and give it to ADC pin then calculate for that FB_constant. So it can adjust the output voltage automatically

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *