How to update duty cycle once only?

91 views Asked by At

I am programming STM32 chip in C and trying to control duty cycle of PWM cycle depending on ADC read value. with below implementation; I am able to set different duty cycle along with ADC value. But I realized that it repeatedly sets duty cycle of PWM as it's in the while loop.. but I need to keep this while loop as I need to constantly check ADC. My expectation is that it only sets single duty cycle (or desired duty cycle) then stops sending data to PWM and ready for the next change from ADC. How should I achieve that? Let me know if I can help clarifying the question. Thank you

#include <stdio.h>

int main()
{   
    int adc_val = 3000; 
    int init_duty = 250;
    int var = 0;
    int data = 0;
        
    int foldit(int var){
        if (var <1200) return 0;
        else if (var >= 1200 && var <= 2000) return 1;
        else if (var > 2000) return 2;
    }
    
    int toSend(int data){
        static int old_duty = -1;
        if(init_duty != old_duty){
            printf("sending data : %d\n", init_duty);
            old_duty = init_duty;
            //TIM1->CCR1 = init_duty;
        }
        else{
            printf("not sending data : %d\n", init_duty);
            //not sending datat 
        }
    }
    
    while(1){
        // adc val = SPI_Raed_ADC_RxData();
        switch(foldit(adc_val)){
            case 0:
                toSend(init_duty);
                printf("current duty cycle set to default :%d\n", init_duty);
                break;
            
            case 1:
                if(init_duty <= 200){
                    //send_UART(setPWMDutyCycle(init_duty));
                    printf("current duty cycle 2.0 :%d\n", init_duty);
                    toSend(init_duty);
                }
                else{
                    for(int i=0;i<10;i++){
                        init_duty = init_duty -10;
                        //send_UART(setPWMDutyCycle(init_duty));
                        if(init_duty <=200)
                        {
                            break;    
                        }
                        printf("current duty cycle 2.1 : %d\n", init_duty);
                        toSend(init_duty);
                    }    
                }
                break;
            
            case 2:
                init_duty = 400;
                //send_UART(setPWMDutyCycle(init_duty));
                printf("current duty cycle 3 : %d\n", init_duty);
                toSend(init_duty);
                break;
            
            default:
                break;
        }
        
    }
}
    

I expect to send data to PWM using send_UART(setPWMDutyCycle(init_duty))only once or update until it reaches desired value.

0

There are 0 answers