
#include <stdint.h> 
#include "pru_hal.h"
//#include "comm.h"

#define G4 4294967295
#define TICK_TIME				200//ticks per us
#define PIN_HIGH(x)				__R30 = __R30 | (1 << x);
#define PIN_LOW(x)				__R30 = __R30 & ~(1 << x);

#define I_COEF					8.53
#define IMAX					100
#define IMIN					50
#define U_TARG					90
#define U_TARG_DELTA			1
#define K						6
#define PREADC					22 * TICK_TIME
#define AVG_ARR_SIZE			100
#define AI_CH_NUM				5
#define L						56//uH
#define E						14//V
#define B1						9//V
#define B2						15//V
#define UC_DELAY				70
#define TAU_RELAX_MAX			1000
#define TAU_RELAX_MIN			10
#define STEPS_TO_DO				100000
#define DEBUG_STEPS				30
#define K_UC					(float)0.285

volatile register uint32_t __R30;  // Output pins 

volatile uint32_t last_cnt;
volatile long long time;//, t1, t2, t3;
volatile uint32_t cnt;
volatile uint32_t vv;
volatile uint32_t state, I1, Uc, alg;
volatile uint32_t cfgU, cfgdU, cfgImax, cfgImin;

void error(uint32_t err, uint32_t add)	
{
	shm_write_uint32((PRU_MEM_ERR) * 4, err);
	shm_write_uint32((PRU_MEM_ERR_ADD) * 4, add);
	state = PRU_STATE_ERROR;
}

void msg(uint32_t err, uint32_t add)	
{
	shm_write_uint32((PRU_MEM_MSG) * 4, err);
	shm_write_uint32((PRU_MEM_MSG_ADD) * 4, add);
}

int main(void)
{
	volatile long long dt, charge1Time, charge2Time, UcTime, adcTime, p;
	volatile uint32_t cur_avg;

	ocp_init();
	shm_init();

	error(PRU_ERR_NONE, 0);
	msg(PRU_MSG_NONE, 0);

	cur_avg = time = charge1Time = charge2Time = 0;

	while (1)	{
		adcTime = time;//время запуска АЦП

		time+=1000;
		if (time >=  adcTime + (long long)(20000)) {//контролируем что мы не вышли за пределы времени ожидания АЦП
			msg(time, adcTime);
			break;
		}
	}

	while(1)	{
		cur_avg++;
		shm_write_uint32((PRU_AI_DATA_OFFSET + 4) * 4, (uint32_t)cur_avg);
	}

	__halt();
	return 0;
}
