以下是PWM.c
#include "pwm.h"
void TIM3_PWM_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE); //ʹÄÜGPIOÍâÉèºÍAFIO¸´Óù¦ÄÜÄ£¿éʱÖÓʹÄÜ
//ÉèÖøÃÒý½ÅΪ¸´ÓÃÊä³ö¹¦ÄÜ,Êä³öTIM3 CH3==>PB0 CH4==>PB1 µÄPWMÂö³å²¨ÐÎ
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_7; //³õʼ»¯GPIO
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //¸´ÓÃÍÆÍìÊä³ö
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_2; //ͨµÀÉèÖÃ
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; //ÉÏÉýÑØ´¥·¢
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; //¹Ü½ÅÓë¼Ä´æÆ÷¶ÔÓ¦¹Øϵ
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; //ÊäÈëÔ¤·ÖƵ¡£Òâ˼ÊÇ¿ØÖÆÔÚ¶àÉÙ¸öÊäÈëÖÜÆÚ×öÒ»´ÎÊäÈëºÍÐźÅƵÂÊûÓб䣬²âµÃµÄÖÜÆÚÒ²²»»á±ä£
//±ÈÈçÑ¡Ôñ4·ÖƵÔòÿËĸöÊäÈëÖÜÆÚ²Å×öÒ»´Î²¶»ñ£¬ÕâÑùÔÚÊäÈëÐźű仯²»Æµ·±µÄÇé¿öÏ£¬¿ÉÒÔ¼õÉÙÈí¼þ±»²»¶ÏÖжϵĴÎÊý¡£
TIM_ICInitStructure.TIM_ICFilter = 0x0; //Â˲¨ÉèÖ㬾Àú¼¸¸öÖÜÆÚÌø±äÈ϶¨²¨ÐÎÎȶ¨0x0~0xf
TIM_PWMIConfig(TIM3, &TIM_ICInitStructure); //¸ù¾Ý²ÎÊýÉèÖÃTIMÍâÉèÐÅÏ¢
TIM_SelectInputTrigger(TIM3, TIM_TS_TI2FP2); //Ñ¡ÔñIC2ΪʼÖÕ´¥·¢Ô´
TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Reset); //TIM´Óģʽ£º´¥·¢ÐźŵÄÉÏÉýÖØгõʼ»¯¼ÆÊýÆ÷ºÍ´¥·¢¼Ä´æÆ÷µÄ¸üÐÂʼþ
TIM_SelectMasterSlaveMode(TIM3, TIM_MasterSlaveMode_Enable); //Æô¶¯¶¨Ê±Æ÷µÄ±»¶¯´¥·¢
TIM_Cmd(TIM3, ENABLE); //Æô¶¯TIM3
TIM_ITConfig(TIM3, TIM_IT_CC2, ENABLE); //´ò¿ªÖжÏ
}
u16 IC2Value = 0;
u16 DutyCycle = 0;
u16 Frequency = 0;
void TIM3_IRQHandler(void)
{
TIM_ClearITPendingBit(TIM3,TIM_IT_CC2);//Çå³ýTIMµÄÖжϴý´¦Àíλ
IC2Value=TIM_GetCapture2(TIM3); //¶ÁÈ¡IC2²¶»ñ¼Ä´æÆ÷µÄÖµ£¬¼´ÎªPWMÖÜÆڵļÆÊýÖµ
if(IC2Value!=0)
{
DutyCycle=(TIM_GetCapture1(TIM3)*100)/IC2Value; //¶ÁÈ¡IC1²¶»ñ¼Ä´æÆ÷µÄÖµ£¬²¢¼ÆËãÕ¼¿Õ±È
Frequency=72000000/IC2Value; //¼ÆËãPWMƵÂÊ
}
else
{
DutyCycle=0;
Frequency=0;
}
}
以下是main.c
#include "delay.h"
#include "sys.h"
#include "usart.h"
#include "exti.h"
#include "wdg.h"
#include "pwm.h"
extern void TIM3_IRQHandler(void);
extern void TIM3_PWM_Init(void);
extern u16 IC2Value;
extern u16 DutyCycle ;
extern u16 Frequency ;
int main(void)
{
SystemInit();
delay_init(72); //ÑÓʱ³õʼ»¯
NVIC_Configuration(); //ÖжÏÅäÖÃ
uart_init(9600); //´®¿Ú³õʼ»¯
while(1)
{
delay_ms(1004);
if(!IC2Value)
{
printf("CO2 = %d\r\n",DutyCycle);
printf("CO2 = %d\r\n",Frequency);
}
}
}
为何读取不到数据呢?用的是PA7 TIM3_CH2
|