블루 브리지 내장형 TIM의 PWM 모드Again

프로젝트 코드 표시 Github

1. 주요 코드

main.c
/*******************************************************************************
*    :main.c
*     :
*     :CLAY
*    :v1.0.0
*     : 2019 2 18 
*     :    LCD  
*         PA1 (TIM2_CH2)     500Hz,   60%   
*******************************************************************************
*/

#include "stm32f10x.h"
#include "lcd.h"
#include "e2prom.h"
#include "stdio.h"
#include "i2c.h"
#include "adc.h"
#include "rtc.h"
#include "usart2.h"
#include "pwm.h"

u32 TimingDelay = 0;
u8 RxdCnt = 0;
u8 RxdOver = 0;
u8 RxdBuf[20];
void Delay_Ms(u32 nTime);
u8 RTC_Flag = 0;

//Main Body
int main(void)
{	
	STM3210B_LCD_Init();
	LCD_Clear(Blue);
	LCD_SetBackColor(Blue);
	LCD_SetTextColor(White);
	
	SysTick_Config(SystemCoreClock/1000);
	
	PWM_Init(500, 60);//500Hz 60%  
	
	while(1)
	{
		
	}
}

//
void Delay_Ms(u32 nTime)
{
	TimingDelay = nTime;
	while(TimingDelay != 0);	
}

pwm.c
#include "stm32f10x.h"

void PWM_Init(u32 freq, u8 duty)
{
	u32 arr;
	
	GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	TIM_OCInitTypeDef  TIM_OCInitStructure;
	
	arr = 1000000 / freq;//          
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;//     
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	TIM_TimeBaseStructure.TIM_Prescaler = 72-1;//72  
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseStructure.TIM_Period = arr - 1;//   
	TIM_TimeBaseStructure.TIM_ClockDivision = 0;
	TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);//TIM2   
	
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;//  
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;//  
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OCInitStructure.TIM_Pulse = (arr-1) * duty / 100;//   
	TIM_OC2Init(TIM2, &TIM_OCInitStructure);//TIM2_CH2
	
	TIM_Cmd(TIM2, ENABLE);//  TIM2
}


pwm.h
#ifndef _PWM_H
#define _PWM_H


void PWM_Init(u32 freq, u8 duty);

#endif


주의사항


1. TIM의 PWM 모드 채널 설정은 대응해야 한다.
TIM_OC2Init(TIM2, &TIM_OCInitStructure);//TIM2_CH2
2 채널은 써야 한다TIM_OC2Init, 같은 이치로 1 채널은 써야 한다TIM_OC1Init2. 주파수값으로 주기값을 계산한다arr = 1000000 / freq;//

좋은 웹페이지 즐겨찾기