Control relay via my serial

I wondering what wrong with my code, i’m trying to control relay via my serial, for example relay 4 will activate when number 4 has been received by myserial
code :
#define RELAY1 4 //Relay1 to port 4
#define RELAY2 5 //Relay2 to port 5

#include <SoftwareSerial.h>

int incomingByte = 0;

SoftwareSerial mySerial(2,3);

void setup(){
//initialize the arduino data pins for output
pinMode(RELAY1, OUTPUT);
pinMode(RELAY2, OUTPUT);

void loop(){

if (Serial.available() > 0) {
// read the incoming byte:
incomingByte =;

// say what you got:
Serial.print("I received: ");

if(4 == HIGH){ //PIN to port 4
digitalWrite(RELAY1, LOW); //TURN ON RELAY1
delay(1000); //DELAY 1SECOND
digitalWrite(RELAY1, HIGH); //TURN OFF RELAY1

if(5 == HIGH){
digitalWrite(RELAY2, LOW);
digitalWrite(RELAY2, HIGH);



So you happily read the incoming data but don't do anything with it :wink:

Also, HIGH is defined as 1 so your if statements will never evaluate to true.

if(incomingByte == '4')
  activate relay on pin 4

thanks, im new into arduino
so how to turn it off, basically when you hit number '4' relay1 will turned on, when you send another '4' it'll turned off for a second then turned on again

You may find some ideas in Serial Input Basics - simple reliable ways to receive data.


You can read back the status of an output pin. The below uses that, inverts the result and writes it back. So it toggles the output pin.

digitalWrite(yourPin, !digitalRead(yourPin));