/**
 * Copyright (c) 2015 - 2019, Nordic Semiconductor ASA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 *
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 *
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

//////////////////////////////////////////////////////////////////////////////////
// Francisco Zurita
// 20 Feb 2022  
// Description: Part of Supplementary Information code to modulate output frequeny
// given an analog input signal.
//////////////////////////////////////////////////////////////////////////////////


#include <nrf.h>
#include "nrf_drv_saadc.h"
#include "nrf_gpiote.h"
#include "nrf_gpio.h"
#include "nrf_drv_gpiote.h"
#include "nrf_drv_ppi.h"
#include "nrf_drv_timer.h"
#include "SEGGER_RTT.h"
#include "nrf_delay.h"
#include "boards.h"
#include "bsp.h"
#include "nrf_error.h"
#include "nordic_common.h"

//#define SAMPLES_IN_BUFFER 8 //
//TODO: CRUCIAL CHANGE

#define SAMPLES_IN_BUFFER 1
volatile uint8_t state = 1;

static nrf_saadc_value_t     m_buffer_pool[2][SAMPLES_IN_BUFFER];
static uint32_t              m_adc_evt_counter;
static uint16_t              sample;
static uint16_t              sample_clip_high = 250000;
static uint16_t              sample_clip_low = 550;
static uint16_t              amplification = 300;

#define GPIO_OUTPUT_PIN_NUMBER 26  /**< Pin number for stimulation output. */


uint32_t period[4]   = {0, 0, 0, 0};
uint32_t repetitions = 0;

/****************/
/* DECLARATIONS */
/****************/

void ppi_init();

/***********************/
/* END OF DECLARATIONS */
/***********************/



/**************/
/* TIMER PART */
/**************/


void timer_init(void)

{
  
  // Start HFCLK from crystal oscillator. The radio needs crystal to function correctly.
  NRF_CLOCK->TASKS_HFCLKSTART = 1;
  while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0);

  // 32-bit timer
  NRF_TIMER0->BITMODE = TIMER_BITMODE_BITMODE_32Bit << TIMER_BITMODE_BITMODE_Pos;

  // 1us timer period
  NRF_TIMER0->PRESCALER = 4 << TIMER_PRESCALER_PRESCALER_Pos;

  // 1000 us compare value, generates EVENTS_COMPARE[0]
  NRF_TIMER0->CC[0] = 100;
  NRF_TIMER0->CC[1] = 200; // duration of the pulses = 100 microseconds
  NRF_TIMER0->CC[2] = sample_clip_high; // initial frequency = 4 Hz, 250000 microseconds.

  // Enable IRQ on EVENTS_COMPARE[0] and EVENTS_COMPARE[1]
  NRF_TIMER0->INTENSET = TIMER_INTENSET_COMPARE0_Enabled << TIMER_INTENSET_COMPARE0_Pos;

  NRF_TIMER0->INTENSET = TIMER_INTENSET_COMPARE1_Enabled << TIMER_INTENSET_COMPARE1_Pos;

  // Clear the timer when COMPARE0 event is triggered
  NRF_TIMER0->SHORTS = TIMER_SHORTS_COMPARE2_CLEAR_Enabled << TIMER_SHORTS_COMPARE2_CLEAR_Pos;


  NVIC_EnableIRQ(TIMER0_IRQn);
//  NRF_TIMER0->TASKS_START = 1;
}


// This IRQ handler will trigger every 1000us
void TIMER0_IRQHandler(void)
{
  if (NRF_TIMER0->EVENTS_COMPARE[0] == 1)
  {
    NRF_GPIOTE->TASKS_OUT[0] = 1;
    NRF_TIMER0->EVENTS_COMPARE[0] = 0;
//    SEGGER_RTT_WriteString(0,"Tick 1\n");
  }

  if (NRF_TIMER0->EVENTS_COMPARE[1] == 1)
  {
    NRF_GPIOTE->TASKS_OUT[0] = 1;
    NRF_TIMER0->EVENTS_COMPARE[1] = 0;
    if (sample > 10000)
    {
        sample = 0;
    }
    if (sample > 550)
    {
        sample = 550;
    }
    NRF_TIMER0->CC[2] = sample_clip_high - NRF_TIMER0->CC[1] + NRF_TIMER0->CC[0] - sample * amplification;
//    SEGGER_RTT_WriteString(0,"Tick 2\n");
    SEGGER_RTT_printf(0,"Sample: %d\n", sample);
  }
}


void timer_rec_init(void)

{
  
  // Start HFCLK from crystal oscillator. The radio needs crystal to function correctly.
  if (NRF_CLOCK->TASKS_HFCLKSTART != 1)
    NRF_CLOCK->TASKS_HFCLKSTART = 1;
  while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0);

  // 32-bit timer
  NRF_TIMER1->BITMODE = TIMER_BITMODE_BITMODE_32Bit << TIMER_BITMODE_BITMODE_Pos;

  // 1us timer period
  NRF_TIMER1->PRESCALER = 4 << TIMER_PRESCALER_PRESCALER_Pos;

  // 1000 us compare value, generates EVENTS_COMPARE[0]
  NRF_TIMER1->CC[0] = sample_clip_low;

  // Enable IRQ on EVENTS_COMPARE[0] and EVENTS_COMPARE[1]
