/**
 * 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 nrf_adc_example main.c
 * @{
 * @ingroup nrf_adc_example
 * @brief ADC Example Application main file.
 *
 * This file contains the source code for a sample application using ADC.
 *
 * @image html example_board_setup_a.jpg "Use board setup A for this example."
 */

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "nrf.h"
#include "nrf_drv_saadc.h"
#include "nrf_drv_ppi.h"
#include "nrf_drv_timer.h"
#include "boards.h"
#include "app_error.h"
#include "nrf_delay.h"
#include "app_util_platform.h"
#include "nrf_pwr_mgmt.h"
#define NRF_LOG_MODULE_NAME adc_sample
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "SEGGER_RTT.h"
#include "SEGGER_RTT_Conf.h"

NRF_LOG_MODULE_REGISTER();

#define SAMPLES_BUFFER_LEN 5
volatile uint8_t state = 1;
extern  uint32_t	 AutoResetCount;            //自动复位计数
extern  uint32_t	 FaultLEDFlashCount;        //灯闪烁时间计数
extern  uint32_t     StallCount;                //堵转计数20ms/次

const nrf_drv_timer_t m_timer = NRF_DRV_TIMER_INSTANCE(2);
nrf_saadc_value_t     m_buffer_pool[2][SAMPLES_BUFFER_LEN];
nrf_ppi_channel_t     m_ppi_channel;
//static uint32_t              m_adc_evt_counter;

static uint32_t mark_time = 0;
static uint32_t make_time_1s = 0;
extern uint32_t ADC_done;

void timer_handler(nrf_timer_event_t event_type, void * p_context)
{

}

void saadc_sampling_event_init(void)
{
    ret_code_t err_code;

    err_code = nrf_drv_ppi_init();
    APP_ERROR_CHECK(err_code);
	

    nrf_drv_timer_config_t timer_cfg = NRF_DRV_TIMER_DEFAULT_CONFIG;
    timer_cfg.bit_width = NRF_TIMER_BIT_WIDTH_32;
    err_code = nrf_drv_timer_init(&m_timer, &timer_cfg, timer_handler);
    APP_ERROR_CHECK(err_code);

    /* setup m_timer for compare event every 400ms */
    uint32_t ticks = nrf_drv_timer_us_to_ticks(&m_timer, 1232);
    nrf_drv_timer_extended_compare(&m_timer,
                                   NRF_TIMER_CC_CHANNEL0,
                                   ticks,
                                   NRF_TIMER_SHORT_COMPARE0_CLEAR_MASK,
                                   false);
    nrf_drv_timer_enable(&m_timer);

    uint32_t timer_compare_event_addr = nrf_drv_timer_compare_event_address_get(&m_timer,
                                                                                NRF_TIMER_CC_CHANNEL0);
    uint32_t saadc_sample_task_addr   = nrf_drv_saadc_sample_task_get();

    /* setup ppi channel so that timer compare event is triggering sample task in SAADC */
    err_code = nrf_drv_ppi_channel_alloc(&m_ppi_channel);
    APP_ERROR_CHECK(err_code);

    err_code = nrf_drv_ppi_channel_assign(m_ppi_channel,
                                          timer_compare_event_addr,
                                          saadc_sample_task_addr);
    APP_ERROR_CHECK(err_code);
}

void saadc_sampling_event_enable(void)
{
    ret_code_t err_code = nrf_drv_ppi_channel_enable(m_ppi_channel);

    APP_ERROR_CHECK(err_code);
}

