/*******************************************************************************
MPLAB Harmony Application Source File

Company:
Microchip Technology Inc.

File Name:
app.c

Summary:
This file contains the source code for the MPLAB Harmony application.

Description:
This file contains the source code for the MPLAB Harmony application. It
implements the logic of the application's state machine and it may call
API routines of other MPLAB Harmony modules in the system, such as drivers,
system services, and middleware. However, it does not call any of the
system interfaces (such as the "Initialize" and "Tasks" functions) of any of
the modules in the system or make any assumptions about when those functions
are called. That is the responsibility of the configuration-specific system
files.
*******************************************************************************/

// DOM-IGNORE-BEGIN
/*******************************************************************************
Copyright (c) 2013-2014 released Microchip Technology Inc. All rights reserved.

Microchip licenses to you the right to use, modify, copy and distribute
Software only when embedded on a Microchip microcontroller or digital signal
controller that is integrated into your product or third party product
(pursuant to the sublicense terms in the accompanying license agreement).

You should refer to the license agreement accompanying this Software for
additional information regarding your rights and obligations.

SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER
CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR
OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
*******************************************************************************/
// DOM-IGNORE-END


// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************

#include "app.h"

#include "stdio.h"
#include "1lcd_lib_XC32.h"

bool LED = 0;

int delay_Clock = 200000000; //200MHz
char Buf[32];

extern bool Timer_Trigger;

void delay_us(volatile unsigned int usec) //1μsec遅延
{
volatile int count;

count = (int)(delay_Clock/20000000)*usec;


do //実測 at 200MH (Clock=200000000)
{ //delay_us(1000):1000.4μsec delay_us(100):100.6μsec delay_us(10):10.5μsec  delay_us(1):1.5μsec
asm("NOP"); asm("NOP"); asm("NOP"); asm("NOP"); asm("NOP");asm("NOP");
asm("NOP"); asm("NOP"); asm("NOP"); asm("NOP"); asm("NOP"); asm("NOP");

count--;
}while(count != 0);


}



void delay_ms(volatile unsigned int msec) //1msec遅延
{
volatile unsigned int i; //実測:at200MH (Clock=200000000)//delay_ms(1): 1.0006msec delay_ms(100):100.04msec

for(i=0; i<msec; i++)
delay_us(1000);
}


void AdcFunc(void) //AD変換、表示
{
unsigned int AdcValue;
float Volt;

Timer_Trigger = 0;

//AD変換開始 Trigger a conversion
PLIB_ADCHS_GlobalSoftwareTriggerEnable(ADCHS_ID_0);//変換開始(グローバルソフトウェアエッジトリガの場合)
// ADCCON3bits.GSWTRG = 1; //変換開始(グローバルソフトウェアエッジトリガの場合)
//Trigger conversion for ADC inputs that have selected the GSWTRG bit as the trigger signal, either
//through the associated TRGSRC<4:0> bits in the ADCTRGx registers or through the STRGSRC<4:0>
//bits in the ADCCON1 register
//Class1 の場合、"ADCCON1bits.STRGSRC = 0; //スキャン開始トリガなし変換が終了する”(default)にすると
//変換終了後、自動的にサンプリングが実行される。

//変換完了を待つ Wait the conversions to complete
//AN4
while(!PLIB_ADCHS_AnalogInputDataIsReady(ADCHS_ID_0,ADCHS_AN4));
// while (ADCDSTAT1bits.ARDY4 == 0);

//結果の取り出し fetch the result
AdcValue = PLIB_ADCHS_AnalogInputResultGet(ADCHS_ID_0, ADCHS_AN4 );
// AdcValue = ADCDATA4;


lcd_cmd(0x80); //1目の先頭へ

sprintf(Buf,"AdV=%u ",AdcValue); //バッファーに文字列をセット
lcd_str(Buf); // 開始メッセージ1行目表示

Volt =(float)AdcValue/4095*3.3;

lcd_cmd(0xC0); //2行目の先頭へ
sprintf(Buf,"Volt=%.2f[V] ",Volt); //文字列としてバッファーに収納
lcd_str(Buf); // 開始メッセージ1行目表示



}