//  NRF_TIMER0->INTENSET = TIMER_INTENSET_COMPARE0_Enabled << TIMER_INTENSET_COMPARE0_Pos;
//
//  NRF_TIMER0->INTENSET = TIMER_INTENSET_COMPARE1_Enabled << TIMER_INTENSET_COMPARE1_Pos;

  // Clear the timer when COMPARE0 event is triggered
  NRF_TIMER1->SHORTS = TIMER_SHORTS_COMPARE0_CLEAR_Enabled << TIMER_SHORTS_COMPARE0_CLEAR_Pos;


  NVIC_EnableIRQ(TIMER1_IRQn);
//  NRF_TIMER1->TASKS_START = 1;
}
/*********************/
/* END OF TIMER PART */
/*********************/


/**************/
/* SAADC PART */
/**************/


void saadc_callback(nrf_drv_saadc_evt_t const * p_event)
{
    if (p_event->type == NRF_DRV_SAADC_EVT_DONE)
    {
        ret_code_t err_code;

        err_code = nrf_drv_saadc_buffer_convert(p_event->data.done.p_buffer, SAMPLES_IN_BUFFER);

//        NRF_RADIO->PACKETPTR = (uint32_t)&p_event->data.done.p_buffer[0];
        sample = (uint32_t)p_event->data.done.p_buffer[0];

        m_adc_evt_counter++;

        NRF_SAADC->EVENTS_END = 0;
//        SEGGER_RTT_WriteString(0,"Sample!\n");
    }
}

void saadc_init(void)
{
    ret_code_t err_code;
    nrf_saadc_channel_config_t channel_config =
        NRF_DRV_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN0);

    err_code = nrf_drv_saadc_init(NULL, saadc_callback);

    err_code = nrf_drv_saadc_channel_init(0, &channel_config);

    err_code = nrf_drv_saadc_buffer_convert(m_buffer_pool[0], SAMPLES_IN_BUFFER);

    err_code = nrf_drv_saadc_buffer_convert(m_buffer_pool[1], SAMPLES_IN_BUFFER);  
}


/*********************/
/* END OF SAADC PART */
/*********************/

/************/
/* PPI PART */
/************/

#define PPI_CHANNEL1 (0)
#define PPI_CHANNEL2 (1)
#define PPI_CHANNEL3 (2)


void ppi_init()
{

//  NRF_PPI->CH[PPI_CHANNEL2].EEP = (uint32_t)&NRF_TIMER0->EVENTS_COMPARE[0];
//  NRF_PPI->CH[PPI_CHANNEL2].TEP = (uint32_t)&NRF_GPIOTE->TASKS_OUT[0];
//  
//  NRF_PPI->CH[PPI_CHANNEL3].EEP = (uint32_t)&NRF_TIMER0->EVENTS_COMPARE[1];
//  NRF_PPI->CH[PPI_CHANNEL3].TEP = (uint32_t)&NRF_GPIOTE->TASKS_OUT[0];

//  NRF_PPI->CHENSET = (1UL << PPI_CHANNEL2);
//  NRF_PPI->CHENSET = (1UL << PPI_CHANNEL3);

  NRF_PPI->CH[PPI_CHANNEL1].EEP = (uint32_t)&NRF_TIMER1->EVENTS_COMPARE[0];
  NRF_PPI->CH[PPI_CHANNEL1].TEP = (uint32_t)&NRF_SAADC->TASKS_SAMPLE;
  NRF_PPI->CHENSET = (1UL << PPI_CHANNEL1);

}

/*******************/
/* END OF PPI PART */
/*******************/


/***************/
/* GPIOTE PART */
/***************/

void gpiote_init()
{
  NRF_GPIOTE->CONFIG[0] = GPIOTE_CONFIG_MODE_Task << GPIOTE_CONFIG_MODE_Pos | 
                          GPIOTE_CONFIG_POLARITY_Toggle << GPIOTE_CONFIG_POLARITY_Pos | 
                          GPIO_OUTPUT_PIN_NUMBER << GPIOTE_CONFIG_PSEL_Pos | 
                          GPIOTE_CONFIG_OUTINIT_Low << GPIOTE_CONFIG_OUTINIT_Pos;

}

/**********************/
/* END OF GPIOTE PART */
/**********************/


static bsp_indication_t actual_state =  BSP_INDICATE_FIRST;         /**< Currently indicated state. */

/* BSP Part */
/**@brief Function for handling bsp events.
 */
void bsp_evt_handler(bsp_event_t evt)
{
    uint32_t err_code;
    switch (evt)
    {
        case BSP_EVENT_KEY_0:
            NRF_TIMER0->TASKS_START = 1;
            break;

        case BSP_EVENT_KEY_1:
            NRF_TIMER0->TASKS_START = 1;
            break;

        default:
            return; // no implementation needed
    }
}


/**@brief Function for initializing low frequency clock.
 */
void clock_initialization()
{
    NRF_CLOCK->LFCLKSRC            = (CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos);
    NRF_CLOCK->EVENTS_LFCLKSTARTED = 0;
    NRF_CLOCK->TASKS_LFCLKSTART    = 1;

    while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0)
    {
        // Do nothing.
    }
}


/**@brief Function for initializing bsp module.
 */
void bsp_configuration()
{
    uint32_t err_code;

    err_code = bsp_init(BSP_INIT_LEDS | BSP_INIT_BUTTONS, bsp_evt_handler);
}
/* END OF BSP PART */


int main(void)
{
//  clock_initialization();
//  app_timer_init();
//  bsp_configuration();

  timer_init();
  timer_rec_init();
  saadc_init();
  gpiote_init();
  ppi_init();

  NRF_TIMER0->TASKS_START = 1;
  NRF_TIMER1->TASKS_START = 1;

  
  while (1)
  {
        __SEV();
        __WFE();
        __WFE();
  }
}