Raspberry Pi 4B study notes (10)-PWM output

Preface

For the usage of each function, please check my other blog " Raspberry Pi wiringPi library functions ".
For pin number descriptions, please check my other blog " Raspberry Pi 4B Study Notes (5) -Let’s GPIO operate it . "

1. Hardware PWM

Raspberry Pi hardware only supports GPIO1 pin to output PWM. If you want to output PWM on other pins, you can only use software PWM.
The following is the hardware PWM code of the GPIO1 pin, which can realize the level of the GPIO1 pin from low to high, and then from high to low.

#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
#include <softPwm.h>  //必不可少
int main( void)
{
    
    
  int pwm_gpio1 = 1;  //使用GPIO1
  int i=0;
  if(wiringPiSetup() == -1)
    {
    
    
    	printf("Init error\n");
		exit(1);
	}
  pinMode(pwm_gpio1 ,PWM_OUTPUT);
  printf("pwm_gpio1 is blinking...\n");    
  for(;;)
  {
    
    
    for(i=0;i<1024;i++)
    {
    
    
      pwmWrite(pwm_gpio1 ,i);
      delay(10);
      printf("Testing is %d......\n",i);    
    }
    for(i=1023;i>0;i--)
    {
    
    
      pwmWrite(pwm_gpio1 ,i);
      delay(10);
      printf("Testing is %d......\n",i);    
    }
  }
}

2. Software PWM

Because the hardware PWM of the Raspberry Pi only supports one pin of GPIO1, in order to enable other GPIO pins to output PWM, the wiringPi library provides a software PWM library.

Need to add pthread library link -lpthread when compiling.

The following is the software PWM code of the GPIO0 pin, which can realize the level of the GPIO0 pin from low to high, and then from high to low.

#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
#include <softPwm.h>
int main( void)
{
    
    
    int pwm_gpio0 = 0;
    int i=0;
    if(wiringPiSetup() == -1)
    {
    
    
    	printf("Init error\n");
		exit(1);
	}
    pinMode(pwm_gpio0 ,PWM_OUTPUT); // OUTPUT也可以
    printf("pwm_gpio0 is blinking...\n");    
    softPwmCreate(pwm_gpio0 ,0 ,100); //创建软PWM 初始值0 重装载值100 
    for( ; ; )
    {
    
    
        for(i=0;i<100;i++)
        {
    
    
            softPwmWrite(pwm_gpio0 ,i);
            delay(30);
            printf("Testing is %d......\n",i);    
        }
        for(i=99;i>0;i--)
        {
    
    
            softPwmWrite(pwm_gpio0 ,i);
            delay(30);
            printf("Testing is %d......\n",i);    
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_44415639/article/details/114842813