PWM Drive Motor for Balanced Car

Preface

We know that the internal processing of single-chip computers is such a digital signal as 0,1. If we only use 0,1 to control the speed of the car, this is certainly unrealistic. Engineers think of using the ratio of the power level to the whole cycle to average the output voltage, so that several single voltages become many different analog output voltages. It's AD/DA conversion everywhere!

1. L298N driver module



Wiring preparation

This is the wiring diagram of the motor I use. Since there is no encoder to measure the speed this time, we only need to connect L298N output A to the positive and negative poles of motor 1 and L298N output B to the positive and negative poles of motor 2.

2. Generation of PWM waves by STM32

(1) Initialization code

void TIM4_PWM_Init(u16 arr,u16 psc)
{
	
	GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	TIM_OCInitTypeDef  	TIM_OCInitStructure;
	
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);	
 	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);  
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8|GPIO_Pin_9;   //TIM_CH3,TIM_CH4
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;        //Configuration to multiplex push-pull output
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;			 //Output speed 50 MHz
	GPIO_Init(GPIOB, &GPIO_InitStructure);                 //Initialize GPIO
	
	
	TIM_TimeBaseStructure.TIM_Period = arr;                // Auto reload register values, cumulative TIM_Period+1 frequency produces an update or interrupt
	TIM_TimeBaseStructure.TIM_Prescaler =psc;              // Clock driving CNT counter = Fck_int/(psc+1)
	TIM_TimeBaseStructure.TIM_ClockDivision = 0;            //Set clock nonfrequency
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  //TIM Up Count Mode
	TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);          //According to TIM_ Unit of time base for initializing TIMx with parameters specified in TimeBaseInitStruct
	
	 
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;        // Configured for PWM mode 1
 	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;  // Output Enables
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; // Output Channel Level Polarity Configuration 	   TIM Output Polarity is High

	TIM_OC3Init(TIM4,&TIM_OCInitStructure);                   //Parameter Initialization Peripheral TIM4 OC3
	TIM_OC4Init(TIM4,&TIM_OCInitStructure);  									//Parameter Initialization Peripheral TIM4 OC4
	
	TIM_OC3PreloadConfig(TIM4, TIM_OCPreload_Enable);          //Enable TIM4 OC3 Preloader
	TIM_OC4PreloadConfig(TIM4, TIM_OCPreload_Enable);					//Enable TIM4 OC4 Preloader
	
	TIM_Cmd(TIM4,ENABLE);       //Enable TIM4
 
}

Configuration process

  • Initialize GPIO structure
  • Base structure at initialization
  • Configure Output Comparison Parameters
  • Enabling timer

(2) PWM Code Analysis

	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;        // Configured for PWM mode 1
 	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;  // Output Enables
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; // Output Channel Level Polarity Configuration 	   TIM Output Polarity is High


Here we select the PWM1 mode, the counter counting method is to increase upwards, the effective level is high.
So when CNT counts from zero to CCR, the output is high level.
When the counter value CNT is equal to the CCR value, the level flips to a low level until the calculator overflow (the value of CNT is equal to the value of the autoloader ARR) remains low.

But what if the value of CCR is greater than the value of ARR?

The following is the output of PWM with different CCR values

(3) Functions of the preloader?

TIM_OC3PreloadConfig(TIM4, TIM_OCPreload_Enable);          //Enable TIM4 OC3 Preloader
TIM_OC4PreloadConfig(TIM4, TIM_OCPreload_Enable);					//Enable TIM4 OC4 Preloader

When outputting PWM waves, does this statement seem to work, but why is it added to many specifications? What is the difference between them?

The significance of enabling preloading is that the time series can be synchronized accurately when multiple channels can be output simultaneously. A meaningful explanation on the Web is that the benefits of designing preload registers and shadow registers are that all the registers that really need to work (shadow registers) can be updated to the contents of the corresponding preload registers at the same time (when an update event occurs), which ensures accurate synchronization of operations across multiple channels.

If there is no shadow register, or if preload registers and shadow registers are straight-forward, that is, when software updates preload registers, shadow registers are updated at the same time, because software cannot update multiple registers at the same time, resulting in the timing of multiple channels not synchronized, if other factors are added (such as interruption), Time series relationships for multiple channels may be unpredictable. It can be seen that if only single channel output is used, multi-channel output does not have synchronous update requirements with precise timing, so it is not possible.

To tell you the truth, I didn't understand what I was looking for online, so I read some explanations for the registers of the corresponding operations of this function.

