本帖最后由 yueguang3048 于 2019-12-27 15:48 编辑
-------------刚开始玩单片机代码,拿STC官方的代码修改的:--------------
软PWM,1KHz 占空比1%,输入到CCP1中,取高电平的时间,发现打印出来的一直是300uS,正常结果应该是500uS,求高手帮助,谢谢void GPIO_Init()
{
P0M0 = 0x00;P0M1 = 0x00;
P1M0 = 0x00;P1M1 = 0x00;
P2M0 = 0x00;P2M1 = 0x00;
P3M0 = 0x00;P3M1 = 0x00;
P4M0 = 0x00;P4M1 = 0x00;
P5M0 = 0x00;P5M1 = 0x00;
P6M0 = 0x00;P6M1 = 0x00;
P7M0 = 0x00;P7M1 = 0x00;
ACC = P_SW1;
ACC &= ~(CCP_S0 | CCP_S1); //CCP_S0=0 CCP_S1=0
P_SW1 = ACC; //(P1.2/ECI, P1.1/CCP0, P1.0/CCP1, P3.7/CCP2)
}
void Timer0Init(void) //@24.000MHz定时器0//24US
{
AUXR |= 0x80; //定时器时钟1T模式
TMOD &= 0xF0; //设置定时器0为模式0(16位自动重装载)
TL0 = (65536-LOWDUTY); //初始化定时器初值和重装值
TH0 = (65536-LOWDUTY) >> 8;
flag = 0; //初始化标志位
TR0 = 1; //定时器0开始计时
ET0 = 1; //使能定时器0中断
TR0 = 1; //定时器0开始计时
PWM=1;
}
void UartInit(void) //115200bps@24.000MHz定时器2
{
SCON = 0x50; //8位数据,可变波特率
AUXR |= 0x01; //串口1选择定时器2为波特率发生器
AUXR |= 0x04; //定时器2时钟为Fosc,即1T
T2L = (65536 - (FOSC/4/BAUD)); //设定定时初值
T2H = (65536 - (FOSC/4/BAUD))>>8;;
AUXR |= 0x10; //启动定时器2
ACC = P_SW1;
ACC &= ~(S1_S0 | S1_S1); //S1_S0=0 S1_S1=0
P_SW1 = ACC; //(P3.0/RxD, P3.1/TxD)
// ES = 1; //使能串口1中断
}
void CCP1_Init()
{
CCON = 0; //初始化PCA控制寄存器//PCA定时器停止//清除CF标志//清除模块中断标志
CL = 0; //复位PCA寄存器
CH = 0;
CCAP1L = 0; //捕获通道0
CCAP1H = 0;
CMOD = 0x09; //设置PCA时钟源为系统时钟24MHz,1分频,且使能PCA计时溢出中断
CCAPM1 = 0x21; //PCA模块0为16位捕获模式(上升沿捕获,可测从高电平开始的整个周期),且产生捕获中断
// CCAPM1 = 0x11; //PCA模块0为16位捕获模式(下降沿捕获,可测从低电平开始的整个周期),且产生捕获中断
// CCAPM1 = 0x31; //PCA模块0为16位捕获模式(上升沿/下降沿捕获,可测高电平或者低电平宽度),且产生捕获中断
CR = 0; //关闭PCA定时器
}
void main()
{
Rising_flag=0;
cnt = 0;
count1 = 0;
GPIO_Init();
Timer0Init();
UartInit();
CCP1_Init();
EA = 1;
SendString("Uart Test !\r\n");
while (1)
{
length = count1/24; //计算为us 1分频
count1 = 0;
CL = 0;
CH = 0;
cnt = 0;
SendData(length%1000000000/100000000+0x30);
SendData(length%100000000/10000000+0x30);
SendData(length%10000000/1000000+0x30);
SendData(length%1000000/100000+0x30);
SendData(length%100000/10000+0x30);
SendData(length%10000/1000+0x30);
SendData(length%1000/100+0x30);
SendData(length%100/10+0x30);
SendData(length%10+0x30);
SendString("uS\r\n");
Delay500ms();
}
}
void PCA_isr() interrupt 7
{
if (CCF1)
{
CCF1 = 0; //PCA模块的中断标志位不会由硬件自动清除,需要软件清除
if (CF && ((CCAP1H & 0x80) == 0))//捕获到有效脉冲信号的同时,发生了溢出中断的问题
{
CF = 0;
cnt++;
}
if(Rising_flag == 0) //捕获到上升沿,开定时器,准备捕获下降沿
{
CR = 1; //PCA定时器开始工作
CCAPM1 = 0x11; //PCA模块0为16位捕获模式(下降沿捕获),且产生捕获中断
Rising_flag = 1;
}
if(Rising_flag == 1) //捕获到下降沿,读取定时器
{
CR = 0;
((BYTE *)&count1)[3] = CCAP1L; //保存本次的捕获值
((BYTE *)&count1)[2] = CCAP1H;
((BYTE *)&count1)[1] = cnt;
((BYTE *)&count1)[0] = 0;
CCAP1H = 0;
CCAP1L = 0;
CCAPM1 = 0x21; //PCA模块0为16位捕获模式(上降沿捕获),且产生捕获中断
Rising_flag = 0;
}
}
if (CF)
{
CF = 0;
CL = 0; //复位PCA寄存器
CH = 0;
cnt++; //PCA计时溢出次数+1
}
}
|