STM32 PWM and DAC practice

Summary:

This article uses the PWM output waveform to control the IO port to realize the breathing light, and through the DAC output 2KHz sine wave and edit the audio output function.

1. PWM exercise


1. Introduction to PWM

PWM is the abbreviation of Pulse Width Modulation, Chinese means pulse width modulation , referred to as pulse width modulation . It is a very effective technology that uses the digital output of the microprocessor to control the analog circuit. Its advantages of simple control, flexibility and good dynamic response have become the most widely used control method of power electronics.

The schematic diagram is as follows:

STM32F1 addition to the basic timer TIM6 and TIM7, other timers can generate PWM outputs. The advanced timers TIM1 and TIM8 can generate up to 7 PWM outputs at the same time. The general-purpose timer can also generate up to 4 PWM outputs at the same time, which have been introduced in the timer interrupt chapter. The PWM output is actually a square wave signal with adjustable pulse width (that is, duty cycle adjustment) . The signal frequency is determined by the value of the automatic reload register ARR, and the duty cycle is determined by the value of the compare register CCR. There are a total of 8 PWM output compare modes, which are specifically configured by the bits OCxM[2:0] of the CCMRx register. We only explain the two most commonly used PWM output modes here: PWM1 and PWM2. For other modes, please refer to chapters 13, 14, 15 timers of "STM32F10x Chinese Reference Manual".

For more knowledge, please refer to the stm32 PWM output experiment

2. PWM output configuration

1) Configure the enable port clock and set the pin multiplexer mapping

2) Initialize timer parameters, including automatic reload value, frequency division coefficient, counting method, etc.

Initialize PWM output parameters, including output polarity, enable, etc.

2

3) Start the timer

4) Then control the duty cycle in the main function:

At this time, the looping code in while(1) has the effect that the duty cycle of led0pwmval gradually increases, that is, it gets brighter and brighter. in

delay_ms(10);	 
if(dir)led0pwmval++;
else led0pwmval--;
if(led0pwmval>300)dir=0;
if(led0pwmval==0)dir=1;										 
TIM_SetCompare2(TIM3,led0pwmval);	

3. Main code

void TIM3_Int_Init(u16 arr,u16 psc)
{
    
    
  TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	NVIC_InitTypeDef NVIC_InitStructure;

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //时钟使能

	TIM_TimeBaseStructure.TIM_Period = arr; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值	 计数到5000为500ms
	TIM_TimeBaseStructure.TIM_Prescaler =psc; //设置用来作为TIMx时钟频率除数的预分频值  10Khz的计数频率  
	TIM_TimeBaseStructure.TIM_ClockDivision = 0; //设置时钟分割:TDTS = Tck_tim
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  //TIM向上计数模式
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); //根据TIM_TimeBaseInitStruct中指定的参数初始化TIMx的时间基数单位
 
	TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE ); //使能指定的TIM3中断,允许更新中断

	NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;  //TIM3中断
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;  //先占优先级0级
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;  //从优先级3级
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道被使能
	NVIC_Init(&NVIC_InitStructure);  //根据NVIC_InitStruct中指定的参数初始化外设NVIC寄存器

	TIM_Cmd(TIM3, ENABLE);  //使能TIMx外设
							 
}
//定时器3中断服务程序
void TIM3_IRQHandler(void)   //TIM3中断
{
    
    
	if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) //检查指定的TIM中断发生与否:TIM 中断源 
		{
    
    
		TIM_ClearITPendingBit(TIM3, TIM_IT_Update  );  //清除TIMx的中断待处理位:TIM 中断源 
		LED1=!LED1;
		}
}
//TIM3 PWM部分初始化 
//PWM输出初始化
//arr:自动重装值
//psc:时钟预分频数
void TIM3_PWM_Init(u16 arr,u16 psc)
{
    
      
	GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	TIM_OCInitTypeDef  TIM_OCInitStructure;
	

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);	//使能定时器3时钟
 	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB  | RCC_APB2Periph_AFIO, ENABLE);  //使能GPIO外设和AFIO复用功能模块时钟
	
	GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3, ENABLE); //Timer3部分重映射  TIM3_CH2->PB5    
 
   //设置该引脚为复用输出功能,输出TIM3 CH2的PWM脉冲波形	GPIOB.5
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; //TIM_CH2
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;  //复用推挽输出
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &GPIO_InitStructure);//初始化GPIO
 
   //初始化TIM3
	TIM_TimeBaseStructure.TIM_Period = arr; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值
	TIM_TimeBaseStructure.TIM_Prescaler =psc; //设置用来作为TIMx时钟频率除数的预分频值 
	TIM_TimeBaseStructure.TIM_ClockDivision = 0; //设置时钟分割:TDTS = Tck_tim
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  //TIM向上计数模式
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); //根据TIM_TimeBaseInitStruct中指定的参数初始化TIMx的时间基数单位
	
	//初始化TIM3 Channel2 PWM模式	 
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //选择定时器模式:TIM脉冲宽度调制模式2
 	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性:TIM输出比较极性高
	TIM_OC2Init(TIM3, &TIM_OCInitStructure);  //根据T指定的参数初始化外设TIM3 OC2

	TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);  //使能TIM3在CCR2上的预装载寄存器
 
	TIM_Cmd(TIM3, ENABLE);  //使能TIM3
	

}

