PWM runtime update issue

, Oct 22, 2024|
0
13
0
Hi,

I am using MS51PC0AE mcu for pwm code and i want to change duty cycle at run time but in my harware code in not working
propely can you guide me how to solve this issue ,second this i can send data from Uart also 


my code :

#include "MS51_32K.h"  // Include header for MS51 microcontroller

// Function to set the PWM duty cycle dynamically
void setPWMDutyCycle(unsigned int dutyPercent) {
    unsigned int dutyValue;
    unsigned int periodValue = 0x03FF;  // Assume a period of 1023 cycles

    // Ensure the duty cycle percentage is between 0 and 100
    if (dutyPercent > 100) dutyPercent = 100;

    // Calculate the actual duty cycle value based on the percentage
    dutyValue = (dutyPercent * periodValue) / 100;

    // Update the duty cycle registers for the PWM channels
    PWM1C0H = (dutyValue >> 8) & 0xFF;  // High byte of duty cycle for PWM1 CH0
    PWM1C0L = dutyValue & 0xFF;         // Low byte of duty cycle for PWM1 CH0

    PWM1C1H = (dutyValue >> 8) & 0xFF;  // High byte of duty cycle for PWM1 CH1
    PWM1C1L = dutyValue & 0xFF;         // Low byte of duty cycle for PWM1 CH1

    // Load the new values
    set_PWM1CON0_LOAD;
}

// Simple delay function
void delay(int ms) {
    int i, j;
    for(i = 0; i < ms; i++)
        for(j = 0; j < 1275; j++);
}

int duty = 0;

void main(void) {
    // Initial PWM setup
    PWM0_ClockSource(PWM_FSYS, 8);  // Set PWM0 clock source
    ENABLE_PWM0_CH0_P12_OUTPUT;     // Enable PWM output on P1.2 (channel 0)
    P12_PUSHPULL_MODE;              // Set P1.2 to push-pull mode
    // Enable PWM channels and set the period
    PWM1PH = 0x03;  // Set PWM period high byte (e.g., 1023 cycles)
    PWM1PL = 0xFF;  // Set PWM period low byte
    // Start PWM
    set_PWM1CON0_PWMRUN;
    // Set initial duty cycle to 1%
    setPWMDutyCycle(1);

    // Main loop to change duty cycle at runtime
    while (1) {
ENABLE_PWM0_CH0_P12_OUTPUT;     // Enable PWM output on P1.2 (channel 0)
   
        // For demonstration: Increase duty cycle from 1% to 90%
        for (duty = 1; duty <= 90; duty += 10) {
            setPWMDutyCycle(duty);  // Change duty cycle dynamically
            delay(500);             // Simple delay to observe changes
        }
    }
}