项目概述
功能描述
检测靠近时,垃圾桶自动开盖并伴随滴一声,2秒后关盖
发生震动时,垃圾桶自动开盖并伴随滴一声,2秒后关盖
按下按键时,垃圾桶自动开盖并伴随滴一声,2秒后关盖
硬件说明
SG90舵机,超声波模块,震动传感器,蜂鸣器
接线说明
舵机控制口 P2.3 ;
超声波Trig接 P1.5 ;
Echo接 P1.6 ;
蜂鸣器接 P2.0 口 ;
震动传感器接 P3.2口(外部中断0)
编程实现过程
- 舵机和超声波代码整合
舵机用定时器0
超声波用定时器1
实现物体靠近后,自动开盖,2秒后关盖 - 查询的方式添加按键控制
- 查询的方式添加震动控制
- 使用外部中断0配合震动控制
源码
#include "reg52.h"
#include "intrins.h"
sbit led1 = P3^7;
sbit led2 = P3^6;
sbit key1 = P2^1;
sbit shock = P3^2;
sbit Trig = P1^5;
sbit Echo = P1^6;
sbit sg90_Steering = P2^3;
sbit beep = P2^0;
int cnt = 0;
int sg90_angle = 0;
int shock_mark = 0;
int sg90_angle_back = 0;
void Delay10us() //@11.0592MHz
{
unsigned char i;
i = 2;
while (--i);
}
void Delay50ms() //@11.0592MHz
{
unsigned char i, j;
i = 90;
j = 163;
do
{
while (--j);
} while (--i);
}
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 Delay2500ms() //@11.0592MHz
{
unsigned char i, j, k;
_nop_();
i = 18;
j = 131;
k = 103;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void Timer1Init() //[email protected]
{
// AUXR &= 0x7F; //?????12T??
TMOD &= 0x0F; //???????
TMOD |= 0x10; //???????
TL1 = 0; //??????
TH1 = 0; //??????
}
void Timer0Init_500us() //[email protected]
{
// AUXR &= 0x7F; //?????12T??
TMOD &= 0xF0; //???????
TMOD |= 0x01; //???????
TL0 = 0x33;
TH0 = 0xFE;
TF0 = 0; //??TF0??
TR0 = 1; //???0????
ET0 = 1;
EA = 1;
}
void Bo_init()
{
Trig = 0;
Trig = 1;
Delay10us();
Trig = 0;
}
void sg90_close()
{
sg90_angle = 1;
}
void sg90_open()
{
if(sg90_angle_back != sg90_angle)
{
sg90_angle = 3;
beep = 0;
Delay150ms();
beep = 1;
}
}
double getDis()
{
double dis;
double time;
Bo_init();
while(Echo == 0);
TR1 = 1;
while(Echo == 1);
TR1 = 0;
time =( TH1 * 256 + TL1 )* 1.085;
dis = time * 0.017;
return dis;
}
void led_open()
{
led1 = 0;
led2 = 1;
}
void led_close()
{
led1 = 1;
led2 = 0;
}
void int0_init()
{
EX0 = 1;
IT0 = 0;
}
void sg90_init()
{
sg90_Steering = 1;
sg90_angle = 1;
}
void Timer0_Handler() interrupt 1
{
cnt++;
TL0 = 0x33;
TH0 = 0xFE;
if(cnt < sg90_angle)
{
sg90_Steering = 1;
TL0 = 0x33;
TH0 = 0xFE;
}
else
{
sg90_Steering = 0;
TL0 = 0x33;
TH0 = 0xFE;
}
if(cnt == 39)
{
sg90_Steering = 1;
TL0 = 0x33;
TH0 = 0xFE;
cnt = 0;
}
}
void Int0_Handler() interrupt 0 //用外部中断捕获振动传感器的低电平
{
shock_mark = 1;
}
void main()
{
double dis;
Timer1Init();
Timer0Init_500us();
sg90_init();
int0_init();
while(1)
{
dis = getDis();
if(dis < 10 || key1 == 0 || shock_mark == 1) //如果小于10厘米,或者key1按键被按下,或者发生震动
{
led_open();
sg90_open();
Delay2500ms();
shock_mark = 0;
}
else
{
led_close();
sg90_close();
}
TL1 = 0;
TH1 = 0;
Delay50ms();
}
}
标签:蜂鸣器,--,void,51,单片机,while,sbit,angle,sg90
From: https://blog.csdn.net/weixin_46105931/article/details/136990017