intpbIn =2;// 定义输入信号引脚intledOut = A0;// 定义输出指示灯引脚intstate = LOW;// 定义默认输入状态voidsetup(){// 设置输入信号引脚为输入状态、输出引脚为输出状态pinMode(pbIn, INPUT);
pinMode(ledOut, OUTPUT);
}voidloop(){
state = digitalRead(pbIn);//读取微动开关状态digitalWrite(ledOut, state);//把读取的状态赋予LED指示灯//模拟一个长的流程或者复杂的任务for(inti =0; i <100; i++)
{//延时10毫秒delay(10);
}
}
intpbIn =0;// 定义中断引脚为0,也就是D2引脚intledOut = A0;// 定义输出指示灯引脚volatileintstate = LOW;// 定义默认输入状态voidsetup(){// 置ledOut引脚为输出状态pinMode(ledOut, OUTPUT);// 监视中断输入引脚的变化attachInterrupt(pbIn, stateChange, CHANGE);
}voidloop(){// 模拟长时间运行的进程或复杂的任务。for(inti =0; i <100; i++)
{// 什么都不做,等待10毫秒delay(10);
}
}voidstateChange(){
state = !state;
digitalWrite(ledOut, state);
}
#include //Timer interrupt function
int pbIn = 0; // Define the interrupt PIN is 0, that is, digital pins 2
int ledOut = 13;
int count=0;
volatile int state = LOW; //Define ledOut, default is off
void setup()
{
Serial.begin(9600);
pinMode(ledOut, OUTPUT);
attachInterrupt(pbIn, stateChange, FALLING); // Sets the interrupt function, falling edge triggered interrupts.
MsTimer2::set(1000,process); // Set the timer interrupt time 1000ms
MsTimer2::start();//Timer interrupt start
}
void loop()
{
Serial.println(count); // Printing times of 1000ms suspension
delay(1);
if(state == HIGH) //When moving objects are detected later, 2s shut down automatically after the ledout light is convenient.
{
delay(2000);
state = LOW;
digitalWrite(ledOut, state); //Turn off led
}
}
void stateChange() //Interrupt function
{
count++;
}
void process() //Timer handler
{
if(count>1) //1000ms interrupt number greater than 1 is considered detected a moving object (this value can be adjusted according to the actual situation, equivalent to adjust the detection threshold of the speed of a moving object)
{
state = HIGH;
digitalWrite(ledOut, state); //Lighting led
count=0; //Count zero
}
else
count=0; //In 1000ms, interrupts does not reach set threshold value is considered not detect moving objects, interrupt the count number is cleared to zero.
}