/*
 * mc_pot.c
 *
 *    Author: Andrey Koryagin https://blog.avislab.com/
 */

#include "u_foc.h"

uint32_t POT_BUF[POT_BUF_LEN];

uint8_t POT_BUF_Index;
uint32_t POT_AVER;
uint16_t POT_SPEED;

void POT_Process() {
	uint8_t i;

	POT_BUF[POT_BUF_Index] = MC_ADC_GetRegularValue(ADC_POT);

	POT_BUF_Index++;
	if (POT_BUF_Index >= POT_BUF_LEN) {
		POT_BUF_Index = 0;
	}

	for (i=0; i<POT_BUF_LEN; i++) {
		POT_AVER += POT_BUF[i];
	}
	POT_AVER = POT_AVER / POT_BUF_LEN;


	if (POT_AVER > POT_START_VALUE) {
		POT_SPEED = POT_MIN_RPM + POT_MAX_RPM * (POT_AVER - POT_START_VALUE) / (POT_MAX_VALUE-POT_START_VALUE);
		if (POT_SPEED > POT_MAX_RPM) {
			POT_SPEED = POT_MAX_RPM;
		}

		if (MC_GetState() == MC_STATE_IDLE) {
			MC_Start();
		}

	} else {
		if (POT_AVER < POT_STOP_VALUE) {
			POT_SPEED = 0;
			if (MC_GetState() == MC_STATE_RUN) {
				MC_Stop();
			}
			if (MC_GetState() == MC_STATE_FAULT) {
				MC_ResetFault();
			}
		}
	}

	MC_SetSpeedRamp(POT_SPEED, 10);
}

