/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usb_device.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "usbd_cdc_if.h"
#include "cdc_int.h"
#include "eeprom.h"
#include "pwm.h"
#include "adc.h"
#include "debug.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

typedef enum{
	bzoff,
	bzmoving,
	bzwarning,
}stBuz_st;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define P1START 0x01
#define P1STOP  0x02
#define P2START 0x04
#define P2STOP  0x08
#define M1FW  0x10
#define M1BW  0x20
#define M2FW  0x40
#define M2BW  0x80
#define M3FW  0x100
#define M3BW  0x200
#define M4FW  0x400
#define M4BW  0x800

#define M1 1
#define M2 2
#define M3 3
#define M4 4

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;

TIM_HandleTypeDef htim2;
TIM_HandleTypeDef htim4;

UART_HandleTypeDef huart1;

/* USER CODE BEGIN PV */

extern volatile uint16_t adc_dma_buf[];
extern uint16_t ch4 ;
extern uint16_t ch5 ;
extern uint16_t ch6 ;
extern uint16_t ch7 ;
extern uint16_t ch8 ;

uint8_t pulsanti=0;
volatile uint8_t rtP1=200;
volatile uint8_t rtP2=200;
volatile uint8_t rtTLC=100;
volatile uint16_t rtramp[4];
volatile uint16_t rtCiclo;
uint16_t m1pwmap;
uint16_t m1pwmch;
uint16_t m2pwmap;
uint16_t m2pwmch;
uint16_t m3pwmap;
uint16_t m3pwmch;
uint16_t m4pwmap;
uint16_t m4pwmch;
uint16_t t1ap;
uint16_t t2ap;
uint16_t t3ap;
uint16_t t4ap;
uint16_t twap;
uint16_t t1ch;
uint16_t t2ch;
uint16_t t3ch;
uint16_t t4ch;
uint16_t twch;
uint16_t tramp;
uint16_t tramp1;
uint16_t trampman;
uint16_t m1pwmMan;
uint16_t m2pwmMan;
uint16_t m3pwmMan;
uint16_t m4pwmMan;

uint16_t mrampstart[4];
uint16_t stPulsanti=0;
omCiclo_st stCiclo=omchiuso;
omCiclo_st memstCiclo=omchiuso;
volatile stBuz_st stBuz=bzoff;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_TIM2_Init(void);
static void MX_TIM4_Init(void);
static void MX_ADC1_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void HAL_SYSTICK_Callback(void){
  static unsigned char c10ms = 0;
  static uint8_t c100ms = 0;
  static uint8_t c1s = 0;
  static uint8_t inidx=0;
  static uint8_t inbuf[4];
  uint8_t i;

  if (++c10ms >= 10) {               // 10 ms
	  c10ms = 0;
	  if(rtP1)rtP1--;
	  if(rtP2)rtP2--;
	  if(rtTLC)rtTLC--;
//**** legge i tasti********************************************************************************
	  inidx++;
	  inidx&=0x03;
	  if(HAL_GPIO_ReadPin(P1_GPIO_Port, P1_Pin)==GPIO_PIN_RESET)inbuf[inidx]|=INP1;else inbuf[inidx]&=(~INP1);
	  if(HAL_GPIO_ReadPin(P2_GPIO_Port, P2_Pin)==GPIO_PIN_RESET)inbuf[inidx]|=INP2;else inbuf[inidx]&=(~INP2);
	  if(HAL_GPIO_ReadPin(CH1_GPIO_Port, CH1_Pin)==GPIO_PIN_RESET)inbuf[inidx]|=INCH1;else inbuf[inidx]&=(~INCH1);
	  if(HAL_GPIO_ReadPin(CH2_GPIO_Port, CH2_Pin)==GPIO_PIN_RESET)inbuf[inidx]|=INCH2;else inbuf[inidx]&=(~INCH2);
	  if(HAL_GPIO_ReadPin(CH3_GPIO_Port, CH3_Pin)==GPIO_PIN_RESET)inbuf[inidx]|=INCH3;else inbuf[inidx]&=(~INCH3);
	  if(HAL_GPIO_ReadPin(CH4_GPIO_Port, CH4_Pin)==GPIO_PIN_RESET)inbuf[inidx]|=INCH4;else inbuf[inidx]&=(~INCH4);

	  pulsanti|=(inbuf[0]&inbuf[1]&inbuf[2]&inbuf[3]);
	  pulsanti&=(inbuf[0]|inbuf[1]|inbuf[2]|inbuf[3]);
//**** legge adc ***********************************************************************************
	  readAdc();
	  if (++c100ms >= 10) {               // 10 ms
		  c100ms = 0;	    //flag_10ms = 1;                // set a flag; do real work in main loop
		  for(i=0;i<4;i++){
			  if(rtramp[i])rtramp[i]--;
		  }
//**** gestione buzzer *****************************************************************************
		  if(stBuz==bzmoving){
			  if(c1s>=5)HAL_GPIO_WritePin(GPIOA, BUZ_Pin, GPIO_PIN_RESET);else HAL_GPIO_WritePin(GPIOA, BUZ_Pin, GPIO_PIN_SET);
		  }else if(stBuz==bzwarning){
			  if(c1s&2)HAL_GPIO_WritePin(GPIOA, BUZ_Pin, GPIO_PIN_RESET);else HAL_GPIO_WritePin(GPIOA, BUZ_Pin, GPIO_PIN_SET);
		  }else{//bzoff
			  HAL_GPIO_WritePin(GPIOA, BUZ_Pin, GPIO_PIN_RESET);
		  }
//**************************************************************************************************
		  if (++c1s >= 10) {               // 10 ms
			  c1s = 0;
			  if(rtCiclo)rtCiclo--;
			  HAL_GPIO_TogglePin(LED2_GPIO_Port, LED2_Pin);
		  }
	  }
  }
}

