Select Page

PWM Examples

Configuring GPIO pin for PWM

In using PWM, we must configure the GPIO pins for PWM output. In this regard, it is same as all other peripherals. The steps are as follows:

  1. Enable the clock to GPIO pin by using RCGCGPIO.
  2. Set the GPIOAFSEL (GPIO alternate function) for PWM output pins.
  3. Enable digital pins in the GPIODEN (GPIO Digital enable) register.
  4. Assign the PWM signals to specific pins using GPIOCTL register (See Tables 16.1 through 16.4).

Configuring PWM generator to create pulses

After the GPIO configuration, we need to take the following steps to configure the PWM:

  1. Disable the generator using PWM×CTL register.
  2. Configure PWM×GENA (or PWM×GENB).
  3. Load the value into PWM×LOAD register to set the desired output frequency.
  4. Load the value into PWM×CMPA (or PWMxCMPB) register to set the desired duty cycle.
  5. Start the PWM generator using PWMxCTL.
  6. Configure PWM×ENABLE register to direct the PWMx to output pin.

Source Code

  1. /* Use PWM to control LED intensity */
  2. 
    
  3. /* In the infinite loop, the value of CMPA register is decremented
  4.  * by 100 every 20 ms. The decreasing CMPA value causes the duty cycle
  5.  * to lengthen.
  6. */
  7. 
    
  8. #include <stdint.h>
  9. #include "inc/tm4c123gh6pm.h"
  10. 
    
  11. void delayMs(int n);
  12. 
    
  13. int main(void)
  14. {
  15.     int x = 15999;
  16. 
    
  17.     /* Enable Peripheral Clocks */
  18.     SYSCTL_RCGCPWM_R |= 2;       /* enable clock to PWM1 */
  19.     SYSCTL_RCGCGPIO_R |= 0x20;   /* enable clock to PORTF */
  20.     SYSCTL_RCC_R &= ~0x00100000; /* no pre-divide for PWM clock */
  21. 
    
  22.     /* Enable port PF3 for PWM1 M1PWM7 */
  23.     GPIO_PORTF_AFSEL_R = 8;      /* PF3 uses alternate function */
  24.     GPIO_PORTF_PCTL_R &= ~0x0000F000; /* make PF3 PWM output pin */
  25.     GPIO_PORTF_PCTL_R |= 0x00005000;
  26.     GPIO_PORTF_DEN_R |= 8;       /* pin digital */
  27. 
    
  28.     PWM1_3_CTL_R = 0;            /* stop counter */
  29.     PWM1_3_GENB_R = 0x0000008C;  /* M1PWM7 output set when reload, */
  30.                                  /* clear when match PWMCMPA */
  31.     PWM1_3_LOAD_R = 16000;       /* set load value for 1kHz (16MHz/16000) */
  32.     PWM1_3_CMPA_R = 15999;       /* set duty cycle to min */
  33.     PWM1_3_CTL_R = 1;            /* start timer */
  34.     PWM1_ENABLE_R = 0x80;        /* start PWM1 ch7 */
  35. 
    
  36.     for(;;) {
  37.         x = x - 100;
  38. 
    
  39.         if (x <= 0)
  40.             x = 16000;
  41. 
    
  42.         PWM1_3_CMPA_R = x;
  43. 
    
  44.         delayMs(20);
  45.     }
  46. }
  47. 
    
  48. 
    
  49. /* delay n milliseconds (16 MHz CPU clock) */
  50. void delayMs(int n)
  51. {
  52.     int i, j;
  53. 
    
  54.     for(i = 0 ; i < n; i++)
  55.         for(j = 0; j < 3180; j++)
  56.             {}  /* do nothing for 1 ms */
  57. }