单片机定时器0做pwm输出,定时器1做超声波测距计时。但是不能同时使用,哪位可以帮忙解决下这个问题
- #include "reg52.h"
- #include "intrins.h"
- sbit tr=P1^4;
- sbit echo=P1^3;
- sbit led=P1^5;
- sbit servo=P2^7;
- int num[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};//段选
- int num2[]={0x01,0x02,0x04,0x08};
- int compare, count = 0;
- void Delay10us() //@11.0592MHz
- {
- unsigned char i;
- _nop_();
- i = 25;
- while (--i);
- }
- void display(int a)
- {
- unsigned char i;
- for(i=0;i<4;i++)
- {
- P2=num2[i];
- switch(i)
- {
- case 0:
- P0=num[a/1000];
- break;
- case 1:
- P0=num[a/100%10];
- break;
- case 2:
- P0=num[a/10%10];
- break;
- case 3:
- P0=num[a%10];
- break;
- }
- Delay10us();
- P0=0xff;
- Delay10us();
- }
- }
- void timer0_init(void)
- {
- TMOD=0X11;//定时器模式选择
- EA=1;//总中断
- ET1=1;//定时器1中断
- TH1=0;
- TL1=0;
- TL0 = 0x9c; //设置定时初值
- TH0 = 0xff; //设置定时初值
- TR0=1;//定时器开关
- TR1=0;
- }
- void setangle(int anglenum)
- {
- compare = anglenum + 7;
- }
- void main(void)
- {
- int ss,a=0;
- int i;
- timer0_init();
- loop:tr=1;
- Delay10us();
- Delay10us();
- tr=0;
- while(!echo)
- {
- i++;
- if(i>20)
- {
- goto loop;
- }
- }
- TR1=1;
- while(echo);
- TR1=0;
- ss=(TH1*256+TL1-20)*0.174;
- TH1=0;
- TL1=0;
- display(ss);
- for(i=0;i<6;i++)
- {
- Delay10us();
- }
- if(ss <= 500)
- {
- led = 1;
- }else{
- led = 0;
- }
- setangle(0);
- }
- void timer0() interrupt 1
- {
- count ++;
- if(count <= compare)
- {
- servo = 1;
- }else{
- servo = 0;
- }
- if(count == 200)
- {
- count = 0;
- }
- TL0 = 0x9c; //设置定时初值
- TH0 = 0xff; //设置定时初值
- }
复制代码
|