/*
  ============================== 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 {
	DS3502_OK = 0, DS3502_I2C_ERROR, DS3502_INVALID_VALUE, DS3502_READ_ERROR
} DS3502_Status_t;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define DS3502_BASE_I2C_ADDR 0x28
#define DS3502_I2C_ADDR   (DS3502_BASE_I2C_ADDR << 1)   // HAL wymaga adresu przesuniętego o 1 bit
#define REG_WR_IVR        0x00
#define REG_CONTROL       0x02
/* 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* DS3502_StatusToString(DS3502_Status_t status) {
	switch (status) {
	case DS3502_OK:
		return "OK";
	case DS3502_I2C_ERROR:
		return "I2C ERROR";
	case DS3502_INVALID_VALUE:
		return "INVALID VALUE";
	case DS3502_READ_ERROR:
		return "READ ERROR";
	default:
		return "UNKNOWN";
	}
}
//Funkcja do wpisywania danych do rejestru
DS3502_Status_t DS3502_WriteReg(uint8_t reg, uint8_t value) {
	uint8_t data[2];

	data[0] = reg;
	data[1] = value;

	if (HAL_I2C_Master_Transmit(&hi2c1, DS3502_I2C_ADDR, data, 2, 100)
			!= HAL_OK) {
		return DS3502_I2C_ERROR;
	}

	return DS3502_OK;
}
//Funkcja do odczytu wartosci ustawionej na potencjometrze, w zakresie od 0-127
DS3502_Status_t DS3502_ReadWiper(uint8_t *value) {
	uint8_t reg = REG_WR_IVR;
	uint8_t data = 0;

	if (value == NULL) {
		return DS3502_READ_ERROR;
	}

	if (HAL_I2C_Master_Transmit(&hi2c1, DS3502_I2C_ADDR, &reg, 1, 100)
			!= HAL_OK) {
		return DS3502_I2C_ERROR;
	}

	if (HAL_I2C_Master_Receive(&hi2c1, DS3502_I2C_ADDR, &data, 1, 100)
			!= HAL_OK) {
		return DS3502_READ_ERROR;
	}

	*value = data & 0x7F;

	return DS3502_OK;
}

// Funkcja do ustawiania potencjometru
DS3502_Status_t DS3502_SetWiper(uint8_t value) {
	DS3502_Status_t status;

	if (value > 127) {
		return DS3502_INVALID_VALUE;
	}

	status = DS3502_WriteReg(REG_CONTROL, 0x80);   // MODE = 1
	if (status != DS3502_OK) {
		return status;
	}

	return DS3502_WriteReg(REG_WR_IVR, value);
}

// Funkcja do zapisu wartosci na po resecie jako ustawienia potencjometru
DS3502_Status_t DS3502_SetDefaultWiper(uint8_t value) {
	DS3502_Status_t status;

	if (value > 127) {
		return DS3502_INVALID_VALUE;
	}

	status = DS3502_WriteReg(REG_CONTROL, 0x00);   // MODE = 0
	if (status != DS3502_OK) {
		return status;
	}

	return DS3502_WriteReg(REG_WR_IVR, value);
}
/* 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 */
	DS3502_Status_t status;
	uint8_t wiper = 0;

	status = DS3502_SetWiper(127);

	if (status == DS3502_OK) {
		status = DS3502_ReadWiper(&wiper);
	}
	DS3502_SetWiper(63);
	while (1) {

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

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