Sender&Reciver Arduino



Sender

#include <Arduino.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); //RX, TX

int buttonPin = 6;
boolean onOff = 0;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  mySerial.begin(9600);
  Serial.begin(9600);
}

void loop() {
 
  int buttonState = digitalRead(buttonPin);//read button state
 
  if(buttonState == 0){//if button is down
    mySerial.println(1111);//send unique code to the receiver to turn on. In this case 1111
    Serial.println("On");
    onOff = 1;//set boolean to 1
  }
  if(buttonState == 1 && onOff == 1){//Verifier to send off signal once
    mySerial.println(0000);//send unique code to the receiver to turn off. In this case 0000

  }
  delay(20);//delay little for better serial communication
}


Reciver

#include <Arduino.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

int ledPin = 13;

void setup() {
  mySerial.begin(9600);
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop() {
   
  if(mySerial.available() > 1){    
    int input = mySerial.parseInt();//read serial input and convert to integer (-32,768 to 32,767)    
    if(input == 1111){//if on code is received
      digitalWrite(ledPin, HIGH);//turn LED on
      Serial.println(input);
    }
    if(input == 0000){//if off code is received
      digitalWrite(ledPin, LOW);//turn LED off
    }
  }
  mySerial.flush();//clear the serial buffer for unwanted inputs    
 
  delay(20);//delay little for better serial communication
 
}