Hello everybody,
I have bought this vibration sensor: http://i40.tinypic.com/vpksxh.jpg
At first I thought that it will work like a button(if vibrates it give digital HIGH, else LOW).
But in reality it works only with this code:
#define SensorLED 13
#define SensorINPUT 2
unsigned char state = 0;
void setup()
{
pinMode(SensorLED, OUTPUT);
pinMode(SensorINPUT, INPUT);
attachInterrupt(0, blink, FALLING);//D2 interface: interrupt 0. call blink()
}
void loop()
{
if(state!=0)
{
state = 0;
digitalWrite(SensorLED,HIGH);
delay(500);
}
else
digitalWrite(SensorLED,LOW);
}
void blink()//when input falling edge, this interrupt function works.
{
state++;
}
//the result is the LED( PIN 13 ) will light 500ms after the Shock.
Can somebody explain me how this code works? Is it possible to change sensors sensitivity with the code?
Thank you very much!
The interrupt routine is activated whenever pin 2 goes from HIGH to LOW, and increments the counter called "state".
The loop() code checks state every half second and if its not zero (indicating some joggling of the sensor in that 1/2 second) it turns the LED on (and clears the state back to zero).
This code is not perfect (for instance if there are 256 joggles of the sensor state wraps round to zero again and it will miss it).