#include <SoftwareSerial.h>

// Create software serial object to communicate with SIM800L
SoftwareSerial mySerial(18, 19); // SIM800L Tx & Rx is connected to Arduino #3 & #2

void setup() {
  // Begin serial communication with Arduino and Serial Monitor
  Serial.begin(9600);
  
  // Begin serial communication with Arduino and SIM800L
  mySerial.begin(9600);

  Serial.println("Initializing..."); 
  delay(1000);

  mySerial.println("AT"); // Handshake test
  updateSerial();

  Serial.println("Enter 'C' to Call or 'S' to Send SMS:");
}

void loop() {
  if (Serial.available()) {
    char input = Serial.read();
    if (input == 'C' || input == 'c') {
      makeCall();
    } else if (input == 'S' || input == 's') {
      sendSMS();
    }
  }
}

void makeCall() {
  Serial.println("Dialing...");
  mySerial.println("ATD+918007415368;"); // Change number accordingly
  updateSerial();
  delay(20000); // Wait for 20 seconds
  mySerial.println("ATH"); // Hang up
  updateSerial();
  Serial.println("Call ended.");
}

void sendSMS() {
  Serial.println("Sending SMS...");
  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+918007415368\""); // Change number accordingly
  updateSerial();
  mySerial.print("Hello, this is a test message."); // SMS content
  updateSerial();
  mySerial.write(26);
  Serial.println("SMS Sent.");
}

void updateSerial() {
  delay(500);
  while (Serial.available()) {
    mySerial.write(Serial.read());
  }
  while (mySerial.available()) {
    Serial.write(mySerial.read());
  }
}
