此程序通过两个定时器一个外部中断,测量PWM高电平时间以及周期,计算并在1602显示出占空比 周期 高电平时间,只需让脉冲在P3^2口输入即能测得数据。。
单片机源程序如下:
- #include <reg52.h>
- #include <LCD1602.h>
- typedef unsigned char uint8;
- typedef unsigned int uint16;//数据类型重定义
- uint8 count = 0; //计进入外部中断次数
- bit flag = 1; //捕获结束标志位
- long Pwm_All; //PWM的周期
- long Pwm_High; //PWM的高电平时间 占空比=Pwm_High/Pwm_All
- void delay(long i)
- {
- while(i--);
- }
- void Interrupt_Init()
- {
- /*定时器1为工作模式1 16位计数器 由TR1直接启动
- 定时器0为工作模式1 16位计数器 由GATE和TR0共同启动*/
- TMOD = 0x19;
-
- TH1 = 0;
- TL1 = 0;
- TH0 = 0;
- TL0 = 0;
-
- IT0 = 1;//下降沿触发
- IT1 = 1;
- //TR0 = 1; //GATE高电平启动
-
- EX0 = 1;
- EA = 1;
- }
- void main()
- {
- uint16 Pwm_percentage; //PWM占空比
- Interrupt_Init();
- LCD1602_Initialize( );
- LCD1602_PrintString(1,1,"ALL:");
- LCD1602_PrintString(1,10,"us");
- LCD1602_PrintString(2,1,"HIGH:");
- LCD1602_PrintString(2,11,"us");
- while(1)
- {
-
- if(flag)
- {
- Pwm_percentage = Pwm_High*1000 / Pwm_All;
- LCD1602_PrintChar(1,12,0x30+Pwm_percentage/100);
- LCD1602_PrintChar(1,13,0x30+Pwm_percentage%100/10);
- LCD1602_PrintChar(1,14,'.');
- LCD1602_PrintChar(1,15,0x30+Pwm_percentage%10);
- LCD1602_PrintChar(1,16,'%');
-
- LCD1602_PrintChar(1,5,0x30+Pwm_All/10000);
- LCD1602_PrintChar(1,6,0x30+Pwm_All%10000/1000);
- LCD1602_PrintChar(1,7,0x30+Pwm_All%1000/100);
- LCD1602_PrintChar(1,8,0x30+Pwm_All%100/10);
- LCD1602_PrintChar(1,9,0x30+Pwm_All%10);
- LCD1602_PrintChar(2,6,0x30+Pwm_High/10000);
- LCD1602_PrintChar(2,7,0x30+Pwm_High%10000/1000);
- LCD1602_PrintChar(2,8,0x30+Pwm_High%1000/100);
- LCD1602_PrintChar(2,9,0x30+Pwm_High%100/10);
- LCD1602_PrintChar(2,10,0x30+Pwm_High%10);
- flag = 0; //计算完一次清零
- }
- delay(70000);
- }
-
- }
- void EXTI0 () interrupt 0
- {
- count++;
- if(count == 1) //第一次下降沿,启动定时器1
- {
- TR1 = 1;
- TR0 = 1;
- }
- if(count == 2) //第二次下降沿,一整个周期完毕
- {
- EX0 = 0; //关闭外部中断,防止被其他打断计算
- TR1 = 0; //周期停止计数
- TR0 = 0; //高电平时间停止计数
- Pwm_All = TH1; //获取数据
- Pwm_All = (Pwm_All<<8)+TL1;
- Pwm_High = TH0;
- Pwm_High = (Pwm_High<<8)+TL0;
- TH1 = 0; //清零为下一次做准备
- TL1 = 0;
- TH0 = 0;
- TL0 = 0;
- count = 0;
- flag = 1;
- EX0 = 1; //开启下一次计算
- TR1 = 0;
- TR0 = 0;
- }
-
- }
复制代码
所有资料51hei提供下载:
PWM捕获占空比.zip
(45 KB, 下载次数: 406)
|