void managePulsanti(void){
	if(pulsanti&INP1){
		if(rtP1==0)stPulsanti|=P1START;
	}else{
		if(stPulsanti&P1START)stPulsanti&=(~P1START);
		else if(rtP1<=190){
			stPulsanti|=P1STOP;
		}
		rtP1=200;
	}
	if(pulsanti&INP2){
		if(rtP2==0)stPulsanti|=P2START;
	}else{
		if(stPulsanti&P2START)stPulsanti&=(~P2START);
		else if(rtP2<=190)stPulsanti|=P2STOP;
		rtP2=200;
	}
	stPulsanti&=(P1START|P1STOP|P2START|P2STOP);
	if(stPulsanti==0){
		switch(pulsanti&0x3c){
			case 0x00:
				rtTLC=100;
				stPulsanti&=(!(M1FW|M1BW|M3FW|M3BW|M4FW|M4BW));
				break;
			case 0x08://tlc1
				if(rtTLC==0)stPulsanti|=M1FW;
				break;
			case 0x10://tlc2
				if(rtTLC==0)stPulsanti|=M1BW;
				break;
			case 0x20://tlc3
				if(rtTLC==0)stPulsanti|=M3FW;
				break;
			case 0x04://tlc4
				if(rtTLC==0)stPulsanti|=M3BW;
				break;
			case 0x30://tlc5
				if(rtTLC==0)stPulsanti|=M4FW;
				break;
			case 0x0c://tlc6
				if(rtTLC==0)stPulsanti|=M4BW;
				break;
			default:
				rtTLC=100;
				stPulsanti&=(!(M1FW|M1BW|M3FW|M3BW|M4FW|M4BW));
				break;
		}
	}
}