void TIM_OC1PreloadConfig(TIM_TypeDef* TIMx, uint16_t TIM_OCPreload)
{
  uint16_t tmpccmr1 = 0;
  /* Check the parameters */
  assert_param(IS_TIM_LIST8_PERIPH(TIMx));
  assert_param(IS_TIM_OCPRELOAD_STATE(TIM_OCPreload));
  tmpccmr1 = TIMx->CCMR1;
  /* Reset the OC1PE Bit */
  tmpccmr1 &= (uint16_t)~((uint16_t)TIM_CCMR1_OC1PE);
  /* Enable or Disable the Output Compare Preload feature */
  tmpccmr1 |= TIM_OCPreload;
  /* Write to TIMx CCMR1 register */
  TIMx->CCMR1 = tmpccmr1;
}

We found that this function operates on OC1PE bit of CCMR1 register and see what it says in the reference manual

The function first resets the OC1PE bit, then determines whether the position is high or low according to the parameters. If we enable this bit, when we change the value in the CCR1 register, he will not change it immediately, but will finish this cycle before updating the value in the next one.

For example, we set ARR=100, CCR1=50, and the accumulator goes up from 0. When OC1PE=0, we suddenly change the value of CCR1 when the accumulator is added to 30, so CCR1=70. When the accumulator is added to 50, the level will not jump, because when OC1PE=0, the change of CCR1 will take effect immediately, at this time CCR1=70 has already been added, so 70 will jump.

When OC1PE=1, it will not take effect in this cycle, and the accumulator will jump at 50, and then it will jump from 70 in the next cycle.

Reference Source

Therefore, for the control motor drive with inaccurate timing requirements, it is OK to turn it on or off. It's not bad if you want to be lazy and write fewer sentences.

3. PWM Speed Control Principle

Take single-chip computer as an example, we know that the IO port of single-chip computer outputs digital signals, and IO port can only output high and low levels. Assuming that the high level is 5V and the low level is 0V, we need to use PWM to output different analog voltage. By changing the duty cycle of the square wave output from the IO port, we can get the analog voltage signal which is simulated using the digital signal.

We know that the voltage is clamped to an analog load by a repetitive pulse sequence connecting 1 or disconnecting 0 (e.g. LED lamp, DC motor, etc.). The connection is the output of the DC power supply, and the disconnection is the disconnection of the DC power supply.

By controlling the connection and disconnection time, it is theoretically possible to output any analog voltage ratio that is no greater than the maximum voltage value (i.e., any size between 0 and 5V) with a duty cycle of 50%.
That is half the high level time and half the low level time. At a certain frequency, you can get the simulated 2.5V output voltage and 75% duty cycle to get 3.75V.

The regulation effect of pwm comes from the width control of "cycle-occupying". When the cycle-occupying circuit is widened, the output energy will be increased, the average voltage value obtained by the resistance-capacitance converter circuit will also rise, the cycle-occupying circuit will become narrower, the average voltage value of the output voltage signal will be reduced, and the average voltage value obtained by the resistance-capacitance converter circuit will also decrease.

That is, at a certain frequency, different output analog voltage can be obtained by different duty cycles
This is how pwm achieves D/A conversion.

PWM is to change the output effective voltage PWM frequency by changing the duty cycle at the appropriate signal frequency. The larger the output effective voltage PWM frequency, the faster the corresponding.

Specific reference

PWM Principle PWM Frequency and Duty Cycle Detailed

Initialize in main function

 TIM4_PWM_Init(1999,7199);	 //arr=1999,psc=7199

Here my clock frequency is 72MHz, so 72MHz/(7199+1)=10KHz after crossover. The working frequency of this motor I use is about 10Khz. When setting the crossover factor, pay attention to the parameters of the motor, otherwise the motor may not work properly.

Set the value of CCR

 TIM_SetCompare3(TIM4,1000);  //The value of CCR3 for TIM4 is set to 1000

View function prototypes

void TIM_SetCompare3(TIM_TypeDef* TIMx, uint16_t Compare3)
{
  /* Check the parameters */
  assert_param(IS_TIM_LIST3_PERIPH(TIMx));
  /* Set the Capture Compare3 Register value */
  TIMx->CCR3 = Compare3;
}

Since we have previously selected the PWM1 mode and the high level is the effective level, so (CCR-0) is the high level duration with duty cycle (CCR-0)/1999+1;
Such as TIM_SetCompare3(TIM4,800); Duty Cycle Ratio (800-0)/1999+1=40%
TIM_SetCompare3(TIM4,1500); Duty Cycle Ratio (1500-0)/1999+1=75%

With this function, we can set different duty cycles to control the speed of the motor.

summary

You didn't learn so much when you used these modules before. This time, you have basically studied every knowledge point carefully because you want to write a blog, but there may still be some mistakes. Thank you for your understanding and correction.

Reference resources

Zero Foundation Balanced Cart 3-STM32 Generate PWM Control Motor Rotation

PWM Principle PWM Frequency and Duty Cycle Detailed

Tags: Single-Chip Microcomputer IoT stm32

Posted on Sun, 21 Nov 2021 15:07:37 -0500 by R0CKY