// *****************************************************************************
// *****************************************************************************
// Section: Global Data Definitions
// *****************************************************************************
// *****************************************************************************

// *****************************************************************************
/* Application Data

Summary:
Holds application data

Description:
This structure holds the application's data.

Remarks:
This structure should be initialized by the APP_Initialize function.

Application strings and buffers are be defined outside this structure.
*/

APP_DATA appData;

// *****************************************************************************
// *****************************************************************************
// Section: Application Callback Functions
// *****************************************************************************
// *****************************************************************************

/* TODO: Add any necessary callback functions.
*/

// *****************************************************************************
// *****************************************************************************
// Section: Application Local Functions
// *****************************************************************************
// *****************************************************************************


/* TODO: Add any necessary local functions.
*/


// *****************************************************************************
// *****************************************************************************
// Section: Application Initialization and State Machine Functions
// *****************************************************************************
// *****************************************************************************

/*******************************************************************************
Function:
void APP_Initialize ( void )

Remarks:
See prototype in app.h.
*/

void APP_Initialize ( void )
{
/* Place the App state machine in its initial state. */
appData.state = APP_STATE_INIT;


/* TODO: Initialize your application's state machine and other
* parameters.
*/



DRV_ADC0_Open();
DRV_ADC_Start();

//レジスタ直接設定の場合
/*
// Configure ADCCON1
ADCCON1 = 0; // No ADCCON1 features are enabled including: Stop-in-Idle, turbo,
ADCCON1bits.STRGSRC = 1; //スキャン開始を グローバルソフトウェアエッジトリガに設定 //ADCCON1bits.STRGSRC = 0; でも可
//ADCCON1bits.STRGSRC = 0; //スキャン開始トリガなし //bit 20-16 STRGSRC<4:0>: Scan Trigger Source Select bits

// CVD mode, Fractional mode and scan trigger source.
// Configure ADCCON2
ADCCON2 = 0; // Since, we are using only the Class 1 inputs, no setting is

// required for ADCDIV
// Initialize warm up time register
ADCANCON = 0;
ADCANCONbits.WKUPCLKCNT = 5; // Wakeup exponent = 32 * TADx

// Clock setting
ADCCON3 = 0;
ADCCON3bits.ADCSEL = 0; //AD変換クロックTclk選択 0:PBCLK3 //1:System Clock //Select input clock source
ADCCON3bits.CONCLKDIV = 1; //分周値 1:1/2 //AD変換制御クロックTq = 2 x Tclk // Control clock frequency is half of input clock
ADCCON3bits.VREFSEL = 0; //リファレンス電圧 Vref+ = AVdd, Vref- = Vss //Select AVdd and AVss as reference source


// Select ADC sample time and conversion clock
//専任ADコンバータ用タイミングレジスタ //Dedicated ADCx Timing Register
//AN4用
ADC4TIMEbits.ADCDIV = 1; //ADC4用制御クロック分周値 1:1/2 Tad0 = 2 x Tq //  ADC4 clock frequency is half of control clock = TAD0
ADC4TIMEbits.SAMC = 5; //サンプリング周期設定 // サンプリング周期= 5 x Tad0 = 5 x 2 x Tq = 5x2x2xTclk //ADC4 sampling time = 5 * TAD0
ADC4TIMEbits.SELRES = 3; //分解能設定 3:12ビット ADC0 resolution is 12 bits


//入力ポート選択 Select analog input for ADC modules, no presync trigger, not sync sampling
ADCTRGMODEbits.SH4ALT = 0; // ADC4入力ポート:AN4 //AN45の場合:ADCTRGMODEbits.SH0ALT = 1

//Input Mode Control Register // データフォーマット Select ADC input mode
//AN4用
ADCIMCON1bits.SIGN4 = 0; //出力フォーマット: unsigned short int //  unsigned data format
ADCIMCON1bits.DIFF4 = 0; //シングルエンド入力 Single ended mode//1:差動入力

// Configure ADCGIRQENx
ADCGIRQEN1 = 0; // No interrupts are used
ADCGIRQEN2 = 0;

// Configure ADCCSSx
ADCCSS1 = 0; // No scanning is used
ADCCSS2 = 0;

//Configure ADCCMPCONx //コンパレータトリガ変換使用せず
ADCCMPCON1 = 0; // No digital comparators are used. Setting the ADCCMPCONx
ADCCMPCON2 = 0; // register to '0' ensures that the comparator is disabled.
ADCCMPCON3 = 0; // Other registers are “don't care”.
ADCCMPCON4 = 0;
ADCCMPCON5 = 0;
ADCCMPCON6 = 0;

// Configure ADCFLTRx //オーバーサンプリングなし
ADCFLTR1 = 0; // No oversampling filters are used.
ADCFLTR2 = 0;
ADCFLTR3 = 0;
ADCFLTR4 = 0;
ADCFLTR5 = 0;
ADCFLTR6 = 0;


//エッジトリガ変換使用せず Set up the trigger sources
ADCTRGSNSbits.LVL4 = 0; // Edge trigger

//変換開始をグローバルソフトウェアエッジトリガに設定 Global software edge Trigger //★★
ADCTRG2bits.TRGSRC4 = 1; //グローバルソフトウェアエッジトリガ設定 //TRGSRC4<4:0>: Trigger Source for Conversion of Analog Input AN4 Select bits
//変換開始を ADCCON3bits.GSWTRG = 1; に設定
//Global software edge Trigger (GSWTRG) Set AN0 to trigger from software.


// Early interrupt
ADCEIEN1 = 0; //割り込みなし // No early interrupt
ADCEIEN2 = 0;

// Turn the ADC on
ADCCON1bits.ON = 1; //ADCモジュール イネーブル

//リファレンス電圧の安定を待つ Wait for voltage reference to be stable
while(!ADCCON2bits.BGVRRDY); // Wait until the reference voltage is ready //BGVRRDY: Band Gap Voltage/ADC Reference Voltage Status b
while(ADCCON2bits.REFFLT); // Wait if there is a fault with the reference voltage

//ADCアナログ回路のクロックON // Enable clock to analog circuit
ADCANCONbits.ANEN4 = 1; // Enable the clock to analog bias

//ADC準備完了を待つ // Wait for ADC to be ready
while(!ADCANCONbits.WKRDY4); // Wait until ADC0 is ready

//ADCデジタル回路ON //Enable the ADC module
ADCCON3bits.DIGEN4 = 1; // Enable ADC4 //必須
*/



lcd_init(); // LCD初期化
lcd_cmd(0b00001100); // カーソル:OFF ブリンク:OFF

lcd_cmd(0x80); //1目の先頭へ
sprintf(Buf,"From Now ");//
lcd_str(Buf); //液晶表示

lcd_cmd(0xC0); //2行目の先頭へ
sprintf(Buf," AD Start !! "); //
lcd_str(Buf); // 開始メッセージ1行目表示

delay_ms(2000);

PLIB_TMR_Period16BitSet(TMR_ID_1,3906); //5 nsec x2 x 3906 x 256 = 9.99936msec = 10msec //インターバル時間
DRV_TMR0_Start();


}


/******************************************************************************
Function:
void APP_Tasks ( void )

Remarks:
See prototype in app.h.
*/

void APP_Tasks ( void )
{

/* Check the application's current state. */
switch ( appData.state )
{
/* Application's initial state. */
case APP_STATE_INIT:
{
bool appInitialized = true;


if (appInitialized)
{

appData.state = APP_STATE_SERVICE_TASKS;
}
break;
}

case APP_STATE_SERVICE_TASKS:
{
if(Timer_Trigger == 1) //AD変換、表示のタイミング
{

AdcFunc(); //AD変換、表示
Timer_Trigger = 0;


if(LED == 0)
{
LED = 1;
LATGbits.LATG15 = 1; //LED ON
}
else
{
LED = 0;
LATGbits.LATG15 = 0; //LED OFF
}

}

break;
}

/* TODO: implement your application state machine.*/


/* The default state should never be executed. */
default:
{
/* TODO: Handle error in application's state machine. */
break;
}
}
}



/*******************************************************************************
End of File
*/