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

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

#include "color_conversion.h"

#include "ILI9341_STM32_Driver.h"
#include "ILI9341_GFX.h"

#include "snow_tiger.h"

#include <stdio.h>
#include <string.h>
/* USER CODE END Includes */

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

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

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

/* USER CODE END PM */

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

/* USER CODE BEGIN PV */
#define X_START 70
#define	Y_START 50
#define PX_SIZE 2

//uint32_t image_data[352*144]; //max resolution is CIF
uint32_t image_data[176 * 72]; //max resolution is QCIF due to RAM size of F446RE

Camera_settings OV7670_settings =
{ QCIF, 		//Resolution
		YUV422, 	//Format
		NORMAL, 	//Effect
		ON,			//AEC
		ON, 		//AGC
		ON, 		//AWB
		OFF,		//Color bar
		OFF,		//vertical flip
		OFF,		//Horizontal flip
		OFF,		//Night mode
		OFF,		//ASC
		ON,			//De-noise
		ON,			//Banding filter
		HISTOGRAM,	//AEC algorithm
		QUARTER_FPS,	//Min. fps in night mode
		F_AUTO,		//Auto detect banding freq.
		256, 		//Exposure - 2 bytes
		4, 			//Gain	[0-7]=[1-128]
		160,		//Brightness - byte
		64, 		//Contrast - byte
		80, 		//Saturation - byte
		2,			//Sharpness	- [0-31]
		0,			//De-noise strength - byte
		x16, 		//Gain ceiling
		77, 		//R channel gain - byte
		103, 		//G channel gain - byte
		153			//B channel gain - byte
		};

uint16_t i, j, k, pw, ph;
uint32_t temp = 0;
int16_t Y1 = 0, Y2 = 0, U = 0, V = 0;
uint16_t width, height;
uint8_t format;
/* USER CODE END PV */

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

/* Direct printf to output somewhere */
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */

#ifndef __UUID_H
#define __UUID_H
//#define STM32_UUID ((uint32_t *)0x1FF0F420)
#define STM32_UUID ((uint32_t *)UID_BASE)
#endif //__UUID_H

/* 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_DMA_Init();
	MX_USART2_UART_Init();
	MX_DCMI_Init();
	MX_I2C2_Init();
	MX_SPI3_Init();
	MX_TIM1_Init();
	/* USER CODE BEGIN 2 */

	char uart2Data[32] = "Connected to UART Two\r\n";
	/*
	 * Output to uart2
	 * use screen or putty or whatever terminal software
	 * 8N1 115200
	 */
	HAL_UART_Transmit(&huart2, (uint8_t*) &uart2Data, sizeof(uart2Data),
			0xFFFF);

	OV7670_Power(DISABLE);

	//I2C2 is used for SCCB and TIM1 for XLCK generation
	OV7670_Init(&hdcmi, &hi2c2, &htim1);

	OV7670_PowerUp();
	OV7670_UpdateSettings(OV7670_settings);
	OV7670_SetFrameRate(XCLK_DIV(1), PLL_x4);
	HAL_Delay(10);

	OV7670_Start(CONTINUOUS, image_data);
	//OV7670_Start(SNAPSHOT, image_data);
	OV7670_getImageInfo(&width, &height, &format);
	HAL_Delay(100);

	ILI9341_Init();

	ILI9341_Fill_Screen(BLACK);
	ILI9341_Set_Rotation(SCREEN_HORIZONTAL_2);
	ILI9341_Draw_Text("OV7670 camera demo", 50, 10, WHITE, 2,
	BLACK);

	/* USER CODE END 2 */

	/* Infinite loop */
	/* USER CODE BEGIN WHILE */
	while (1)
	{
		for (k = 0; k < 2; k++) //interleaved drawing - image looks more fluent
		{
			for (i = k; i < height; i++)
			{

				//for(ph=0;ph<PX_SIZE;ph++)
				//{
				for (j = 0; j < (((width) / 2)); j++)
				{
					temp = image_data[j + i * (width / 2)]; // temp contains 2 pixel values

					if (format == YUV422)	//YUV422
					{
						//Extract YUV
						Y2 = (temp >> 24) & 0x00FF;
						U = ((temp >> 16) & 0x00FF) - 128;
						Y1 = (temp >> 8) & 0x00FF;
						V = (temp & 0x00FF) - 128;

						ILI9341_Draw_Pixel(X_START + 2 * j, Y_START + i,
								YUVtoRGB565(Y1, U, V));
						ILI9341_Draw_Pixel(X_START + 2 * j + 1, Y_START + i,
								YUVtoRGB565(Y2, U, V));
					}
					else				//RGB565
					{
						ILI9341_Draw_Pixel(X_START + 2 * j, Y_START + i,
								temp & 0xFFFF);
						ILI9341_Draw_Pixel(X_START + 2 * j + 1, Y_START + i,
								(temp >> 16) & 0xFFFF);

					}
					//}
				}
				i++; //skip 1 line - interleaved drawing
			}
		}
		/* 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_RCC_PWR_CLK_ENABLE();
	__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3);

	/** 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 = 8;
	RCC_OscInitStruct.PLL.PLLN = 84;
	RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
	RCC_OscInitStruct.PLL.PLLQ = 2;
	RCC_OscInitStruct.PLL.PLLR = 2;
	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_DIV2;

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

/* USER CODE BEGIN 4 */
/**
 * @brief  Retargets the C library printf function to the USART.
 * @param  None
 * @retval None
 */
PUTCHAR_PROTOTYPE
{
	/* Place your implementation of fputc here */
	/* e.g. write a character to the USART2 and Loop until the end of transmission */
	HAL_UART_Transmit(&huart2, (uint8_t*) &ch, 1, 0xFFFF);

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