Arduino Mega resets when using relay

int val= 0;
void setup() {
  // put your setup code here, to run once:
pinMode(29, INPUT);
pinMode(20, OUTPUT);
digitalWrite(20, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  val = digitalRead(29);
  if (val == HIGH)
  {
    digitalWrite(20, LOW);
  }
  val = digitalRead(29);
  if (val == LOW)
  {
    digitalWrite(20, HIGH);
  }

}

Hi All, need a bit of help with my arduino mega. I'm relatively new, so not got the best coding skills.
Attached is my schematic.
I have a push button which controls a relay, when pushed, the relay turns on and when released, the relay turns off. This works well, but the only issue is when I connect 12v to the output side of the relay, when the relay is turned on it causes the mega to reset, which for my other code is an issue.

I've tried it without the 12v supply and it works fine, any ideas how i can get it to work all the time?

Thanks

val can only be HIGH or LOW. You only need to check it once.

  val = digitalRead(29);
  if (val == HIGH) {
    digitalWrite(20, LOW);
  } else {
    digitalWrite(20, HIGH);
  }

But I suspect wiring is your issue. Can you please expand our diagram to include the power source?

Hi, the power source is a 12v dc wall adapter. 12v+ is connected to COM on the relay and then the output from the relay is connected to NO on the relay.

It resets when you push the button?
I see no resistors puling your button. Have you seen the button tutorial?

The button doesn't have a resistor, as all of the other buttons I have used in my projects never need them.

Your code is fine.
Please post a picture of the entire project so the wiring can be properly checked.

Use a kick back diode for inductive loads.

I've now worked out that the issue comes when I digitalWrite(20, HIGH); this then causes the mega to reset. Wiring is fine, as I have 3 other relays set up the same and they work fine.

It shouldn't.

Apparently not.

1 Like