/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2023 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 "i2c.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"

#include "SSD1322_OLED_lib/SSD1322_HW_Driver.h"
#include "SSD1322_OLED_lib/SSD1322_API.h"
#include "SSD1322_OLED_lib/SSD1322_GFX.h"

#include "SSD1322_OLED_lib/Fonts/FreeMono9pt7b.h"
#include "SSD1322_OLED_lib/Fonts/FreeMonoBold9pt7b.h"

#include "tom_and_jerry.h"
#include "creeper.h"
#include "krecik.h"
#include "pat_i_mat.h"
#include "stars_4bpp.h"
/* USER CODE END Includes */

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

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define HC_SR04P_UART_ASK_FOR_DISTANCE 0XA0

#define HC_SR04P_I2C_ADDRESS 0x57<<1
#define HC_SR04P_I2C_DISTANCE_R1 0X01
#define I2C_TIMEOUT 5

#define OLED_UPDATE_PERIOD 1000
/* USER CODE END PD */

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

/* USER CODE END PM */

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

/* USER CODE BEGIN PV */
uint8_t TxData[16];
uint8_t RxData[16];
HAL_StatusTypeDef UartTxStatusCode;
HAL_StatusTypeDef UartRxStatusCode;

HAL_StatusTypeDef I2cTxStatusCode;
HAL_StatusTypeDef I2cRxStatusCode;

float hc_sr04p_distance_uart;
float hc_sr04p_distance_i2c;

char lcd_line[32];
uint32_t SoftTimerLCD;
/* USER CODE END PV */

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

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* 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_USART2_UART_Init();
	MX_USART1_UART_Init();
	MX_SPI1_Init();
	MX_I2C1_Init();
	/* USER CODE BEGIN 2 */

	SoftTimerLCD = HAL_GetTick();

	// Declare bytes array for a frame buffer.
	// Dimensions are divided by 2 because one byte contains two 4-bit grayscale pixels
	uint8_t tx_buf[256 * 64 / 2];

	SSD1322_API_init();
	set_buffer_size(256, 64);
	/* USER CODE END 2 */

	/* Infinite loop */
	/* USER CODE BEGIN WHILE */

	while (1)
	{

		if ((HAL_GetTick() - SoftTimerLCD) > OLED_UPDATE_PERIOD)
		{
			SoftTimerLCD = HAL_GetTick();

			//UART
			TxData[0] = HC_SR04P_UART_ASK_FOR_DISTANCE;
			UartTxStatusCode = HAL_UART_Transmit(&huart1, (uint8_t*) (&TxData),
					1, 50);
			__HAL_UART_SEND_REQ(&huart1, UART_RXDATA_FLUSH_REQUEST);
			UartRxStatusCode = HAL_UART_Receive(&huart1, (uint8_t*) (&RxData),
					3, 150);
			if (HAL_OK == UartRxStatusCode)
			{
				hc_sr04p_distance_uart = ((float) ((uint32_t) RxData[0] * 65536
						+ (uint32_t) RxData[1] * 256 + (uint32_t) RxData[2]))
						/ 10000.0f;
			}
			else
			{
				hc_sr04p_distance_uart = 0;
			}
			// I2C
			//			I2cRxStatusCode = HAL_I2C_Mem_Read(&hi2c1, HC_SR04P_I2C_ADDRESS,
			//					HC_SR04P_I2C_DISTANCE_R1, 1, (uint8_t*) (&RxData), 3, I2C_TIMEOUT);
			// 					does not work because of needed break to perform the  measurement

			TxData[0] = HC_SR04P_I2C_DISTANCE_R1;
			I2cTxStatusCode = HAL_I2C_Master_Transmit(&hi2c1,
					HC_SR04P_I2C_ADDRESS, (uint8_t*) (&TxData), 1, I2C_TIMEOUT);
			HAL_Delay(150); // break to perform the  measurement
			I2cRxStatusCode = HAL_I2C_Master_Receive(&hi2c1,
					HC_SR04P_I2C_ADDRESS, (uint8_t*) (&RxData), 3, I2C_TIMEOUT);
			if (HAL_OK == I2cRxStatusCode)
			{
				hc_sr04p_distance_i2c = ((float) ((uint32_t) RxData[0] * 65536
						+ (uint32_t) RxData[1] * 256 + (uint32_t) RxData[2]))
						/ 10000.0f;
			}
			else
			{
				hc_sr04p_distance_i2c = 0;
			}

			// OLED
			fill_buffer(tx_buf, 0);

			select_font(&FreeMono9pt7b);

			draw_text(tx_buf, "HC-SR04p via UART & I2C", 0, 10, 5);
			sprintf(lcd_line, "d_UART = %.1f cm", hc_sr04p_distance_uart);
			draw_text(tx_buf, lcd_line, 0, 27, 10);

			sprintf(lcd_line, "d_I2C  = %.1f cm", hc_sr04p_distance_i2c);
			draw_text(tx_buf, lcd_line, 0, 43, 10);
			draw_text(tx_buf, "        ufnalski.edu.pl", 0, 60, 5);

			send_buffer_to_OLED(tx_buf, 0, 0);
		}
		/* 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
	 */
	if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
	{
		Error_Handler();
	}

	/** Configure LSE Drive Capability
	 */
	HAL_PWR_EnableBkUpAccess();
	__HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_LOW);

	/** Initializes the RCC Oscillators according to the specified parameters
	 * in the RCC_OscInitTypeDef structure.
	 */
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE
			| RCC_OSCILLATORTYPE_MSI;
	RCC_OscInitStruct.LSEState = RCC_LSE_ON;
	RCC_OscInitStruct.MSIState = RCC_MSI_ON;
	RCC_OscInitStruct.MSICalibrationValue = 0;
	RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
	RCC_OscInitStruct.PLL.PLLM = 1;
	RCC_OscInitStruct.PLL.PLLN = 40;
	RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
	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();
	}

	/** Enable MSI Auto calibration
	 */
	HAL_RCCEx_EnableMSIPLLMode();
}

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