/**
  ******************************************************************************
  * @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.
  *
  ******************************************************************************
  */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>


/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart2;


/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);

/* Private user code ---------------------------------------------------------*/

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

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

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

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART2_UART_Init();

  Data_Pins_Init(0);
  Address_Pins_Init();
  Command_Pins_Init();

  int man_id, dev_id;
  Enter_Device_ID(&man_id, &dev_id);

  char *manufacturer = (char*)malloc(13 * sizeof(char));
  char *device = (char*)malloc(13 * sizeof(char));
  sprintf(manufacturer, "0x%02X \r\n", man_id);
  sprintf(device, "0x%02X \r\n", dev_id);

  debug_print("Manufacturer ID = \r\n");
  debug_print(manufacturer);
  debug_print("Device ID = \r\n");
  debug_print(device);


  /* Infinite loop */
  while (1)
  {
    //debug_print("Hello from STM32!\r\n");
  }

}

void Write_Address(int address){
  int pin_array[] = {
    GPIO_PIN_0, GPIO_PIN_1, GPIO_PIN_2, GPIO_PIN_3,
    GPIO_PIN_4, GPIO_PIN_5, GPIO_PIN_6, GPIO_PIN_7,
    GPIO_PIN_8, GPIO_PIN_9, GPIO_PIN_10, GPIO_PIN_11,
    GPIO_PIN_12, GPIO_PIN_13,
    GPIO_PIN_0, GPIO_PIN_1, GPIO_PIN_2, GPIO_PIN_3, GPIO_PIN_4 // These last 3 are our PB pins not the PC ones
  }; 
  for(int i=0; i<19; i++){
    if(i<14){
      if((address >> i) & 1) HAL_GPIO_WritePin(GPIOC, pin_array[i], GPIO_PIN_SET);
      else HAL_GPIO_WritePin(GPIOC, pin_array[i], GPIO_PIN_RESET);
    }
    else{
      if((address >> i) & 1) HAL_GPIO_WritePin(GPIOB, pin_array[i], GPIO_PIN_SET);
      else HAL_GPIO_WritePin(GPIOB, pin_array[i], GPIO_PIN_RESET);
    }
  }
}

int Receive_Data(void){
  Data_Pins_Init(0); // We make sure it's in input mode
  int result = 0;
  int pin_array[] = {
    GPIO_PIN_0, GPIO_PIN_1, GPIO_PIN_11, GPIO_PIN_12,
    GPIO_PIN_4, GPIO_PIN_5, GPIO_PIN_6, GPIO_PIN_7,
  };
  for(int i=0; i<8; i++){
    if(HAL_GPIO_ReadPin(GPIOA, pin_array[i]) == GPIO_PIN_SET){
      result += 1 << i;
    }
  }
  return result;
}

void Write_Data(int value){
  Data_Pins_Init(1); // We make sure it's in output mode
  int pin_array[] = {
    GPIO_PIN_0, GPIO_PIN_1, GPIO_PIN_11, GPIO_PIN_12,
    GPIO_PIN_4, GPIO_PIN_5, GPIO_PIN_6, GPIO_PIN_7,
  };
  for(int i=0; i<8; i++){
    if((value >> i) & 1) HAL_GPIO_WritePin(GPIOA, pin_array[i], GPIO_PIN_SET);
    else HAL_GPIO_WritePin(GPIOA, pin_array[i], GPIO_PIN_RESET);
  }
}

// All arguments must be 0 (low) or 1 (high)
void Write_Command_Pins(int CE, int OE, int WE){
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, (CE) ? GPIO_PIN_SET : GPIO_PIN_RESET);
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_9, (OE) ? GPIO_PIN_SET : GPIO_PIN_RESET);
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10,(WE) ? GPIO_PIN_SET : GPIO_PIN_RESET);
}

