/*◄■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ EUSARTs.c ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■►*/

// <editor-fold defaultstate="collapsed" desc="Title">
/*════════════════════════════════════════════════════════════════════════════*/
/*                        © John William Darsow                               */
/* Created on  : Tuesday, December 6, 2016                                    */
/* Current Version Date: (see File Date)                                      */
/* Tuesday, May 16, 2017 Combined with EUSART2                                */
/*                                                                            */
/* File        : EUSARTs.c      EUSART1 Generated Driver File                 */
/*                                                                            */
/* For         : LCCnode1.c                                                   */
/* µChip       : PIC18F26K80                                                  */
/* See drawing : LCCnode1.dwg                                                 */
/*                                                                            */
/* This is the generated driver implementation file for the EUSART1 driver    */
/*  using MPLAB(c) Code Configurator, Cleaned up by JWD.                      */
/*  This header file provides implementations for driver APIs for EUSART1.    */
/*════════════════════════════════════════════════════════════════════════════*/
// </editor-fold>

/*═════════════════════════════════ INCLUDEs ═════════════════════════════════*/
#include "EUSARTs.h"

/*═══════════════════════════ FUNCTION  DEFINITIONS ══════════════════════════*/
// <editor-fold defaultstate="collapsed" desc="Functions Definitions">

