/*
 ============================== DS3502 + STM32G474RE – Sterowanie potencjometrem I2C HAL ==============================

 Ten przykład pokazuje podstawową obsługę cyfrowego potencjometru DS3502 po magistrali I2C.
 Kod jest przygotowany pod STM32G474RE z użyciem biblioteki HAL.
 Program ustawia pozycję suwaka (wiper) oraz odczytuje aktualną wartość z układu.
 DS3502 jest potencjometrem liniowym o rozdzielczości 7-bit (0–127).

 W STM32CubeMX / STM32CubeIDE należy włączyć wybrany interfejs I2C.

 W przykładzie przyjęto:
 - I2C1_SCL na PA15
 - I2C1_SDA na PB7

 W celu testowania sugerujemy podłączenie:
 - RH do 3.3V
 - RL do GND
 - RW do multimetru

 Dzięki temu możliwy będzie pomiar zmieniającego się napięcia wyjściowego.

 Pomiar napięcia należy wykonywać między RW a GND lub między RW a RL,
 jeśli RL podłączono do GND.

 Pomiar rezystancji należy wykonywać WYŁĄCZNIE przy odłączonym zasilaniu układu.

 Pozostawienie pinów RH/RL niepodłączonych może powodować nieprzewidziane zachowania pomiarowe.

 DS3502 komunikuje się przez I2C z domyślnym adresem 0x28.

 W funkcjach HAL adres I2C jest przesunięty o 1 bit,
 dlatego w kodzie używane jest:
 (0x28 << 1)

 Połączenia (DS3502 ↔ STM32G474RE):

 SDA  -> PB7  / I2C1_SDA
 SCL  -> PA15 / I2C1_SCL
 VCC  -> 3.3V
 GND  -> GND

 Połączenia części analogowej potencjometru:

 RH   -> 3.3V
 RL   -> GND
 RW   -> punkt pomiarowy (multimetr / sygnał wyjściowy)

 Zakres suwaka (Wiper):

 0     -> minimalna rezystancja / ~0V
 64    -> środek zakresu / ~1.65V
 127   -> maksymalna rezystancja / ~3.3V

 Magistrala I2C:

 Adres DS3502:      0x28
 Adres dla HAL:     0x28 << 1
 Zalecana prędkość: 100 kHz lub 400 kHz

 Obsługiwane statusy:

 - DS3502_OK
 - DS3502_I2C_ERROR
 - DS3502_INVALID_VALUE
 - DS3502_READ_ERROR

 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
typedef enum {
	MCP4725_OK = 0, MCP4725_I2C_ERROR, MCP4725_INVALID_VALUE
} MCP4725_Status_t;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define MCP4725_BASE_I2C_ADDR   0x60
#define MCP4725_I2C_ADDR        (MCP4725_BASE_I2C_ADDR << 1)

#define MCP4725_CMD_WRITE_DAC   0x40

#define MCP4725_MAX_VALUE       4095
#define MCP4725_STEP            128
#define VALUE_TO_WRITE 127
/* USER CODE END PD */

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

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

COM_InitTypeDef BspCOMInit;
I2C_HandleTypeDef hi2c1;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C1_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
const char* MCP4725_StatusToString(MCP4725_Status_t status) {
	switch (status) {
	case MCP4725_OK:
		return "OK";
	case MCP4725_I2C_ERROR:
		return "I2C ERROR";
	case MCP4725_INVALID_VALUE:
		return "INVALID VALUE";
	default:
		return "UNKNOWN";
	}
}

MCP4725_Status_t MCP4725_SetDAC(uint16_t value) {
	uint8_t data[3];

	if (value > MCP4725_MAX_VALUE) {
		return MCP4725_INVALID_VALUE;
	}

	data[0] = MCP4725_CMD_WRITE_DAC;
	data[1] = value >> 4;
	data[2] = (value & 0x0F) << 4;

	if (HAL_I2C_Master_Transmit(&hi2c1, MCP4725_I2C_ADDR, data, 3, 100)
			!= HAL_OK) {
		return MCP4725_I2C_ERROR;
	}

	return MCP4725_OK;
}
/* 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_I2C1_Init();
	/* USER CODE BEGIN 2 */

	/* USER CODE END 2 */

	/* Initialize led */
	BSP_LED_Init(LED_GREEN);

	/* Initialize USER push-button, will be used to trigger an interrupt each time it's pressed.*/
	BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);

	/* Initialize COM1 port (115200, 8 bits (7-bit data + 1 stop bit), no parity */
	BspCOMInit.BaudRate = 115200;
	BspCOMInit.WordLength = COM_WORDLENGTH_8B;
	BspCOMInit.StopBits = COM_STOPBITS_1;
	BspCOMInit.Parity = COM_PARITY_NONE;
	BspCOMInit.HwFlowCtl = COM_HWCONTROL_NONE;
	if (BSP_COM_Init(COM1, &BspCOMInit) != BSP_ERROR_NONE) {
		Error_Handler();
	}

	/* Infinite loop */
	/* USER CODE BEGIN WHILE */
	MCP4725_Status_t status;
	status = MCP4725_SetDAC(2048);   // ~100%
	HAL_Delay(2000);
	if (status != MCP4725_OK) {
		Error_Handler();
	}
	while (1) {

	}
	/* USER CODE END 3 */
}

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

	/** Configure the main internal regulator output voltage
	 */
	HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST);

	/** Initializes the RCC Oscillators according to the specified parameters
	 * in the RCC_OscInitTypeDef structure.
	 */
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
	RCC_OscInitStruct.HSIState = RCC_HSI_ON;
	RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
	RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV4;
	RCC_OscInitStruct.PLL.PLLN = 85;
	RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
	RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
	RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
	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_DIV1;
	RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) {
		Error_Handler();
	}
}

/**
 * @brief I2C1 Initialization Function
 * @param None
 * @retval None
 */
static void MX_I2C1_Init(void) {

	/* USER CODE BEGIN I2C1_Init 0 */

	/* USER CODE END I2C1_Init 0 */

	/* USER CODE BEGIN I2C1_Init 1 */

	/* USER CODE END I2C1_Init 1 */
	hi2c1.Instance = I2C1;
	hi2c1.Init.Timing = 0x40B285C2;
	hi2c1.Init.OwnAddress1 = 0;
	hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
	hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
	hi2c1.Init.OwnAddress2 = 0;
	hi2c1.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
	hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
	hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
	if (HAL_I2C_Init(&hi2c1) != HAL_OK) {
		Error_Handler();
	}

	/** Configure Analogue filter
	 */
	if (HAL_I2CEx_ConfigAnalogFilter(&hi2c1, I2C_ANALOGFILTER_ENABLE)
			!= HAL_OK) {
		Error_Handler();
	}

	/** Configure Digital filter
	 */
	if (HAL_I2CEx_ConfigDigitalFilter(&hi2c1, 0) != HAL_OK) {
		Error_Handler();
	}
	/* USER CODE BEGIN I2C1_Init 2 */

	/* USER CODE END I2C1_Init 2 */

}

/**
 * @brief GPIO Initialization Function
 * @param None
 * @retval None
 */
static void MX_GPIO_Init(void) {
	/* 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_GPIOF_CLK_ENABLE();
	__HAL_RCC_GPIOA_CLK_ENABLE();
	__HAL_RCC_GPIOB_CLK_ENABLE();

	/* 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 */