4. Demonstration effect

a. Analog oscilloscope display

Select the magic wand -Debug-configuration is as follows

The oscilloscope configuration is as follows:

display effect:

b. Oscilloscope display

c. Physical effect

2. DAC practice


1. Introduction to DAC

  • DAC is a digital/analog conversion module , so the name suggests. Its function is to convert the input digital code into the corresponding analog voltage output. Its function is opposite to that of ADC. In a common digital signal system, most sensor signals are converted into voltage signals, and the ADC converts the voltage analog signal into a digital code that is easy to be stored and processed by the computer. After the computer is processed, the DAC outputs the voltage analog signal. Analog signals are often used to drive certain actuators, making it easy for humans to perceive. For example, the collection and restoration of audio signals is such a process.
  • STM32 has an on-chip DAC peripheral. Its resolution can be configured as an 8-bit or 12-bit digital input signal. It has two DAC output channels . These two channels do not affect each other. Each channel can use the DMA function. Error detection capability can be triggered externally.
  • The DAC module diagram is as follows:

The entire DAC module is expanded around **"Digital to Analog Converter x"** at the bottom of the block diagram. On its left are the reference power pins: VDDA, VSSA, and Vref+. The STM32 DAC specifies its reference voltage Vref+ input The range is 2.4–3.3V. The input of "digital-to-analog converter x" is the digital code of the DAC's data register "DORx", and the analog signal converted by it is output by "DAC OUTX" on the right side of the figure. The data register "DORx" is also controlled by the "control logic", which can control the data register to add some pseudo noise signals or configure to generate a triangular wave signal. The upper left corner of the figure is the trigger source of the DAC. The DAC performs DAC conversion according to the signal of the trigger source. Its function is equivalent to the switch of the DAC converter. The trigger source that can be configured is external interrupt source trigger, timer trigger or software Control trigger. If you need to control the frequency of the sine wave in the experiment in this chapter, you need a timer to trigger the DAC to perform data conversion.

2. Analyze the key points and realize the output of 2KHz sine wave

  • DAC_Trigger is used to configure the DAC trigger mode

  • DAC_WaveGeneration is whether to start output noise or triangle wave

  • DAC_LFSRUnmask_TriangleAmpliude selects the low-pass filter or the amplitude of the triangle wave of the noise generator

  • DAC_OutputBuffer select whether to enable the output buffer

    For more steps, please refer to《【野火®】零死角玩转STM32—F103-MINI》

    According to the formula:

Set as follows

This will output2KhzSine wave

The results are as follows:

Connect the buzzer and hear a single tone.

4. Design output audio signal

The logic of the algorithm is similar to the idea of ​​outputting a sine wave signal, but the difference is to change the sampled value.

step1: Turn Adobe Auditionon your favorite music, set:

  • Sampling rate 8000
  • Mono
  • 16th place
  • About 2-3s collection

step2: save as .wav file

.wav files are Uedit32opened by software

step3: format conversion

Select all content, right click-copy the selected view in hexadecimal, copy to notepad-paste back-right click-select range

step4: Copy to notepad++ for filling

Regarding notepad++the usage mentioned above,

Insert by column block 0xand ,repeat operation for each column

step5: modify the array

step6: Burn in to observe the waveform

3. Summary

In this experiment, I tried to understand DAC and PWM. These two modules are widely used in timing. For example, in some competitions, you can use PWM waves to control the steering gear and click, and use ADC and DAC to collect information. Gain a lot

reference

[1] Use STM32 to control passive buzzer to sound and play music (STM32_07)

[2] Stm32 PMW output experiment

[3] Detailed explanation of the waveform diagram of the IO port based on STM32 keil4 MDK software simulation output!

Guess you like

Origin blog.csdn.net/lee_goi/article/details/111998475