See how much easier it is to read your code when it is indented and has some whitespace between the functions. Use the AutoFormat tool.
#define reone 7 //relay no. 1
#define retwo 6
#define rethree 5
#define refour 4
#define sone A2 // switch no. 1
#define stwo A3
#define sthree A4
#define sfour A5
int val1=0;
int val2=0;
int val3=0;
int val4=0;
void setup()
{
pinMode (reone, OUTPUT);
pinMode (retwo, OUTPUT);
pinMode (rethree, OUTPUT);
pinMode (refour, OUTPUT);
pinMode (sone, INPUT);
pinMode (stwo, INPUT);
pinMode (sthree, INPUT);
pinMode (sfour, INPUT);
}
void loop(){
offline();
}
void offline(){
relay1();
relay2();
relay3();
relay4();
}
void relay1(){
val1 = digitalRead(sone); // read input value and store it
// check whether the input is HIGH (button pressed)
if (val1 == HIGH) {
digitalWrite(reone, HIGH); // turn relay ON
} else {
digitalWrite(reone, LOW);
}
}
void relay2(){
val2 = digitalRead(stwo); // read input value and store it
// check whether the input is HIGH (button pressed)
if (val2 == HIGH) {
digitalWrite(retwo, HIGH); // turn relay ON
} else {
digitalWrite(retwo, LOW);
}
}
void relay3(){
val3 = digitalRead(sthree); // read input value and store it
// check whether the input is HIGH (button pressed)
if (val3 == HIGH) {
digitalWrite(rethree, HIGH); // turn relay ON
} else {
digitalWrite(rethree, LOW);
}
}
void relay4(){
val4 = digitalRead(sfour); // read input value and store it
// check whether the input is HIGH (button pressed)
if (val4 == HIGH) {
digitalWrite(refour, HIGH); // turn relay ON
} else {
digitalWrite(refour, LOW);
}
}
I suspect your problem is due to switch bounce. Do you have external pull-down (or pull-up) resistors on the switch pins. if not the easiest thing is probably to use pinMode(pin, INPUT-PULLUP); to activate the internal pull-up resistors. Then wire your switches so that they pull the pin to GND when closed. Also note that that will mean LOW signifies the switch is closed.
It would also be a good idea to have ashort interval between successive readings of the switches. Have a look at the demo Several Things at a Time
If you want the relay to stay in position until the switch is pressed a second time then you need different code. Have a look at the State Change example that comes with the Arduino IDE.
...R