static uint8_t sample_num  = 0;
uint32_t result_buffer[5][16];
void saadc_callback(nrfx_saadc_evt_t const * p_event)   //SAADC事件回调函数，只有一个缓存填满后才会进入事件回调函数
{
	  
	  if (p_event->type == NRFX_SAADC_EVT_DONE)
    {
        ret_code_t err_code;
				
		if(	p_event->data.done.size !=5)
		{	
				NRF_LOG_INFO("p_event->data.done.size.%d",p_event->data.done.size);
		}
        //设置好缓存，为下一次采样准备
				err_code = nrfx_saadc_buffer_convert(p_event->data.done.p_buffer, SAMPLES_BUFFER_LEN);
        APP_ERROR_CHECK(err_code);
		

			
				if(sample_num<16)
				{

						result_buffer[0][sample_num]=p_event->data.done.p_buffer[0];//三相电流
						result_buffer[1][sample_num]=p_event->data.done.p_buffer[1];
					
						result_buffer[2][sample_num]=p_event->data.done.p_buffer[2];
						result_buffer[3][sample_num]=p_event->data.done.p_buffer[3];//电位器1
						
						result_buffer[4][sample_num]=p_event->data.done.p_buffer[4];//电位器2
//						result_buffer[5][sample_num]=my_sample_buffer[0][5];
						
					  sample_num++;
				}
				if(sample_num == 16)
				{
					sample_num = 0;
//					m_adc_evt_counter++;
					ADC_done = 1;
					StallCount++;
					AutoResetCount++;
					FaultLEDFlashCount++;
					
					
					
					if(mark_time<50)
					{
						mark_time++;
						
						
					}
					else{
						mark_time=0;
						make_time_1s++;
						NRF_LOG_INFO("%d ,%d ,%d, %d ,%d", p_event->data.done.p_buffer[0],p_event->data.done.p_buffer[1],p_event->data.done.p_buffer[2],p_event->data.done.p_buffer[3],p_event->data.done.p_buffer[4]);
//						memset(p_event->data.done.p_buffer, 0, 10);
											}
				}
				

    }
		else
		{	
				NRF_LOG_INFO("p_event->type %d.",p_event->type);
		}
}


//初始化SAADC，配置使用的SAADC通道的参数和缓存
void saadc_init(void)
{
    ret_code_t err_code;
	  //定义ADC通道配置结构体，并使用单端采样配置宏初始化

	nrf_saadc_channel_config_t channel_config_1 =
	NRFX_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN2);			//通道2单端输入
	nrf_saadc_channel_config_t channel_config_2 =
	NRFX_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_VDD);			//通道3单端输入
	nrf_saadc_channel_config_t channel_config_3 =
	NRFX_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN5);			//通道5单端输入
	nrf_saadc_channel_config_t channel_config_4 =
	NRFX_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN6);			//通道6单端输入
	nrf_saadc_channel_config_t channel_config_5 =
	NRFX_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_VDD);			//通道7单端输入

	err_code = nrf_drv_saadc_init(NULL, saadc_callback);									//初始化SAADC，注册事件回调函数。
  APP_ERROR_CHECK(err_code);

	err_code = nrfx_saadc_channel_init(0, &channel_config_1);						//初始化SAADC通道5
	APP_ERROR_CHECK(err_code);
	err_code = nrfx_saadc_channel_init(1, &channel_config_2);						//初始化SAADC通道6
	APP_ERROR_CHECK(err_code);
	err_code = nrfx_saadc_channel_init(2, &channel_config_3);						//初始化SAADC通道7
	APP_ERROR_CHECK(err_code);
	err_code = nrfx_saadc_channel_init(3, &channel_config_4);						//初始化SAADC通道2
	APP_ERROR_CHECK(err_code);
	err_code = nrfx_saadc_channel_init(4, &channel_config_5);						//初始化SAADC通道3
	APP_ERROR_CHECK(err_code);



		err_code = nrfx_saadc_buffer_convert(m_buffer_pool[0], 5); //配置缓存1，将缓存1地址赋值给SAADC驱动程序中的控制块m_cb的一级缓存指针
    APP_ERROR_CHECK(err_code);
    err_code = nrfx_saadc_buffer_convert(m_buffer_pool[1], 5);//配置缓存2，将缓存1地址赋值给SAADC驱动程序中的控制块m_cb的二级缓存指针
    APP_ERROR_CHECK(err_code);
		

}

void test_adc(void)
{
    saadc_init();
    saadc_sampling_event_init();
    saadc_sampling_event_enable();
}
