Komunikasi Serial 2 Arduino UNO - Half Duplex

 

Komunikasi Serial 2 Arduino UNO - Half Duplex

Simulasi menggunakan: https://www.tinkercad.com/  

 

VR #1 - menggerakan Servo yang terdapat di Arduino #2

VR #2 - menyalakan LED yang terdapat di Arduino #1

 

Arduino #1

#include <SoftwareSerial.h>

SoftwareSerial SerialBaru(2,3);

const int ledPin =  13;  // Built-in LED
const int EnTxPin =  4;  // HIGH:Transmitter, LOW:Receiver
void setup()
{
  SerialBaru.begin(1200);
  SerialBaru.setTimeout(100);  
  pinMode(ledPin, OUTPUT);
  pinMode(EnTxPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  digitalWrite(EnTxPin, HIGH);
}
 
void loop()
{   
  int rdata = analogRead(0); //data from potentiometer
  int angle= map(rdata, 0, 1023, 0, 180);
 
  //transmitter data packet
  SerialBaru.print("I"); //initiate data packet
  SerialBaru.print("S"); //code for servo
  SerialBaru.print(angle); //servo angle data
  SerialBaru.print("F"); //finish data packet
  delay(50);

  //receiver data packet
  SerialBaru.print("I"); //initiate data packet
  SerialBaru.print("L"); //code for sensor
  SerialBaru.print("F"); //finish data packet
  SerialBaru.flush();    
 
  digitalWrite(EnTxPin, LOW); //RS485 as receiver

  if(SerialBaru.find("i"))
  {
      int data=SerialBaru.parseInt();
      if(SerialBaru.read()=='f') //finish reading
       {
         onLED(data);            
      }
      
  }
  digitalWrite(EnTxPin, HIGH); //RS485 as transmitter
 
}

void onLED(int data)
{
  if(data>500)
     digitalWrite(ledPin, HIGH);
  else
     digitalWrite(ledPin, LOW);
}

Arduino #2

#include <Servo.h>

#include <SoftwareSerial.h>

SoftwareSerial SerialBaru(2,3);

Servo myservo;
const int EnTxPin = 4;
void setup () {
  SerialBaru.begin (1200);
  myservo.attach (9);
  pinMode(EnTxPin, OUTPUT );
  digitalWrite (EnTxPin, LOW );
}

void loop (){
  if ( SerialBaru.available ()){
    if ( SerialBaru.read () == 'I' ){
      char function = SerialBaru.read ();
      if (function == 'S' ){
        int angle = SerialBaru.parseInt ();
        if ( SerialBaru.read () == 'F' ){
          if (angle <= 180) {
            myservo.write (angle);
          }
        }
      }
      else if (function == 'L' ){
        if ( SerialBaru.read () == 'F' ){
          int val = analogRead (0);
          digitalWrite (EnTxPin, HIGH ); //enable to transmit
          SerialBaru.print ( "i" );
          SerialBaru.print (val);
          SerialBaru.println ( "f" );
          SerialBaru.flush ();
          digitalWrite (EnTxPin, LOW ); //enable to receive
        }
      }
    }
  }
  delay (10);
}

 

Ref:

Modbus (RS-485) Using Arduino (create.arduino.cc)