滚珠开关实验
实验现象
利用滚珠开关的特性,编写一个电动车防盗报警设备
理论学习
滚动开关,当有震动发生的时候,滚珠开关的两个引脚会瞬间接通,arduino通过中断方式获取到该信号,进行蜂鸣器报警
原理图
代码编写
#define key 2
#define buzzer 3
int flag = 0;
int count = 0;
void setup() {
//只是执行1次
pinMode(key,INPUT_PULLUP);
pinMode(buzzer, OUTPUT);
attachInterrupt(0, buzzerDi, FALLING);
Serial.begin(9600);
/*
attachInterrupt()
外部中断函数,只有arduino指定的外部中断口有效
语法:attachInterrupt(interrupt,function,mode);
参数:intertupt:中断号,一般arduino有中断0(数字2口)和中断1(数字3口)
function:中断服务函数,该函数必须没有参数并且返回为空
mode:中断触发模式
1.LOW信号低触发
2.CHANGE 信号翻转触发
3.RISING 信号上升沿触发
4.FALLING 信号下降沿触发
*/
}
void loop() {
//可以执行多次
if (flag == 1) {
flag = 0;
digitalWrite(buzzer,HIGH);
delay(1000);
}
else {
digitalWrite(buzzer,LOW);
}
Serial.println(count);
}
void buzzerDi() {
flag = 1;
count++;
}