light swtich and realys to control 220v ac

(IT works for a few times and randomly gives that error)

HI All,

This is my first post so forgive me if this question is answered I could not find a related topic. I have an Arduino UNO and 220v controling relay. What I am trying to do is to use the relay to turn on and off the switch. the way I have set it up is show in the attached diagram.

I am trying to use the serial connection and the input of pin 7 to drive the arduino
When I am trying to use this sketch to turn led on pin 13 it works,but as soon as I connect the relay the arduino resets.

const int ledPin = 13; // the pin that the LED is attached to
const int btn = 7;

int val;
int brightness;
int pstate;

void setup()
{
// initialize the serial communication:
Serial.begin(9600);
// initialize the ledPin as an output:
pinMode(ledPin, OUTPUT);
pinMode(btn,INPUT);

}
void loop() {
val = digitalRead(btn); // read input value and store it in val
if(pstate!=val){
if (val == LOW) { // check if the button is pressed
digitalWrite(ledPin, HIGH); // turn LED on
Serial.println(" Switch on led 13 ON “);
}
if (val == HIGH) { // check if the button is not pressed
digitalWrite(ledPin, LOW); // turn LED off
Serial.println(” Switch off led 13 OFF ");
}
pstate = val;
}

// check if data has been sent from the computer:
if (Serial.available()) {
// read the most recent byte (which will be from 0 to 255):
brightness = Serial.read();
// set the brightness of the LED:
if (brightness == ‘H’){
digitalWrite(ledPin,HIGH);
Serial.println(" H rericeved from laptop led 13 ON “);
}
if (brightness == ‘L’){
digitalWrite(ledPin, LOW);
Serial.println(” L rericeved from laptop led 13 OFF ");

}

}
delay(100);
}

here is the error i get when i connect the relays to the arduino

Error inside Serial.serialEvent()
java.io.IOException: Input/output error in nativeavailable
at gnu.io.RXTXPort.nativeavailable(Native Method)
at gnu.io.RXTXPort$SerialInputStream.available(RXTXPort.java:1598)
at processing.app.Serial.serialEvent(Serial.java:215)
at gnu.io.RXTXPort.sendEvent(RXTXPort.java:774)
at gnu.io.RXTXPort.eventLoop(Native Method)
at gnu.io.RXTXPort$MonitorThread.run(RXTXPort.java:1643)

I think the issue is due to the 5v running through 2 circuits. I am not sure how to solve this.

An Arduino output does not provide enough current to control a relay, and you could damage or destroy the Arduino by trying.

http://www.arduino.cc/playground/uploads/Learning/relays.pdf