首先我们通过原理图寻找振动传感器的引脚,原理图如下:
发现振动传感器的引脚V&P在P2.4引脚处,把此引脚定义为输入端口,即将P2^4引脚置1,并不断检测此引脚状态。当振动发生时,振动传感器内部被短接,P2^4引脚的电平为0。
基本使用方法就是这么简单,以下是一个简单的样例代码:
#include <STC15F2K60S2.h>
#include <intrins.h> //_nop_();
#define uchar unsigned char
uchar code arrLed[] = {0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
sbit zd = P2 ^ 4;
sbit led_sel = P2 ^ 3;
void Delay50ms() //@11.0592MHz
{
unsigned char i, j, k;
_nop_();
_nop_();
i = 3;
j = 26;
k = 223;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void Init()
{
P0M0 = 0xff; //led灯要设置成推挽输出
P0M1 = 0x00; //P0口
P2M0 = 0x08; //P2.3
P2M1 = 0x00;
led_sel = 1;
P0 = 0x00;
zd = 1;
}
void main()
{
uchar i = 0;
Init();
while( 1 )
{
if( zd == 0 )
{
i = 0;
while( i < 9 )
{
P0 = arrLed[i];
Delay50ms();
i++;
}
}
else
P0 = 0x00;
}
}
(若有不足和错误,还请各位斧正)