RELAY NO CONTACT CIRCUIT PROBLEM (SOOOOLVEDDD)

According to the "Button" example of the Arduino i made the same circuit with only one diference. I replace the button with a Normaly Open (NO) relay contact.

I want the serial monitor give me a feedback in each state. So here is my code which is working perfect in the 1st case

const int buttonPin  = 4;     // the pin that the pushbutton is attached to

int buttonState      = 0;     // current state of the button
int lastButtonState  = 0;     // previous state of the button

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);  // initialize the button pin as a input
  
}

void loop() {
  
  buttonState = digitalRead(buttonPin);

  if (buttonState != lastButtonState) {
    
    
    if (buttonState == 1) {
      
      Serial.println("LED IS ON");
    }
      else  {          
      Serial.println("LED IS OFF");
      }      
    
    lastButtonState = buttonState;
  }
  
  
  delay(1000);
}

1 case. With the button everything working fine

2 case. With the NO relay contact it works only once when the relay is energized and the contact is close. Then everything stucks.

i have attached a picture with the circuit diagram.

As the circuit works with the button that means that there is no problem with my code. So is There somethin that i miss in the 2nd circuit?????

button_schem.png

The code and the circuit you posted are correct. Not ideal, but correct.

A pushbutton automatically opens when you release it.
The NO contacts on an energized relay will remain closed until you tell it to do something else in your code.

In your code, consider doing something when a condition "changes".

EDIT: Your relay acts like a SPDT toggle switch. You can simulate this problem with the "Button" example simply by holding the button down ... see what happens.

Thanks for your response...

I m using the 230V AC relay like a button. I mean, i ernergize - de energize it through a switch. So the contacts of the relay acts like a button..

The main problem is that my board (digital input 4 ) looks like couldnt read back the 0 volts (LOW STATE) when the relay de energizes an the contact opens

Is your buttonPIN input floating?
You'll need to use a pullup or pulldown resistor, or use INPUT_PULLUP when configuring the pin.

nothing change with the INPUT_PULLUP... :confused:

You'll need to re-wire your input switch (relay contacts?) so that it connects the input to GND (not 5V).

You can use the original pull down as you posted, or the internal pullup method. Both will work. I suspect you just made a wiring error.

:slight_smile:

I swear the God i didnt make anything different and finaly it works .....

here is the ytube link !!! Thank you all !!!