Led is connected to pin 12. It is by default at High state. After pressing the switch I want it to be in LOW state for 1 sec and high again. But does become high. Can anyone tell me why delay() is not working? I have to use interrupts because I want to detect negative edge
int pinTx=12;
volatile int state=HIGH;
void setup()
{
pinMode(pinTx,OUTPUT);
attachInterrupt(0,tx,FALLING);
}
void loop()
{
digitalWrite(pinTx,state);
if(state==LOW)
{
digitalWrite(pinTx,state); // turn off the LED
delay(1000); // wait a second
digitalWrite(pinTx,!state); // invert the state i.e. HIGH
state=HIGH; // again state becomes High
}
}
void tx()
{
state=LOW;
}
Hey thanks a lot peeyushsigma for your help. I could run the code successfully. I had a query, Is it necessary to add digitalWrite(pinTx,state) in the IF bloack again as it is already written outside the block. Can you explain me how interrupts work. Is it possible to write the if block in void tx() instead of void loop().
good question sadpony...yes it is necessary to write digitalWrite(pinTx,state); in the IF block, this statement turns off the LED connected to pin no 12 (pintx in your code)...because whenever the interrupt pin is going high to low ( Falling edge) the "void Tx ()" function is executes and change the state to low...you can try this also it will give the same result....
Code:
int pinTx=12;
volatile int state=HIGH;
void setup()
{
pinMode(pinTx,OUTPUT);
digitalWrite(pinTx,state); // initially turn on the LED
attachInterrupt(0,tx,FALLING); // this function tells that the interrupt 0 is attached to tx() function and will execute when falling edge is detected
}
void loop()
{
if(state==LOW)
{
digitalWrite(pinTx,state); // turns off the LED
delay(1000); // wait a second
digitalWrite(pinTx,!state); // invert the state i.e. HIGH ..-> this is necessary to turn on the LED again..
state=!state; // and invert the state now state= HIGH you can also write "state=HIGH" or "state=1"
}
}
void tx() // this function will execute every time when you press the button connected to interrupt pin
{
state=LOW;
}