/*──────────────────────────── INITILIZE EUSART1 ─────────────────────────────*/
void EUSART1_Initialize(void)
{
/* Enhanced Universal Synchronous Asynchronous Receiver Transmitter (EUSART) */
/*------- TXREG1 EUSART TransmitReceive Data Register  -------*/
/*------- RCREG1 EUSART Receive Data Register -------*/
   TRISCbits.TRISC6          = 0b0;         // CCP3 Servo3 / USART1 Tx,  tri-state Output
   TRISCbits.TRISC7          = 0b1;         // CCP4 Servo4 / USART1 Rx,  tri-state Output
//   PIE1bits.RC1IE          = 0b1;         //5 USART1 Receive Interrupt Enable bit
// PIE1bits.TX1IE            = 0b0;         //4 USART1 Transmit Interrupt Enable bit
   IPR1bits.RC1IP            = LOW;         //5 EUSART1 Receive Interrupt Priority
// IPR1bits.TX1IP            = 0b0;         //4 EUSART1 Transmit Interrupt Priority

   // <editor-fold defaultstate="collapsed" desc="TXSTA1">
   /* set byte */
// TXSTA1                     = 0x04;        // Transmit Status & Control Register
// TX9 8-bit; TX9D 0; SENDB sync_break_complete; TXEN disabled; SYNC asynchronous; BRGH hi_speed; CSRC slave_mode; 
   /* or set bits */
// TXSTA1bits.CSRC            = 0b0;         // Clock Source Select bit (Synch mode Only)
   /*
      Asynchronous mode:
         Don?t care
      Synchronous mode:
         1 = Master mode (clock generated internally from BRG)
         0 = Slave mode (clock from external source)
   */
// TXSTA1bits.TX9             = 0b0;         // 9-bit Transmit Enable bit
   /*
      1 = Selects 9-bit transmission
      0 = Selects 8-bit transmission
   */
   TXSTA1bits.TXEN            = 0b1;         // Transmit Enable  bit(1)
   /*
      1 = Transmit enabled
      0 = Transmit disabled
   */
   TXSTA1bits.SYNC            = 0b0;         // EUSART Mode Select bit
   /*
      1 = Synchronous mode
      0 = Asynchronous mode
   */
// TXSTA1bits.SENB            = 0b0;         // Send Break Character bit (Asynch mode Only)
   /*
      Asynchronous mode:
         1 = Send Sync Break on next transmission (cleared by hardware upon completion)
         0 = Sync Break transmission completed
      Synchronous mode:
         Don?t care
   */
   TXSTA1bits.BRGH            = 0b1;         // High Baud Rate Select bit (Asynch mode Only)
   /*
      Asynchronous mode:
         1 = High speed
         0 = Low speed
      Synchronous mode:
         Dont care
   */
   TXSTA1bits.TRMT            = 0b0;         // Transmit Shift Register bit Status
   /*
      1 = TSR empty
      0 = TSR full
   */
// TXSTA1bits.TX9D            = 0b0;         // Ninth bit of Transmit Data bit
   /*
      Can be address/data bit or a parity bit.
   */
   //TXSTA1 </editor-fold>

   // <editor-fold defaultstate="collapsed" desc="RCSTA1">
   /* set byte */
// RCSTA1                     = 0x80;        // 0x19D Receive Status & Control Register
// SPEN enabled; RX9 8-bit; RX9D 0; CREN disabled; ADDEN disabled; SREN disabled; 
   /* or set bits */
// RCSTA1bits.SPEN            = 0b1;         // Serial Port Enable bit [[!! DO THIS LAST !!]]
   /*
      1 = Serial port enabled (configures RX/DT and TX/CK pins as serial port pins)
      0 = Serial port disabled (held in Reset)
   */
// RCSTA1bits.RX9             = 0b0;         // 9-bit Receive Enable bit
   /*
      1 = Selects 9-bit reception
      0 = Selects 8-bit reception
   */
// RCSTA1bits.SREN            = 0b0;         // Single Receive Enable bit (Synch-Master Only)
   /*
      Asynchronous mode:
         Don?t care
      Synchronous mode - Master:
         1 = Enables single receive
         0 = Disables single receive
         This bit is cleared after reception is complete.
      Synchronous mode - Slave
         Don't care
   */
   RCSTA1bits.CREN            = 0b1;         // Continuous Receive Enable bit
   /*
      Asynchronous mode:
         1 = Enables receiver
         0 = Disables receiver
      Synchronous mode:
         1 = Enables continuous receive until enable bit CREN is cleared (CREN overrides SREN)
         0 = Disables continuous receive
   */
// RCSTA1bits.ADDEN           = 0b0;         // Address Detect Enable bit
   /*
      Asynchronous mode 9-bit (RX9 = 1):
         1 = Enables address detection, enable interrupt and load the receive buffer when RSR<8> is set
         0 = Disables address detection, all bytes are received and ninth bit can be used as parity bit
      Asynchronous mode 8-bit (RX9 = 0):
         Don?t care
   */
   RCSTA1bits.FERR;                          // Framing Error bit
   /*
      1 = Framing error (can be updated by reading RCREG register and receive next valid byte)
      0 = No framing error
   */
   RCSTA1bits.OERR;                          // Overrun Error bit
   /*
      1 = Overrun error (can be cleared by clearing bit CREN)
      0 = No overrun error
   */
// RCSTA1bits.RX9D;                          // Ninth bit of Received Data bit
   /*
      This can be address/data bit or a parity bit and must be calculated by user firmware.
   */
   //RCSTA1 </editor-fold>

   // <editor-fold defaultstate="collapsed" desc="BAUDCON1">
   /* set byte */
// BAUDCON1                  = 0x08;        // BAUDCON1 0x19F Baud Rate Control Register
// ABDOVF no_overflow; TXCKP async_non-inverted_sync_falling-edge; BRG16 16bit_generator; WUE disabled; ABDEN disabled; RXDTP not_inverted; 
   /* or set bits */
// BAUDCON1bits.ABDOVF;                     //7 Auto-Baud Detect Overflow bit (Asynch mode Only)
   /*
      Asynchronous mode:
         1 = Auto-baud timer overflowed
         0 = Auto-baud timer did not overflow
      Synchronous mode:
         Don't care
   */
// BAUDCON1bits.RCIDL;                      //6 Receive Idle Flag bit (Asynch mode Only)
   /*
      Asynchronous mode:
         1 = Receiver is Idle
         0 = Start bit has been received and the receiver is receiving
      Synchronous mode:
         Don't care
   */
// BAUDCON1bits.RXDTP        = 0b0;         //5 Received Data Polarity Select bit (Asynchronous mode only)
   /*
      Asynchronous mode:
         1 = Receive data (RXx) is inverted
         0 = Receive data (RXx) is not inverted
   */
// BAUDCON1bits.TXCKP        = 0b0;         //4 Clock and Data Polarity Select bit
   /*
      Asynchronous mode:
         1 = Transmit inverted data to the RB7/TX/CK pin
         0 = Transmit non-inverted data to the RB7/TX/CK pin
      Synchronous mode:
         1 = Data is clocked on rising edge of the clock
         0 = Data is clocked on falling edge of the clock
   */
   BAUDCON1bits.BRG16        = 0b1;         //3 16-bit Baud Rate Generator bit
   /*
      1 = 16-bit Baud Rate Generator is used
      0 = 8-bit Baud Rate Generator is used
   */
// BAUDCON1bits.WUE          = 0b0;         //1 Wake-up Enable bit (Asynch mode Only)
   /*
      Asynchronous mode:
         1 = Receiver is waiting for a falling edge. No character will be received byte RCIF will be set. WUE will
            automatically clear after RCIF is set.
         0 = Receiver is operating normally
      Synchronous mode:
         Don?t care
   */
// BAUDCON1bits.ABDEN        = 0b0;         //0 Auto-Baud Detect Enable bit (Asynch mode Only)
   /*
      Asynchronous mode:
         1 = Auto-Baud Detect mode is enabled (clears when auto-baud is complete)
         0 = Auto-Baud Detect mode is disabled
      Synchronous mode:
         Don't care
   */
   //BAUDCON1 </editor-fold>

   // <editor-fold defaultstate="collapsed" desc="Baud Rate">
   SPBRG1                    = 0x44;        // Baud Rate Generator timer lo byte, for 57,600 @ 8MHz
   SPBRGH1                   = 0x00;        // Baud Rate Generator timer hi byte
   //Baud Rate </editor-fold>

}

