How to write a C Program Pulse Width Modulation in C Programming Language ?
This C Program Pulse Width Modulation.
Description: This code controls a servo using PWM via Timer A. Three external buttons are used to change the servo's position. Button 0 rotates the servo CCW in 5ms increments. Button 1 rotates the servo to its center position. Button 2 rotates the servo CW in 5ms increments.
Solution:
- #include <msp430.h>
- /*
- * main.c
- *Pulse Width Modulation
- *
- * Description:
- * This code controls a servo using PWM via Timer A. Three external buttons are used to change
- * the servo's position. Button 0 rotates the servo CCW in 5ms increments. Button 1 rotates
- * the servo to its center position. Button 2 rotates the servo CW in 5ms increments.
- *
- */
- #define ms_20 655 // 20.0 ms
- int PositionIndex = 6;
- int main(void)
- {
- WDTCTL = WDTPW + WDTHOLD; // Stop WDT
- P1DIR |= BIT2; // P1.2 output
- P2IE |= BIT0 + BIT1 + BIT2; // Interrupt enabled for external buttons
- P2IES &= ~(BIT0 + BIT1 + BIT2); // Interrupt low to high enable
- P2IFG &= ~(BIT0 + BIT1 + BIT2); // IFG clear
- // Using P1.2 for hardware set/reset as when TAR hits CCRO and CCR1 values.
- // This allows P1.2 to toggle outside of software control. Note that Timer A
- // is running compare mode but interrupts are not being utilized.
- // Note that this feature of toggling port bits outside of software control
- // may be utilized while cpu is in low power mode.
- P1SEL |= BIT2; // P1.2 TA1/2 options
- // Setting CCR0 for a 20 ms period with CCTL1 determining pulse width (duty
- // cycle) as determined by OUTMOD_7.
- CCR0 = ms_20 - 1; // PWM Period of 20 ms
- CCTL1 = OUTMOD_7; // CCR1 reset/set
- TACTL = TASSEL_1 + MC_1; // ACLK, up mode
- _enable_interrupt();
- while(1);
- }
- #pragma vector=PORT2_VECTOR
- __interrupt void Port_2(void)
- {
- // if statement determines when rotated to the max position (CW or CCW)
- if(PositionIndex > 11){
- PositionIndex = 11;
- }
- else if(PositionIndex < 1){
- PositionIndex = 1;
- }
- else{
- }
- // if statement controls the servo based on button press
- if((P2IFG & BIT0) == BIT0){
- PositionIndex--;
- P2IFG &= ~BIT0;
- }
- else if((P2IFG & BIT2) == BIT2){
- PositionIndex++;
- P2IFG &= ~BIT2;
- }
- else{
- PositionIndex = 6;
- P2IFG &= ~BIT1;
- }
- CCR1 = (PositionIndex*5) + 20; // update servo's position based on PositionIndex value
- }