#include <zephyr.h>
#include <device.h>
#include <devicetree.h>
#include <drivers/gpio.h>
#include <stdio.h>
#include <hal/nrf_gpio.h>
#include "ADS1231.h"

#define PWDN 21
#define LED1 28
#define LED2 29
#define LED3 30
 
#define YES  1
#define NO  0
int main( void )
{
    ADS1231_status_t        aux;
    ADS1231_pins_t          myADS1231pins;
    Vector_count_t          myData;
    Vector_mass_t           myCalculatedMass;
    Vector_voltage_t        myCalculatedVoltage;
    bool myNewMeasurement;
    
   // conf_GPIO   ();
    //conf_TIMER0 ();
    nrf_gpio_cfg_output(LED1);
    nrf_gpio_cfg_output(LED2);
    nrf_gpio_cfg_output(LED3);

    // Configure the pins to handle the ADS1231 device ( P0.12: #DRDY/DOUT, P0.13: SCLK )
    myADS1231pins = ADS1231_Init ( 19, 20 );

    aux = ADS1231_PowerDown   ( myADS1231pins );
    aux = ADS1231_Reset       ( myADS1231pins );
    k_msleep( 1000 );


    // CALIBRATION time start!
    // 1. REMOVE THE MASS ON THE LOAD CELL ( ALL LEDs OFF ). Read data without any mass on the load cell
    aux = ADS1231_ReadData_WithoutMass ( myADS1231pins, &myData, 4 );

    nrf_gpio_pin_clear(LED1 );
    k_msleep ( 3000 );

    // 2. PUT A KNOWN MASS ON THE LOAD CELL ( JUST LED1 ON ). Read data with an user-specified calibration mass
    aux = ADS1231_ReadData_WithCalibratedMass ( myADS1231pins, &myData, 4 );
    // CALIBRATION time end!


    // [ OPTIONAL ] REMOVE THE MASS ON THE LOAD CELL ( JUST LED2 ON ). Read the device without any mass to calculate the tare weight for 5 seconds
   // NRF_GPIO->OUTSET    =   ( 1UL << LED1 );
    //NRF_GPIO->OUTCLR    =   ( 1UL << LED2 );
    //nrf_delay_ms ( 3000 );
   // NRF_GPIO->OUTSET    =   ( 1UL << LED2 );

    // Calculating the tare weight ( JUST LED3 ON )
   nrf_gpio_pin_clear(LED3 );
    aux = ADS1231_SetAutoTare ( myADS1231pins, 1.0, ADS1231_SCALE_kg, &myData, 5 );
  nrf_gpio_pin_set(LED3 );
    nrf_gpio_cfg_output(PWDN);
    nrf_gpio_pin_clear(PWDN);
    k_msleep ( 3000 );
    nrf_gpio_pin_set(PWDN);
   myNewMeasurement = YES ;
    //NRF_TIMER0->TASKS_START  =   1;                 // Start Timer0

    while( 1 )
    {
        //NRF_POWER->SYSTEMOFF = 1;
       /* NRF_POWER->TASKS_LOWPWR = 1;                // Sub power mode: Low power.

        // Enter System ON sleep mode
		__WFE();
		// Make sure any pending events are cleared
		__SEV();
		__WFE();*/


		if ( myNewMeasurement == YES ){
            

            aux                 =    ADS1231_ReadRawData       ( myADS1231pins, &myData, 4 );
            myCalculatedMass    =    ADS1231_CalculateMass     ( &myData, 1.0, ADS1231_SCALE_kg );
            myCalculatedVoltage =    ADS1231_CalculateVoltage  ( &myData, 5.0 );
           printf("Load in Kg: %f",myCalculatedMass);
            myNewMeasurement    =   NO;

           
		}

        

    }
}