void manageCiclo(void){

	switch(stCiclo){
		case omchiuso:
			if(stPulsanti&P1START){
				stBuz=bzwarning;
				rtCiclo=3;
				stCiclo=omapertura0;
			}else if(stPulsanti&P1STOP)stCiclo=omstopapertura;
//			else if(stPulsanti&M1FW){
//				stBuz=bzmoving;
//				(void)ramp(M1,FW,mrampstart[M1-1],m1pwmMan,trampman,RAMPINIT);
//				stCiclo=omM1fw1;
//			}else if(stPulsanti&M1BW){
//				stBuz=bzmoving;
//				(void)ramp(M1,BW,mrampstart[M1-1],m1pwmMan,trampman,RAMPINIT);
//				stCiclo=omM1bw1;
//			}else if(stPulsanti&M2FW){
//				stBuz=bzmoving;
//				(void)ramp(M2,FW,mrampstart[M2-1],m2pwmMan,trampman,RAMPINIT);
//				stCiclo=omM2fw1;
//			}else if(stPulsanti&M2BW){
//				stBuz=bzmoving;
//				(void)ramp(M2,BW,mrampstart[M2-1],m2pwmMan,trampman,RAMPINIT);
//				stCiclo=omM2bw1;
//			}else if(stPulsanti&M3FW){
//				stBuz=bzmoving;
//				(void)ramp(M3,FW,mrampstart[M3-1],m3pwmMan,trampman,RAMPINIT);
//				stCiclo=omM3fw1;
//			}else if(stPulsanti&M3BW){
//				stBuz=bzmoving;
//				(void)ramp(M3,BW,mrampstart[M3-1],m3pwmMan,trampman,RAMPINIT);
//				stCiclo=omM3bw1;
//			}else if(stPulsanti&M4FW){
//				stBuz=bzmoving;
//				(void)ramp(M4,FW,mrampstart[M4-1],m3pwmMan,trampman,RAMPINIT);
//				stCiclo=omM4fw1;
//			}else if(stPulsanti&M4BW){
//				stBuz=bzmoving;
//				(void)ramp(M4,BW,mrampstart[M4-1],m3pwmMan,trampman,RAMPINIT);
//				stCiclo=omM4bw1;
//			}
			break;
		case omM1fw1:
			(void)ramp(M1,FW,mrampstart[M1-1],m1pwmMan,trampman,RAMPRUN);
			if(pulsanti==0)stCiclo=omM1fw2;
			break;
		case omM1fw2:
			(void)ramp(M1,FW,mrampstart[M1-1],m1pwmMan,trampman,RAMPRUN);
			if(pulsanti)stCiclo=omStopMan;
			break;
		case omM1bw1:
			(void)ramp(M1,BW,mrampstart[M1-1],m1pwmMan,trampman,RAMPRUN);
			if(pulsanti==0)stCiclo=omM1bw2;
			break;
		case omM1bw2:
			(void)ramp(M1,BW,mrampstart[M1-1],m1pwmMan,trampman,RAMPRUN);
			if(pulsanti)stCiclo=omStopMan;
			break;
		case omM2fw1:
			(void)ramp(M2,FW,mrampstart[M2-1],m2pwmMan,trampman,RAMPRUN);
			if(pulsanti==0)stCiclo=omM2fw2;
			break;
		case omM2fw2:
			(void)ramp(M2,FW,mrampstart[M2-1],m2pwmMan,trampman,RAMPRUN);
			if(pulsanti)stCiclo=omStopMan;
			break;
		case omM2bw1:
			(void)ramp(M2,BW,mrampstart[M2-1],m2pwmMan,trampman,RAMPRUN);
			if(pulsanti==0)stCiclo=omM2bw2;
			break;
		case omM2bw2:
			(void)ramp(M2,BW,mrampstart[M2-1],m2pwmMan,trampman,RAMPRUN);
			if(pulsanti)stCiclo=omStopMan;
			break;
		case omM3fw1:
			(void)ramp(M3,FW,mrampstart[M3-1],m3pwmMan,trampman,RAMPRUN);
			if(pulsanti==0)stCiclo=omM3fw2;
			break;
		case omM3fw2:
			(void)ramp(M3,FW,mrampstart[M3-1],m3pwmMan,trampman,RAMPRUN);
			if(pulsanti)stCiclo=omStopMan;
			break;
		case omM3bw1:
			(void)ramp(M3,BW,mrampstart[M3-1],m3pwmMan,trampman,RAMPRUN);
			if(pulsanti==0)stCiclo=omM3bw2;
			break;
		case omM3bw2:
			(void)ramp(M3,BW,mrampstart[M3-1],m3pwmMan,trampman,RAMPRUN);
			if(pulsanti)stCiclo=omStopMan;
			break;
		case omM4fw1:
			(void)ramp(M4,FW,mrampstart[M4-1],m4pwmMan,trampman,RAMPRUN);
			if(pulsanti==0)stCiclo=omM4fw2;
			break;
		case omM4fw2:
			(void)ramp(M4,FW,mrampstart[M4-1],m4pwmMan,trampman,RAMPRUN);
			if(pulsanti)stCiclo=omStopMan;
			break;
		case omM4bw1:
			(void)ramp(M4,BW,mrampstart[M4-1],m4pwmMan,trampman,RAMPRUN);
			if(pulsanti==0)stCiclo=omM4bw2;
			break;
		case omM4bw2:
			(void)ramp(M4,BW,mrampstart[M4-1],m4pwmMan,trampman,RAMPRUN);
			if(pulsanti)stCiclo=omStopMan;
			break;
		case omStopMan:
			SetMotPerc(M1,FW,0);
			SetMotPerc(M2,FW,0);
			SetMotPerc(M3,FW,0);
			SetMotPerc(M4,FW,0);
			SetMotPerc(M1,BW,0);
			SetMotPerc(M2,BW,0);
			SetMotPerc(M3,BW,0);
			SetMotPerc(M4,BW,0);
			if(pulsanti==0){
				stBuz=bzoff;
				stCiclo=omaperto;
			}
			break;
		case omapertura0:
			if(rtCiclo==0){
				stBuz=bzmoving;
				(void)ramp(M2,BW,mrampstart[M2-1],m2pwmap,tramp,RAMPINIT);
				stCiclo=omapertura1;
			}
			break;
		case omapertura1:
			if(ramp(M2,BW,mrampstart[M2-1],m2pwmap,tramp,RAMPRUN)==DONE){
				rtCiclo=t1ap;
				stCiclo=omapertura2;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura2:
			if(rtCiclo==0){
				(void)ramp(M2,BW,m2pwmap,0,tramp,RAMPINIT);
				stCiclo=omapertura3;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura3:
			if(ramp(M2,BW,m2pwmap,0,tramp,RAMPRUN)==DONE){
				rtCiclo=twap;
				stCiclo=omapertura4;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura4:
			if(rtCiclo==0){
				(void)ramp(M1,FW,mrampstart[M1-1],m1pwmap,tramp,RAMPINIT);
				stCiclo=omapertura5;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura5:
			if(ramp(M1,FW,mrampstart[M1-1],m1pwmap,tramp,RAMPRUN)==DONE){
				rtCiclo=t2ap;
				stCiclo=omapertura6;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura6:
			if(rtCiclo==0){
				(void)ramp(M3,FW,mrampstart[M3-1],m3pwmap,tramp,RAMPINIT);
				stCiclo=omapertura7;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura7:
			if(ramp(M3,FW,mrampstart[M3-1],m3pwmap,tramp,RAMPRUN)==DONE){
				rtCiclo=t3ap;
				stCiclo=omapertura8;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura8:
			if(rtCiclo==0){
				(void)ramp(M3,FW,m3pwmap,0,tramp,RAMPINIT);
				(void)ramp(M1,FW,m1pwmap,0,tramp,RAMPINIT);
				stCiclo=omapertura9;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura9:
			if((ramp(M3,FW,m3pwmap,0,tramp,RAMPRUN)==DONE)&&(ramp(M1,FW,m1pwmap,0,tramp,RAMPRUN)==DONE)){
				rtCiclo=twap;
				stCiclo=omapertura10;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura10:
			if(rtCiclo==0){
				(void)ramp(M4,FW,mrampstart[M4-1],m4pwmap,tramp,RAMPINIT);
				stCiclo=omapertura11;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura11:
			if(ramp(M4,FW,mrampstart[M4-1],m4pwmap,tramp,RAMPRUN)==DONE){
				rtCiclo=t4ap;
				stCiclo=omapertura12;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura12:
			if(rtCiclo==0){
				(void)ramp(M4,FW,m4pwmap,0,tramp,RAMPINIT);
				stCiclo=omapertura13;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura13:
			if(ramp(M4,FW,m4pwmap,0,tramp,RAMPRUN)==DONE){
				rtCiclo=twap;
				stCiclo=omapertura14;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omapertura14:
			if((rtCiclo==0)&&(pulsanti==0)){
				stBuz=bzoff;
				stCiclo=omaperto;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopapertura;
			break;
		case omstopapertura:
			SetMotPerc(M1,FW,0);
			SetMotPerc(M2,FW,0);
			SetMotPerc(M3,FW,0);
			SetMotPerc(M4,FW,0);
			if(pulsanti==0){
				stBuz=bzoff;
				stCiclo=omchiuso;
				stPulsanti&=(~P1STOP);
			}
			break;
		case omaperto:
			if(stPulsanti&P1START){
				stBuz=bzmoving;
				(void)ramp(M1,BW,mrampstart[M1-1],m1pwmch,tramp,RAMPINIT);
				stCiclo=omchiusura1;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			else if(stPulsanti&M1FW){
				stBuz=bzmoving;
				(void)ramp(M1,FW,mrampstart[M1-1],m1pwmMan,trampman,RAMPINIT);
				stCiclo=omM1fw1;
			}else if(stPulsanti&M1BW){
				stBuz=bzmoving;
				(void)ramp(M1,BW,mrampstart[M1-1],m1pwmMan,trampman,RAMPINIT);
				stCiclo=omM1bw1;
			}else if(stPulsanti&M2FW){
				stBuz=bzmoving;
				(void)ramp(M2,FW,mrampstart[M2-1],m2pwmMan,trampman,RAMPINIT);
				stCiclo=omM2fw1;
			}else if(stPulsanti&M2BW){
				stBuz=bzmoving;
				(void)ramp(M2,BW,mrampstart[M2-1],m2pwmMan,trampman,RAMPINIT);
				stCiclo=omM2bw1;
			}else if(stPulsanti&M3FW){
				stBuz=bzmoving;
				(void)ramp(M3,FW,mrampstart[M3-1],m3pwmMan,trampman,RAMPINIT);
				stCiclo=omM3fw1;
			}else if(stPulsanti&M3BW){
				stBuz=bzmoving;
				(void)ramp(M3,BW,mrampstart[M3-1],m3pwmMan,trampman,RAMPINIT);
				stCiclo=omM3bw1;
			}else if(stPulsanti&M4FW){
				stBuz=bzmoving;
				(void)ramp(M4,FW,mrampstart[M4-1],m3pwmMan,trampman,RAMPINIT);
				stCiclo=omM4fw1;
			}else if(stPulsanti&M4BW){
				stBuz=bzmoving;
				(void)ramp(M4,BW,mrampstart[M4-1],m3pwmMan,trampman,RAMPINIT);
				stCiclo=omM4bw1;
			}
			break;
		case omchiusura1:
			if(ramp(M1,BW,mrampstart[M1-1],m1pwmch,tramp,RAMPRUN)==DONE){
				rtCiclo=t4ch;
				stCiclo=omchiusura2;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura2:
			if(rtCiclo==0){
				(void)ramp(M3,BW,mrampstart[M3-1],m3pwmch,tramp,RAMPINIT);
				stCiclo=omchiusura3;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura3:
			if(ramp(M3,BW,mrampstart[M3-1],m3pwmch,tramp,RAMPRUN)==DONE){
				rtCiclo=t1ch;
				stCiclo=omchiusura4;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura4:
			if(rtCiclo==0){
				(void)ramp(M3,BW,m3pwmch,0,tramp,RAMPINIT);
				(void)ramp(M1,BW,m1pwmch,0,tramp,RAMPINIT);
				stCiclo=omchiusura5;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura5:
			if((ramp(M3,BW,m3pwmch,0,tramp,RAMPRUN)==DONE)&&(ramp(M1,BW,m1pwmch,0,tramp,RAMPRUN)==DONE)){
				rtCiclo=twch;
				stCiclo=omchiusura6;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura6:
			if(rtCiclo==0){
				(void)ramp(M2,FW,mrampstart[M2-1],m2pwmch,tramp,RAMPINIT);
				(void)ramp(M4,BW,mrampstart[M4-1],m4pwmch,tramp,RAMPINIT);
				stCiclo=omchiusura7;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura7:
			if((ramp(M2,FW,mrampstart[M2-1],m2pwmch,tramp,RAMPRUN)==DONE)&&(ramp(M4,BW,mrampstart[M4-1],m4pwmch,tramp,RAMPRUN)==DONE)){
				rtCiclo=t3ch;
				stCiclo=omchiusura8;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura8:
			if(rtCiclo==0){
				(void)ramp(M2,FW,m2pwmch,0,tramp,RAMPINIT);
				stCiclo=omchiusura9;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura9:
			if(ramp(M2,FW,m2pwmch,0,tramp,RAMPRUN)==DONE){
				rtCiclo=t2ch;
				stCiclo=omchiusura10;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura10:
			if(rtCiclo==0){
				(void)ramp(M4,BW,m4pwmch,0,tramp,RAMPINIT);
				stCiclo=omchiusura11;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura11:
			if(ramp(M4,BW,m4pwmch,0,tramp,RAMPRUN)==DONE){
				rtCiclo=twch;
				stCiclo=omchiusura14;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura12:
			if(rtCiclo==0){
				//(void)ramp(M4,BW,m4pwmch,0,tramp,RAMPINIT);
				stCiclo=omchiusura14;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura13:
			if(ramp(M4,BW,m4pwmch,0,tramp,RAMPRUN)==DONE){
				rtCiclo=twch;
				stCiclo=omchiusura14;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omchiusura14:
			if((rtCiclo==0)&&(pulsanti==0)){
				stBuz=bzoff;
				stCiclo=omchiuso;
			}
			if(stPulsanti&P1STOP)stCiclo=omstopchiusura;
			break;
		case omstopchiusura:
			SetMotPerc(M1,FW,0);
			SetMotPerc(M2,FW,0);
			SetMotPerc(M3,FW,0);
			SetMotPerc(M4,FW,0);
			if(pulsanti==0){
				stBuz=bzoff;
				stCiclo=omaperto;
				stPulsanti&=(~P1STOP);
			}
			break;
	}
}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USB_DEVICE_Init();
  MX_TIM2_Init();
  MX_TIM4_Init();
  MX_ADC1_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
  HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc_dma_buf, ADC_NUM_CHANNELS);
  StopMot(timMot1,FWMot1);
  StopMot(timMot1,BWMot1);
  StopMot(timMot2,FWMot2);
  StopMot(timMot2,BWMot2);
  StopMot(timMot3,FWMot3);
  StopMot(timMot3,BWMot3);
  StopMot(timMot4,FWMot4);
  StopMot(timMot4,BWMot4);
  //CDC_Transmit_FS((uint8_t*)"Start\r\n", 7);
  //while (CDC_Transmit_FS((uint8_t*)"Start\r\n", 7) == USBD_BUSY);
  if (EE_Init() != EE_OK){
      for(;;);//errore eeprom
  }
  loadEE();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1){
	  manageCDC();
	  manageAdc();
	  managePulsanti();
	  manageCiclo();
	  debug();
//	  while (CDC_Available()) {
	//	  int c = CDC_ReadByte();
      //if (c < 0) break;

//		  uint8_t out = (uint8_t)c;
//		  if (out >= 'a' && out <= 'z') out -= 32; // to upper

//		  unsigned char s[100];
//		  sprintf((char*)s,"\nc=%03d",c);
//		  while (CDC_Transmit_FS(s, 6) == USBD_BUSY) {
//        // tiny spin or yield
//      }
 //   }

	    //HAL_Delay(1000);
	   // CDC_Transmit_FS((uint8_t*)"Ping\r\n", 6);
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL6;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC|RCC_PERIPHCLK_USB;
  PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV6;
  PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL_DIV1_5;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief ADC1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_ADC1_Init(void)
{

  /* USER CODE BEGIN ADC1_Init 0 */

  /* USER CODE END ADC1_Init 0 */

  ADC_ChannelConfTypeDef sConfig = {0};

  /* USER CODE BEGIN ADC1_Init 1 */

  /* USER CODE END ADC1_Init 1 */

  /** Common config
  */
  hadc1.Instance = ADC1;
  hadc1.Init.ScanConvMode = ADC_SCAN_ENABLE;
  hadc1.Init.ContinuousConvMode = ENABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 5;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_4;
  sConfig.Rank = ADC_REGULAR_RANK_1;
  sConfig.SamplingTime = ADC_SAMPLETIME_28CYCLES_5;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_5;
  sConfig.Rank = ADC_REGULAR_RANK_2;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_6;
  sConfig.Rank = ADC_REGULAR_RANK_3;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_7;
  sConfig.Rank = ADC_REGULAR_RANK_4;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_8;
  sConfig.Rank = ADC_REGULAR_RANK_5;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN ADC1_Init 2 */

  /* USER CODE END ADC1_Init 2 */

}

/**
  * @brief TIM2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM2_Init(void)
{

  /* USER CODE BEGIN TIM2_Init 0 */

  /* USER CODE END TIM2_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};
  TIM_OC_InitTypeDef sConfigOC = {0};

  /* USER CODE BEGIN TIM2_Init 1 */

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 0;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 17999;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_TIM_PWM_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = 1000;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_ENABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.Pulse = 2000;
  if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.Pulse = 3000;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.Pulse = 4000;
  sConfigOC.OCFastMode = TIM_OCFAST_ENABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM2_Init 2 */

  /* USER CODE END TIM2_Init 2 */
  HAL_TIM_MspPostInit(&htim2);

}

/**
  * @brief TIM4 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM4_Init(void)
{

  /* USER CODE BEGIN TIM4_Init 0 */

  /* USER CODE END TIM4_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};
  TIM_OC_InitTypeDef sConfigOC = {0};

  /* USER CODE BEGIN TIM4_Init 1 */

  /* USER CODE END TIM4_Init 1 */
  htim4.Instance = TIM4;
  htim4.Init.Prescaler = 0;
  htim4.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim4.Init.Period = 17999;
  htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim4) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim4, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_TIM_PWM_Init(&htim4) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = 5000;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_ENABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.Pulse = 6000;
  if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.Pulse = 7000;
  if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.Pulse = 8000;
  if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM4_Init 2 */

  /* USER CODE END TIM4_Init 2 */
  HAL_TIM_MspPostInit(&htim4);

}

/**
  * @brief USART1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART1_UART_Init(void)
{

  /* USER CODE BEGIN USART1_Init 0 */

  /* USER CODE END USART1_Init 0 */

  /* USER CODE BEGIN USART1_Init 1 */

  /* USER CODE END USART1_Init 1 */
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */

  /* USER CODE END USART1_Init 2 */

}

/**
  * Enable DMA controller clock
  */
static void MX_DMA_Init(void)
{

  /* DMA controller clock enable */
  __HAL_RCC_DMA1_CLK_ENABLE();

  /* DMA interrupt init */
  /* DMA1_Channel1_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  /* USER CODE BEGIN MX_GPIO_Init_1 */

  /* USER CODE END MX_GPIO_Init_1 */

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LED2_GPIO_Port, LED2_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, INH1_Pin|INH2_Pin|INH3_Pin|INH4_Pin
                          |EXP1_Pin|EXP2_Pin|EXP3_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, BUZ_Pin|LED1_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : LED2_Pin */
  GPIO_InitStruct.Pin = LED2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LED2_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pins : P1_Pin P2_Pin */
  GPIO_InitStruct.Pin = P1_Pin|P2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

  /*Configure GPIO pin : AIN1_Pin */
  GPIO_InitStruct.Pin = AIN1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  HAL_GPIO_Init(AIN1_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pins : INH1_Pin INH2_Pin INH3_Pin INH4_Pin
                           EXP1_Pin EXP2_Pin EXP3_Pin */
  GPIO_InitStruct.Pin = INH1_Pin|INH2_Pin|INH3_Pin|INH4_Pin
                          |EXP1_Pin|EXP2_Pin|EXP3_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /*Configure GPIO pins : CH1_Pin CH2_Pin CH3_Pin CH4_Pin */
  GPIO_InitStruct.Pin = CH1_Pin|CH2_Pin|CH3_Pin|CH4_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /*Configure GPIO pins : BUZ_Pin LED1_Pin */
  GPIO_InitStruct.Pin = BUZ_Pin|LED1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /* USER CODE BEGIN MX_GPIO_Init_2 */

  /* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
