/*******************************************************************************
  Main Source File

  Company:
    Microchip Technology Inc.

  File Name:
    main.c

  Summary:
    This file contains the "main" function for a project.

  Description:
    This file contains the "main" function for a project.  The
    "main" function calls the "SYS_Initialize" function to initialize the state
    machines of all modules in the system
 *******************************************************************************/

// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************

#include <stddef.h>                     // Defines NULL
#include <stdbool.h>                    // Defines true
#include <stdlib.h>                     // Defines EXIT_FAILURE
#include "definitions.h"                // SYS function prototypes
#include "timer.h"
#include "ABP2.h"
#include "i2c1.h"
#include "uart1.h"
#include "maxon.h"
#include "eeprom.h"



#define VER "PIC32 v1.0"
unsigned long AlarmCnt = 0;
unsigned short ABP2Data[8];
unsigned char RxFifo[RxFifoSz]; // The statically allocated FIFO buffer (500 bytes)
//                SCI1 FIFO routines are slightly modified versions from
//                "Embedded Microcomputer Systems: Real Time Interfacing",
//                Jonathan W. Valvano 9/7/00
unsigned char *RxPutPt;    // Pointer of where to put next char in SCI1 FIFO
unsigned char *RxGetPt;    // Pointer of where to get next char from SCI1 FIFO
                  // FIFO is empty if PutPt=GetPt 
                  // FIFO is full  if PutPt+1=GetPt
unsigned short revs;
unsigned short CNticks;

//#define APP_FLASH_ADDRESS (NVM_FLASH_START_ADDRESS + (NVM_FLASH_SIZE / 2)) 
#define APP_FLASH_ADDRESS (NVM_FLASH_START_ADDRESS + (NVM_FLASH_SIZE - NVM_FLASH_PAGESIZE)) 

// Allocate buffer in RAM for eeprom
uint8_t CACHE_ALIGN rowBuffer[NVM_FLASH_ROWSIZE];

//eeprom variables
uint8_t eePosition = 0;
uint16_t eePump = 500;
uint16_t eePurge =  100;
uint16_t eeHome = 0;
uint16_t eeOffset = 3900;



