要注意舵机转动中 延时函数要放在哪里
#include "reg52.h"
sbit D5 = P3^7;//
sbit D6 = P3^6;//
sbit Trig = P1^5;
sbit Echo = P1^6;
sbit sg90_con = P1^1;
int cnt;
int jd;
double time;
void Delay10us() //@11.0592MHz
{
unsigned char i;
i = 2;
while (--i);
}
void Timer1Init() //100??@11.0592MHz
{
TMOD &= 0x0F; //ÉèÖö¨Ê±Æ÷ģʽ
TMOD |= 0x10; //ÉèÖö¨Ê±Æ÷ģʽ
TL1 = 0; //ÉèÖóõÖµ
TH1 = 0; //ÉèÖóõÖµ
}
void Time0Init() // 控制超声波
{
//ÅäÖö¨Ê±Æ÷0 ¹¤×÷ģʽΪ16λ¼Æʱ
TMOD &= 0xF0; //ÉèÖö¨Ê±Æ÷ģʽ
TMOD |= 0x01; //ÉèÖö¨Ê±Æ÷ģʽ
//¸ø³õÖµ£¬¶¨³öÒ»¸ö0.5msÀ´
TL0 = 0x33;
TH0 = 0xFE;
//¿ªÊ¼¼Æʱ
TR0 = 1;
//Çå³ý±êʶλ
TF0 =0;
// ´ò¿ª¶¨Ê±Æ÷0 ÖжÏ
ET0 = 1;
//´ò¿ª×ÜÖÐ¶Ï EA
EA = 1;
}
void startHC()
{
Trig = 0;
Trig = 1;
Delay10us();
Trig = 0;
}
double get_dis() // 超声波测距
{
TL1 = 0; //ÉèÖóõÖµ
TH1 = 0; //ÉèÖóõÖµ
//1.¸øTrig ¶Ë¿ÚÖÁÉÙ10us µÄ¸ßµçƽ
startHC();
//2.EchoÐźţ¬Óɵ͵çƽ±äΪ¸ßµçƽ¿ªÊ¼Ê±·¢ÐźÅ
while(Echo == 0);
TR1 = 1; //¿ªÊ¼¼Æʱ
//3.EchoÐźţ¬Óиߵçƽ±äΪµÍµçƽ½áÊø·¢ÐźÅ
while(Echo == 1);
TR1 = 0; //½áÊø¼Æʱ
//4.¼ÆËãʱ¼ä
time = (TH1*256 +TL1)*1.085 ;
//5.¼ÆËã¾àÀë
return (0.017* time);
}
void OpenTheLed5()
{
D5 = 0;
D6 = 1;
}
void CloseTheLed5()
{
D5 = 1;
D6 = 0;
}
void Delay150ms() //@11.0592MHz
{
unsigned char i, j, k;
//_nop_();
i = 2;
j = 13;
k = 237;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void Delay2000ms() //@11.0592MHz
{
unsigned char i, j, k;
//_nop_();
i = 15;
j = 2;
k = 235;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void opengaizi()
{
jd = 3; //90¡ã
cnt = 0;
Delay2000ms();
}
void closegaizi()
{
jd = 1; // 0¶È
cnt = 0;
Delay150ms();
}
void SG90_Init()
{
jd = 1; // ³õʼ½Ç¶ÈÊÇ 0 ¶È£¬0.5ms£¬Òç³ö1
cnt = 0;
sg90_con = 1; //Ò»¿ªÊ¼´Ó¸ßµçƽ¿ªÊ¼
}
void main()
{
double dis;
Timer1Init();
Time0Init();
SG90_Init();
while(1){
dis = get_dis();
if(dis<10){
OpenTheLed5();
opengaizi(); //
}else{
CloseTheLed5();
closegaizi();
}
}
}
void Time0ZD() interrupt 1 //±¬±íÖ®ºó£¬²»ÔÚÓÃÈí¼þÇåÁ㣬Õâ¸öÖжϽ«±êʶλTF0
{
cnt++;
TL0 = 0x33;
TH0 = 0xFE;
// ¿ØÖÆPWM²¨
if(cnt<jd){
sg90_con = 1;
}else{
sg90_con = 0;
}
if(cnt == 40){ // ËÄÊ®´Î±¬±í£¬¾¹ýÁË20ms£¬Íê³ÉÁËÒ»¸öÖÜÆÚ£
cnt = 0;
sg90_con = 1;
}
}