stm32 analog output multiple pwm through IO port

    This is mainly used to control the steering gear. TIM1 is used to simulate 5 channels of 50Hz PWM signals, and only the duty cycle is adjusted to control the angle of the steering gear.

There is no specific test for the maximum number of channels that can be simulated.

Disadvantage: Because it is a timer interrupt simulation (interrupts are more frequent), it will affect the main function running.

	LED p1('A',8); //IO port initialization, not introduced here, push-pull output
	LED p2('A',9);
	LED p3('A',10);
	LED p4('A',11);
	LED p5('A',4);
u16 count=0;
u16 pwm_count=1000; //Total count period 20ms, 20us advance
u16 pwm1 = 25;
u16 pwm2=25;
u16 pwm3 = 25;
u16 pwm4=125;
u16 pwm5 = 125;
extern "C" void TIM4_IRQHandler(void)//1ms come in once
{ 		    		  			    
	if(TIM4->SR&0X0001)//Overflow interrupt
	{ 	
		count++;	
		if(count<pwm1)
		{
			PAout(8)=1;
			
		}
		else{
			PAout(8)=0;
		}
		//-------------------------------
		if(count<pwm2)
		{
			PAout(9)=1;
			
		}
		else{
			PAout(9)=0;
		}
		//------------------------------
		if(count<pwm3)
		{
			PAout(10)=1;
			
		}
		else{
			PAout(10)=0;
		}
		//--------------------------------
		if(count<pwm4)
		{
			PAout(11)=1;
			
		}
		else{
			PAout(11)=0;
		}
		//-------------------------------
		if(count<pwm5)
		{
			PAout(4)=1;
			
		}
		else{
			PAout(4)=0;
		}
		
		if(count==pwm_count)count=0;


	}				   
	TIM4->SR&=~(1<<0);//Clear the interrupt flag 	    
}
//Enable timer 4, enable interrupt.
void Timer1_Init(u16 arr,u16 psc)
{
	RCC->APB1ENR|=1<<2; //TIM4 clock enable    
 	TIM4->ARR=arr; //Set the automatic reload value of the counter  
	TIM4->PSC=psc; //Prescaler 71, get 1Mhz count clock	
	TIM4->DIER|=1<<0; //Allow update interrupt			  							    
	TIM4->CR1|=0x01; //Enable timer 2
  MY_NVIC_Init(1,1,TIM4_IRQn,2);//Preempt 1, sub-priority 1, group 2 (the highest priority in group 2)									 
}

Timer1_Init(19,71); The initialization is good, and it is interrupted every 20us.

Control the servo angle by changing these values

19, and the total count to control the frequency.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325585664&siteId=291194637