/**
 * Copyright (c) 2014 - 2020, 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.
 *
 */
/** @file
 *
 * @defgroup blinky_example_main main.c
 * @{
 * @ingroup blinky_example
 * @brief Blinky Example Application main file.
 *
 * This file contains the source code for a sample application to blink LEDs.
 *
 */

#include <stdbool.h>
#include <stdint.h>
#include "nrf_delay.h"
#include "boards.h"
#include "nrf_saadc.h"

#define BUF_SIZE 250

static nrf_saadc_value_t s_buf[BUF_SIZE];

void SAADC_IRQHandler(void) {
    // With BUF_SIZE set to 250 and sampling with 16x oversampling and 5 us
    // acquisition + sampling time give a total of 250 * 16 * 5 = 20000 us =
    // 20 ms. Thus after 20 ms there shouldn't be possible for the SAADC to
    // generate any events that could trigger the IRQ. So by delaying the
    // IRQHandler with 20 ms it should clear all events in a single go and
    // there wouldn't any further calls to the IRQ handler.
    //
    // However, this doesn't seem to be true, the IRQ handler is called
    // repeatedly even after clearing all events.
    //
    // Removing the 20 ms delay should still not block the main thread by more than
    // a maximum the number of events times 1 us.
    // 1 STARTED
    // 1 END
    // 250 RESULTDONE
    // 16 * 250 DONE
    // Total time 1 + 1 + 250 + 16 * 250 = 4252 us
    //
    //
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    // Try to disable this to get slow blinking of LEDs instead of no
    // blinking at all.
    nrf_delay_ms(20);
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    if (nrf_saadc_event_check(NRF_SAADC_EVENT_END)) {
        nrf_saadc_event_clear(NRF_SAADC_EVENT_END);
        // Simulate some work
        nrf_delay_us(1);
        // Invert LED to indicate the END event
        bsp_board_led_invert(3);
    }

    if (nrf_saadc_event_check(NRF_SAADC_EVENT_STARTED)) {
        nrf_saadc_event_clear(NRF_SAADC_EVENT_STARTED);
        // Simulate some work
        nrf_delay_us(1);
    }

    if (nrf_saadc_event_check(NRF_SAADC_EVENT_RESULTDONE)) {
        nrf_saadc_event_clear(NRF_SAADC_EVENT_RESULTDONE);
        // Simulate some work
        nrf_delay_us(1);
    }

    if (nrf_saadc_event_check(NRF_SAADC_EVENT_DONE)) {
        nrf_saadc_event_clear(NRF_SAADC_EVENT_DONE);
        // Simulate some work
        nrf_delay_us(1);
    }

}

void sensor_init(void) {
    nrf_saadc_resolution_set(NRF_SAADC_RESOLUTION_14BIT);
    nrf_saadc_oversample_set(NRF_SAADC_OVERSAMPLE_16X);
    nrf_saadc_continuous_mode_enable(16 * 16 * (2 + 3));

    nrf_saadc_int_disable(NRF_SAADC_INT_ALL);
    nrf_saadc_int_enable(NRF_SAADC_INT_END);
    nrf_saadc_int_enable(NRF_SAADC_INT_STARTED);

    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    // Try to disable these two and the flashing of LED1 and LED2 increase in
    // frequency.
    nrf_saadc_int_enable(NRF_SAADC_INT_RESULTDONE);
    nrf_saadc_int_enable(NRF_SAADC_INT_DONE);
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


    nrf_saadc_event_clear(NRF_SAADC_EVENT_END);
    nrf_saadc_event_clear(NRF_SAADC_EVENT_STARTED);
    nrf_saadc_event_clear(NRF_SAADC_EVENT_RESULTDONE);
    nrf_saadc_event_clear(NRF_SAADC_EVENT_DONE);

    NRFX_IRQ_PRIORITY_SET(SAADC_IRQn, 6);
    NRFX_IRQ_ENABLE(SAADC_IRQn);

    nrf_saadc_enable();

    nrf_saadc_channel_config_t config = {
            .resistor_p = NRF_SAADC_RESISTOR_DISABLED,
            .resistor_n = NRF_SAADC_RESISTOR_DISABLED,
            .gain       = NRF_SAADC_GAIN1_5,
            .reference  = NRF_SAADC_REFERENCE_INTERNAL,
            .acq_time   = NRF_SAADC_ACQTIME_3US,
            .mode       = NRF_SAADC_MODE_DIFFERENTIAL,
            .burst      = NRF_SAADC_BURST_ENABLED,
            .pin_p      = NRF_SAADC_INPUT_AIN3,
            .pin_n      = NRF_SAADC_INPUT_AIN4,
    };
    nrf_saadc_channel_init(0, &config);
    nrf_saadc_buffer_init(s_buf, BUF_SIZE);

    nrf_saadc_task_trigger(NRF_SAADC_TASK_START);
    nrf_saadc_task_trigger(NRF_SAADC_TASK_SAMPLE);
}

/**
 * @brief Function for application main entry.
 */
int main(void)
{
    /* Configure board. */
    bsp_board_init(BSP_INIT_LEDS);

    sensor_init();

    /* Toggle LEDs. */
    while (true)
    {
        for (int i = 0; i < 2; i++)
        {
            bsp_board_led_invert(i);
            nrf_delay_ms(250);
        }
    }
}

/**
 *@}
 **/