void Write_Command(int addr, int data) {
    Write_Command_Pins(1, 1, 1);
    Write_Address(addr);
    Write_Data(data);
    Write_Command_Pins(0, 1, 1);  
    // 4. Pulse WE# low to latch data
    Write_Command_Pins(0, 1, 0);  // WE low
    Write_Command_Pins(0, 1, 1);  // WE high

    // 5. Deassert CE#
    Write_Command_Pins(1, 1, 1);
}

int Flash_ReadByte(int addr) {
    Write_Address(addr);
    Data_Pins_Init(0);
    Write_Command_Pins(0, 0, 1); 
    int data = Receive_Data();
    Write_Command_Pins(1, 1, 1); 
    return data;
}

void Enter_Device_ID(int *manufacturer, int *device){
  // Enter ID mode
  Write_Command(0x5555, 0xAA);
  Write_Command(0x2AAA, 0x55);
  Write_Command(0x5555, 0x90);

  // Read Manufacturer ID (it should be 0xBF)
  *manufacturer = Flash_ReadByte(0x0000);

  // Read Device ID (it should be 0xB7 for the SST39SF040)
  *device = Flash_ReadByte(0x0001);

  // Exit ID mode
  Write_Command(0x5555, 0xF0); 
}

/**
  * @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_SCALE2);

  /** 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 = 16;
  RCC_OscInitStruct.PLL.PLLN = 336;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
  RCC_OscInitStruct.PLL.PLLQ = 7;
  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();
  }
}

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }

}

// The argument must be 0 (input) or 1 (output)
void Data_Pins_Init(int as_output){
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  // Configure PA0..PA7 as push-pull outputs
  GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_11 | GPIO_PIN_12 |
                        GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7;
  if(as_output == 1){
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;   // Push-pull output
    GPIO_InitStruct.Pull = GPIO_NOPULL;           // No pull-up/down
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; // Fast switching
  }else{
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;  // Input mode
    GPIO_InitStruct.Pull = GPIO_PULLDOWN;      // No pull-up/down
  }
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}

void Address_Pins_Init(void){
  GPIO_InitTypeDef GPIOC_InitStruct = {0};
  // Configure PC0..PC15 as push-pull outputs
  GPIOC_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 |
                        GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 |
                        GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10| GPIO_PIN_11|
                        GPIO_PIN_12| GPIO_PIN_13| GPIO_PIN_14| GPIO_PIN_15;
  GPIOC_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;   // Push-pull output
  GPIOC_InitStruct.Pull = GPIO_NOPULL;           // No pull-up/down
  GPIOC_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; // Fast switching
  HAL_GPIO_Init(GPIOC, &GPIOC_InitStruct);
  
  // Then we do the same for the remaining
  GPIO_InitTypeDef GPIOB_InitStruct = {0};
  // Configure PB0..PB2 as push-pull outputs
  GPIOB_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4;
  GPIOB_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;   // Push-pull output
  GPIOB_InitStruct.Pull = GPIO_NOPULL;           // No pull-up/down
  GPIOB_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; // Fast switching
  HAL_GPIO_Init(GPIOB, &GPIOB_InitStruct);
}

void Command_Pins_Init(void){
  // PA8-10 as outputs pins
  GPIO_InitTypeDef GPIOA_InitStruct = {0};
  GPIOA_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10;
  GPIOA_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;   // Push-pull output
  GPIOA_InitStruct.Pull = GPIO_NOPULL;           // No pull-up/down
  GPIOA_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; // Fast switching
  HAL_GPIO_Init(GPIOA, &GPIOA_InitStruct);
}

void debug_print(const char *msg) {
  HAL_UART_Transmit(&huart2, (uint8_t*)msg, strlen(msg), HAL_MAX_DELAY);
}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  // HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : B1_Pin */
  // GPIO_InitStruct.Pin = B1_Pin;
  // GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
  // GPIO_InitStruct.Pull = GPIO_NOPULL;
  // HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);

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


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