AnsweredAssumed Answered

How to set PWM frequency ?

Question asked by naveen kumar on Jul 1, 2019
Latest reply on Jul 2, 2019 by naveen kumar

Hi,

 

We are  using Imx6UL board and five PWM's for my project, i am able to set pwm frequency and duty cycle using command line (echo command ) , same commands unable to set using c code, Please any one help on this issues.

 

My code :

 

static int PWMSetTimePeriod(int pwmnumber, int period)
{
        char path[VALUE_MAX];
       char buffer[BUFFER_MAX];
        int fdpwmperiod;
       ssize_t bytes_written;


        snprintf(path, VALUE_MAX, " /sys/class/pwm/pwmchip%d/pwm0/period", pwmnumber);

        printf("PWMSet TimePeriod path = %s period = %d\n",path,period);

        fdpwmperiod = open(path, O_RDWR);
        if (-1 == fdpwmperiod)
       {
                fprintf(stderr, "Failed to open set pwm period for writing!\n");
                return(-1);
        }

      bytes_written = snprintf(buffer, BUFFER_MAX, "%d", period);
        if (1 != write(fdpwmperiod, buffer, bytes_written)) {
                fprintf(stderr, "Failed to set pwm period value!\n");
                return(-1);
        }

       printf("path = %s period=%s\n",path,buffer);

        close(fdpwmperiod);
        return(0);
}


static int PWMSetDutyCycle(int pwmnumber, int duty_cycle)
{
       
        char path[VALUE_MAX];
        int fdpwmdutycycle;

 

        snprintf(path, VALUE_MAX, " /sys/class/pwm/pwmchip%d/pwm0/duty_cycle", pwmnumber);
        fdpwmdutycycle = open(path, O_WRONLY);
        if (-1 == fdpwmdutycycle) {
                fprintf(stderr, "Failed to open set pwm PWMSetDutyCycle for writing!\n");
                return(-1);
        }
        if (1 != write(fdpwmdutycycle, &duty_cycle, sizeof(int))) {
                fprintf(stderr, "Failed to set pwm persiod value!\n");
                return(-1);
        }
        close(fdpwmdutycycle);
        return(0);
}

 


static int PWMEnable(int pwmnumber, int value)
{  
        char path[VALUE_MAX];
        int fdpwmenable;

        snprintf(path, VALUE_MAX, " /sys/class/pwm/pwmchip%d/pwm0/enable", pwmnumber);
        fdpwmenable = open(path, O_WRONLY);
        if (-1 == fdpwmenable) {
                fprintf(stderr, "Failed to open pwm enable for writing!\n");
                return(-1);
        }
       if (1 != write(fdpwmenable, &value, sizeof(int))) {
                fprintf(stderr, "Failed to enable/disable pwm!\n");
                return(-1);
        }
        close(fdpwmenable);
        return(0);
}

 

Console Output Logs :

 

PWMSet TimePeriod path =  /sys/class/pwm/pwmchip1/pwm0/period period = 10000
Failed to open set pwm period for writing!
Failed to open set pwm PWMSetDutyCycle for writing!
Failed to open pwm enable for writing!

 

Regarsd,

PK

Outcomes