a)目的:基礎(chǔ)PWM輸出,以及中斷配合應(yīng)用。輸出選用PB1,配置為TIM3_CH4,是目標(biāo)板的LED6控制腳。b)對(duì)于簡(jiǎn)單的PWM輸出應(yīng)用,暫時(shí)無需考慮TIM1的高級(jí)功能之區(qū)別。
本文引用地址:http://m.butianyuan.cn/article/201611/322072.htmc)初始化函數(shù)定義:
void TIM_Configuration(void);//定義TIM初始化函數(shù)
d)初始化函數(shù)調(diào)用:
TIM_Configuration();//TIM初始化函數(shù)調(diào)用
e)初始化函數(shù),不同于前面模塊,TIM的初始化分為兩部分——基本初始化和通道初始化:
void TIM_Configuration(void)//TIM初始化函數(shù)
{
TIM_TimeBaseInitTypeDefTIM_TimeBaseStructure;//定時(shí)器初始化結(jié)構(gòu)
TIM_OCInitTypeDefTIM_OCInitStructure;//通道輸出初始化結(jié)構(gòu)
//TIM3初始化
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;//周期0~FFFF
TIM_TimeBaseStructure.TIM_Prescaler = 5;//時(shí)鐘分頻
TIM_TimeBaseStructure.TIM_ClockDivision = 0;//時(shí)鐘分割
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;//模式
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);//基本初始化
TIM_ITConfig(TIM3, TIM_IT_CC4, ENABLE);//打開中斷,中斷需要這行代碼
//TIM3通道初始化
TIM_OCStructInit(& TIM_OCInitStructure);//默認(rèn)參數(shù)
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;//工作狀態(tài)
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;//設(shè)定為輸出,需要PWM輸出才需要這行代碼
TIM_OCInitStructure.TIM_Pulse = 0x2000;//占空長(zhǎng)度
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;//高電平
TIM_OC4Init(TIM3, &TIM_OCInitStructure);//通道初始化
TIM_Cmd(TIM3,ENABLE);//啟動(dòng)TIM3
}
f)RCC初始化函數(shù)中加入TIM時(shí)鐘開啟:
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM3, ENABLE);
g)GPIO里面將輸入和輸出管腳模式進(jìn)行設(shè)置。信號(hào):AF_PP,50MHz。
h)使用中斷的話在NVIC里添加如下代碼:
//打開TIM2中斷
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQChannel;//通道
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;//占先級(jí)
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;//響應(yīng)級(jí)
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;//啟動(dòng)
NVIC_Init(&NVIC_InitStructure);//初始化
中斷代碼:
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_CC4) != RESET)//判斷中斷來源
{
TIM_ClearITPendingBit(TIM2, TIM_IT_CC4);//清除中斷標(biāo)志
GPIO_WriteBit(GPIOB, GPIO_Pin_11, (BitAction)(1-GPIO_ReadOutputDataBit(GPIOB, GPIO_Pin_11)));//變換LED色彩
IC4value = TIM_GetCapture4(TIM2);//獲取捕捉數(shù)值
}
}
i)簡(jiǎn)單應(yīng)用:
//改變占空比
TIM_SetCompare4(TIM3,變量);
j)注意事項(xiàng):
管腳的IO輸出模式是根據(jù)應(yīng)用來定,比如如果用PWM輸出驅(qū)動(dòng)LED則應(yīng)該將相應(yīng)管腳設(shè)為AF_PP,否則單片機(jī)沒有輸出。
評(píng)論