/*
This Arduino Mega code is the data rate translator between the 
  PC and the audio modem
  Written by : Alastair GW0AJU
  Date : 3rd May 2020
 */

#include <EEPROM.h>

char ch_read;
char radio_read;
String mess;
int ptt_flag = 1;
int t = 0;
int ledTx = 11;
int audio_enable = 10;

void setup()

{

    Serial.begin(57600);   // pc link data rate
    Serial3.begin(1200);  // Packet Memo data rate
    pinMode(ledTx, OUTPUT); // tx / rx indicator
    digitalWrite(ledTx, HIGH); // led on
    pinMode(audio_enable, OUTPUT); // ptt in Tx mode
    digitalWrite(audio_enable, LOW); // ptt in Tx mode
    pinMode(8,OUTPUT); 
}

void loop()

{
//fsk_test();
 send_receive_data();
}

void fsk_test()

{
  digitalWrite(audio_enable, HIGH); // activate the Modem audio fsk generaTOR OUTPUT
  digitalWrite(8, HIGH);
  delay(5000);
  digitalWrite(8, LOW);
  delay(5000); 
}

void send_receive_data()

{ 
  do
  {
    Serial.flush();
    if (Serial3.available())
    {
    radio_read = Serial3.read();  // read modem
    Serial.print(radio_read);  // send to PC 
     }
  } while (Serial.available() == 0);


  do   // tx mode
  {
    if ((ptt_flag == 1 ) && (Serial.available() != 0))
    {
    digitalWrite(ledTx, LOW); // ptt in Tx mode  
    delay(250);
    digitalWrite(audio_enable, HIGH); // ptt in Tx mode 
    delay(250);
    ptt_flag = 0; 
    }    

    /*

     * Place here the modem dtmf signalling

     */

    Serial3.flush();

   if (Serial.available())
        {
         ch_read = Serial.read();
         Serial3.write(ch_read);  // send to modem
         Serial.print(ch_read);  // send modem copy to PC         
        }

   if ((ptt_flag == 0 ) && (Serial.available() == 0))
      {   
       delay(250);
       digitalWrite(audio_enable, LOW); // ptt in Tx mode
       delay(250);
       digitalWrite(ledTx, HIGH); // ptt in Rx mode  
       ptt_flag = 1; 
      }

  } while (Serial.available() != 0);
}