int main ( void )
{
    unsigned char ch;
    unsigned short val;
    char str[15];
    uint32_t data;
    /* Initialize all modules */
    SYS_Initialize ( NULL );
    TMR2_Start();
    
    GPIO_RE5_Set(); //debug
    //GPIO_RF1_Set(); //Turn on ABP2 diff pducer
    
    i2c1_init();
    
    (void)__builtin_disable_interrupts();
    CNENB = 0x100; //enable CN irq on RB8
    (void)__builtin_enable_interrupts();
    
    read_eeprom();

    if(WaitForEpos(5000))
     {
      printf("0x3000:04 now 0x%08lX\n",ReadObject32(MotionDir,MotionDirSubIndex));
      EnableDrive(3000);
     }
    else
     {
      printf("EPOS4 not ready - check power and RS232\n");
     }
    
    printf("\n%s\n",VER);
    while ( true )
    {
        
        printf("S>");
        ch = getchar();
        printf("%c\r\n",ch);
        //printf("TMR2 = %d, AlarmCnt = %lu\n",TMR2_CounterGet(),AlarmCnt);
        //GPIO_RE5_Clear();
        //msWait(100);
        //GPIO_RE5_Set();
        //printf("TMR2 = %d, AlarmCnt = %lu\n",TMR2_CounterGet(),AlarmCnt);
        /* Maintain state machines of all polled MPLAB Harmony modules. */
        //SYS_Tasks ( );
        
        switch(ch) //====================================================
        { // and depending upon the ch, do the appropriate action =======
         case '?' :  break; // causes directory prompt to be displayed
         case ' ' :  break; // wait for another character
         case  -1 :  break; // wait for another character 
         case 'G' : //Get motor position
                    //UART1_Write(VER,10);
                    //vPutStrMaxon ( VER, 10, 1 );
                    //RxStr(12,str,1000,1000);
                    //printf("str = %s\n",str);
                    val = 99;
                    val = GetPosition();
                    printf("Position = %d\n",val);
                    break;
         case 'A' :
                    GPIO_RF1_Set(); //Turn on ABP2 diff pducer
                    msWait(10);
                    ABP2_read();
                    printf("P = %f, T = %f\r\n",ABP2_P_psi(),ABP2_T_degC());
                    GPIO_RF1_Clear();
                    break;
         case 'O' :
                    PumpOn();
                    break;
         case 'F' :
                    PumpOff();
                    break;
         case 'H' :
                    Home(MAXHOMETIME);
                    break;
         case 'S' :
                    sample();
                    break; 
         case 'E' :
                    change_eeprom(10000);
                    break;
         case 'C' :
                    eePosition = 0;
                    write_eeprom();
                    break;
         case '+' :
                    eePosition = eePosition + 1;
                    write_eeprom();
                    break;
         case '-' :
                    eePosition = eePosition -1;
                    write_eeprom();
                    break;
         case 'D' :
                    eePosition = 0;
                    eePump = 500;
                    eePurge = 100;
                    eeHome = 0;
                    eeOffset = 3900;
                    write_eeprom();
                    break;
         case '1' :
                    EnableDrive(3000);
                    break;
          case 'M' : //instrumented single relative move
            {
             long tgt = -3900;
             unsigned short sw;
             int t;

             printf("Before: SW = 0x%04X, Pos = %ld\n",
                    ReadObject(Statusword,0x00),GetPosition32());

             if(!MoveCntsRelative(tgt))
              {
               printf("move not accepted\n");
               break;
              }

             for(t=0; t<10000; t+=200)
              {
               msWait(200);
               sw = ReadObject(Statusword,0x00);
               printf("t=%5d SW=0x%04X Pos=%ld Demand=%ld\n",
                      t,sw,GetPosition32(),(long)ReadObject32(0x6062,0x00));
               if(GETBIT(sw,10)){ printf("target reached\n"); break; }
              }
            }
            break;
         case 'W' :
                    PrintDriveState();
                    break;
         case 'V' :
                    printf("Power supply   = %u (0.1V)\n", ReadObject(0x2200,0x01));
                    printf("Logic supply ok= %u\n",    ReadObject(0x2200,0x02));
                    printf("STO inputs     = 0x%02X\n",ReadObject(0x3202,0x01));
                    PrintDriveState();
                    break;
         case 'R' :
                    RotateSampler();
                    break;
         case 'U' : //show menu and pump times
                    printf("CANON SAMPLER MAXON %s\r\n",VER);
                    printf(" S.ample      :  W.Drv Stat : M.otion test\r\n");
                    printf(" E.eprom vals :  T.est code : C.lear position\r\n");
                    printf(" +.inc pos    :  -.dec pos  : P.osition\r\n");
                    printf(" O.n Pump     :  F. off Pump: G.etMotor Position\r\n");
                    printf(" R.otate tst  :  H.ome      : \r\n");
                    printf(" D.efault eeprom \r\n");
                    printf(" A.BP2 reading: \r\n");
                    printf("Purge revs = %d : Pump revs = %d \r\n",eeRead(ePURGE),eeRead(ePUMP));
                    printf("HOME offset = %d cnts : Bag offset = %d cnts\r\n",eeRead(eHOME),eeRead(eOFFSET));
                    printf("Last position = %d\n",eeRead(ePOS));
                    break;
        default  :  printf(" input unknown \r\n");

       } //==============================================================
        
        //GPIO_RF1_Set(); //Turn on ABP2 diff pducer
        //msWait(10);
        //ABP2_read();
        //printf("P = %f, T = %f\r\n",ABP2_P_psi(),ABP2_T_degC());
        //GPIO_RF1_Clear();
        
        
    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}


/*******************************************************************************
 End of File
*/

