Please Help to fix this Code

Hi All,

I want to work this code as follows:- LED should be ON if there is any vibration and should stay ON for 2 minutes,if there is no vibration detected.At the moment it is ON when there is vibration and stay ON for 2 minutes. And no function is executed while it is ON(No vibration detects).

int vib_pin=7; int led_pin=13; void setup() { pinMode(vib_pin,INPUT); pinMode(led_pin,OUTPUT); }

void loop() { int val; val=digitalRead(vib_pin); digitalWrite(led_pin,LOW); if(val==1) { digitalWrite(led_pin,HIGH); delay(120000); } else digitalWrite(led_pin,LOW); }


Nothing (except interrupts) can happen during a (blocking) delay(). There are examples and tutorials to show you how to use the millis() and/or micros() functions for non-blocking timing.

Beginner's guide to millis(). Several things at a time. Blink without delay().

So how does this code not do what you want it to?

Hi Mate, I works like this

Delay starts soon there is a vibration in vibration sensor. But I wan't the delay start when there is no vibration

You mean, switch on the LED when the vibration stops? Then look at the state change detection example in the IDE. That's what you need here.

No.I will explain you clearly.

I want to turn ON the LED if there is vibration. But should stay ON for two minute when the vibration stops.The two minute delay in turning off should start from the moment when the vibration stops.

As mentioned in reply #4, state change detection.

Switch the led on when the code detects a change from no-vibration to vibration. Switch the led off two minutes after the code detects a change from vibration to no-vibration.

You do not say what needs to happen if a new vibration is detected during the two minutes. If the process needs to cancel the wait, see the links in reply #1.

Hi Mate, If new vibration detects during two minute wait,then LED should be ON continuously

From the previous replies, you should have enough ammunition to try to tackle the problem.

When you get stuck, post your attempt an people will try to help you.