/*──────────────────────────── INITILIZE EUSART2 ─────────────────────────────*/
void EUSART2_Initialize(void)
{
/* Enhanced Universal Synchronous Asynchronous Receiver Transmitter (EUSART) */
/*------- TXREG2 EUSART TransmitReceive Data Register  -------*/
/*------- RCREG2 EUSART Receive Data Register -------*/
   TRISDbits.TRISD7          = 0b1;         // USART2 Rx
   TRISDbits.TRISD6          = 0b0;         // USART2 Tx
   PIE3bits.RC2IE            = 0b1;         //5 EUSART2 Receive Interrupt Enable bit
// PIE3bits.TX2IE            = 0b0;         //4 EUSART2 Transmit Interrupt Enable bit
   IPR3bits.RC2IP            = LOW;         //5 EUSART2 Receive Priority Flag
// IPR3bits.TX2IP            = 0b0;         //4 EUSART2 Transmit Interrupt Priority

   // <editor-fold defaultstate="collapsed" desc="TXSTA2">
   /* set byte */
// TXSTA2                     = 0x04;        // Transmit Status & Control Register

// TXSTA2bits.CSRC            = 0b0;         // Clock Source Select bit (Synch mode Only)
   /*
      Asynchronous mode:
         Don?t care
      Synchronous mode:
         1 = Master mode (clock generated internally from BRG)
         0 = Slave mode (clock from external source)
   */
// TXSTA2bits.TX9             = 0b0;         // 9-bit Transmit Enable bit
   /*
      1 = Selects 9-bit transmission
      0 = Selects 8-bit transmission
   */
   TXSTA2bits.TXEN            = 0b1;         // Transmit Enable  bit(1)
   /*
      1 = Transmit enabled
      0 = Transmit disabled
   */
   TXSTA2bits.SYNC            = 0b0;         // EUSART Mode Select bit
   /*
      1 = Synchronous mode
      0 = Asynchronous mode
   */
// TXSTA2bits.SENB            = 0b0;         // Send Break Character bit (Asynch mode Only)
   /*
      Asynchronous mode:
         1 = Send Sync Break on next transmission (cleared by hardware upon completion)
         0 = Sync Break transmission completed
      Synchronous mode:
         Don?t care
   */
   TXSTA2bits.BRGH            = 0b1;         // High Baud Rate Select bit (Asynch mode Only)
   /*
      Asynchronous mode:
         1 = High speed
         0 = Low speed
      Synchronous mode:
         Dont care
   */
   TXSTA2bits.TRMT            = 0b0;         // Transmit Shift Register bit Status
   /*
      1 = TSR empty
      0 = TSR full
   */
// TXSTA2bits.TX9D            = 0b0;         // Ninth bit of Transmit Data bit
   /*
      Can be address/data bit or a parity bit.
   */
   //TXSTA2 </editor-fold>

   // <editor-fold defaultstate="collapsed" desc="RCSTA2">
   /* set byte */
// RCSTA2                     = 0x80;        // Receive Status & Control Register
// SPEN enabled; RX9 8-bit; RX9D 0; CREN disabled; ADDEN disabled; SREN disabled; 
   /* or set bits */
// RCSTA2bits.SPEN            = 0b1;         // Serial Port Enable bit [[!! DO THIS LAST !!]]
   /*
      1 = Serial port enabled (configures RX/DT and TX/CK pins as serial port pins)
      0 = Serial port disabled (held in Reset)
   */
// RCSTA2bits.RX9             = 0b0;         // 9-bit Receive Enable bit
   /*
      1 = Selects 9-bit reception
      0 = Selects 8-bit reception
   */
// RCSTA2bits.SREN            = 0b0;         // Single Receive Enable bit (Synch-Master Only)
   /*
      Asynchronous mode:
         Don?t care
      Synchronous mode - Master:
         1 = Enables single receive
         0 = Disables single receive
         This bit is cleared after reception is complete.
      Synchronous mode - Slave
         Don't care
   */
   RCSTA2bits.CREN            = 0b1;         // Continuous Receive Enable bit
   /*
      Asynchronous mode:
         1 = Enables receiver
         0 = Disables receiver
      Synchronous mode:
         1 = Enables continuous receive until enable bit CREN is cleared (CREN overrides SREN)
         0 = Disables continuous receive
   */
// RCSTA2bits.ADDEN           = 0b0;         // Address Detect Enable bit
   /*
      Asynchronous mode 9-bit (RX9 = 1):
         1 = Enables address detection, enable interrupt and load the receive buffer when RSR<8> is set
         0 = Disables address detection, all bytes are received and ninth bit can be used as parity bit
      Asynchronous mode 8-bit (RX9 = 0):
         Don?t care
   */
   RCSTA2bits.FERR;                          // Framing Error bit
   /*
      1 = Framing error (can be updated by reading RCREG register and receive next valid byte)
      0 = No framing error
   */
   RCSTA2bits.OERR;                          // Overrun Error bit
   /*
      1 = Overrun error (can be cleared by clearing bit CREN)
      0 = No overrun error
   */
// RCSTA2bits.RX9D;                          // Ninth bit of Received Data bit
   /*
      This can be address/data bit or a parity bit and must be calculated by user firmware.
   */
   //RCSTA2 </editor-fold>

   // <editor-fold defaultstate="collapsed" desc="BAUDCON2">
   /* set byte */
// BAUDCON2                  = 0x08;        // Baud Rate Control Register
// ABDOVF no_overflow; TXCKP async_non-inverted_sync_falling-edge; BRG16 16bit_generator; WUE disabled; ABDEN disabled; RXDTP not_inverted; 
   /* or set bits */
// BAUDCON2bits.ABDOVF;                     //7 Auto-Baud Detect Overflow bit (Asynch mode Only)
   /*
      Asynchronous mode:
         1 = Auto-baud timer overflowed
         0 = Auto-baud timer did not overflow
      Synchronous mode:
         Don't care
   */
// BAUDCON2bits.RCIDL;                      //6 Receive Idle Flag bit (Asynch mode Only)
   /*
      Asynchronous mode:
         1 = Receiver is Idle
         0 = Start bit has been received and the receiver is receiving
      Synchronous mode:
         Don't care
   */
// BAUDCON1bits.RXDTP        = 0b0;         //5 Received Data Polarity Select bit (Asynchronous mode only)
   /*
      Asynchronous mode:
         1 = Receive data (RXx) is inverted
         0 = Receive data (RXx) is not inverted
   */
// BAUDCON1bits.TXCKP        = 0b0;         //4 Clock and Data Polarity Select bit
   /*
      Asynchronous mode:
         1 = Transmit inverted data to the RB7/TX/CK pin
         0 = Transmit non-inverted data to the RB7/TX/CK pin
      Synchronous mode:
         1 = Data is clocked on rising edge of the clock
         0 = Data is clocked on falling edge of the clock
   */
   BAUDCON2bits.BRG16        = 0b1;         //3 16-bit Baud Rate Generator bit
   /*
      1 = 16-bit Baud Rate Generator is used
      0 = 8-bit Baud Rate Generator is used
   */
// BAUDCON2bits.WUE          = 0b0;         //1 Wake-up Enable bit (Asynch mode Only)
   /*
      Asynchronous mode:
         1 = Receiver is waiting for a falling edge. No character will be received byte RCIF will be set. WUE will
            automatically clear after RCIF is set.
         0 = Receiver is operating normally
      Synchronous mode:
         Don?t care
   */
// BAUDCON2bits.ABDEN        = 0b0;         //0 Auto-Baud Detect Enable bit (Asynch mode Only)
   /*
      Asynchronous mode:
         1 = Auto-Baud Detect mode is enabled (clears when auto-baud is complete)
         0 = Auto-Baud Detect mode is disabled
      Synchronous mode:
         Don't care
   */
   //BAUDCON2 </editor-fold>

   // <editor-fold defaultstate="collapsed" desc="Baud Rate">
   SPBRG2                    = 0x44;        // Baud Rate Generator timer lo byte, for 57,600 @ 16MHz
   SPBRGH2                   = 0x00;        // Baud Rate Generator timer hi byte
   //Baud Rate </editor-fold>

}

/*═══════════════════════════════ EUSARTs APIs ═══════════════════════════════*/

/*────────────────────── EUSART1 Write for NCE Cab Bus ───────────────────────*/
void EUSART1_Write(Byte txData)
{
    while(!PIR1bits.TX1IF);
    TXREG1 = txData;         // Write the data byte to the USART.
}

/*────────────────────── EUSART1 putch for NCE Cab Bus ───────────────────────*/
void putch1(char txData)
{  // Declared in eusarts.h
    EUSART1_Write(txData);
}

/*──────────────── EUART2 putch for printf(), Console & JMRI ─────────────────*/
void putch(char txData)
{  // Declared in conio.h
    while(!PIR3bits.TX2IF);
    TXREG2 = txData;    // Write the data byte to the USART.
}

/*─────────────────────── EUART2 Send JMRI CAN String ────────────────────────*/
void print2(const Char * data)
{
   uInt8 i = 0;
   
   while(data[i] != NULL)
   {
      while(!PIR3bits.TX2IF);          // Wait till TSR empty before transmitting, or !TXSTAbits.TRMT
      TXREG2 = data[i];                // transmit data via EUSART2
      i++;
   }
}

//Functions Definitions </editor-fold>
