/* 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 "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include "stm32f4xx_ll_gpio.h"
#include "lcd.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
//ECE177 #defines here
#define nop() __asm("\tnop\n\t")

#define LEDS GPIOC->ODR
// defines for DRIVE_KEYPAD_ROW(row) and READ_KEYPAD_COL(col) here

// I'll do the ENABLE_SPKR "define" 
#define ENABLE_SPKR (GPIOA->MODER |= 0x01 << 10*2)
// You add a "TOGGLE_SPKR" define

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
//ECE177 -- used for getkey()
unsigned char colmap[] = {8, 9, 10, 12};

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
//ECE177 function prototypes here
struct note;
struct song;
signed char getkey(void);			// forward declarations
signed char mapkey(signed char key);
void delaycycles(int cycles);
void mydelayms(unsigned int ms);
void playnote(struct note n);
void playsong(const struct song* s);
unsigned char serialRead(void);
void serialWrite(unsigned char c);

//void setTMR1(int timerval);

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
struct note {
	unsigned char notenum;		// index into array of frequencies for this note
	unsigned char duration;		// duration of note in 1/8ths of a second
};

struct song {
	unsigned char numnotes;		// Number of notes in this song
	const struct note thenotes[30];	// Array of the notes (max 30)
};

const struct song steinsong = {
    14,
	{
		{2,12},	//	 First line of "Maine Stein Song"
		{4,1},	//	 Data is note number and duration (1/8 ths second)
		{2,3},
		{1,1},
		{2,3},
		{7,4},
		{11,8},
		{14,4},
		{7,2},
		{7,2},
		{9,4},
		{7,4},
		{6,8},
		{4,8}
	}
};


const struct song marylamb = {
    26,
	{
		{4,3},	//	 First line of "Mary Had a Little Lamb"
		{2,1},	//	 Data is note number and duration (1/8 ths second)
		{0,2},
		{2,2},
		{4,2},
		{4,2},
		{4,4},
		{2,2},
		{2,2},
		{2,4},
		{4,2},
		{7,2},
		{7,4},
		{4,3},
		{2,1},
		{0,2},
		{2,2},
		{4,2},
		{4,2},
		{4,2},
		{4,2},
		{2,2},
		{2,2},
		{4,2},
		{2,2},
		{0,8}
	}
};

const unsigned int frequency[] = {        // note number & note
		262,      // 0  C
		277,      // 1  C#
		294,      // 2  D
		311,      // 3  D#
		330,      // 4  E
		349,      // 5  F
		370,      // 6  F#
		392,      // 7  G
		415,      // 8  G#
		440,      // 9  A
		466,      // 10 A#
		494,      // 11 B
		523,      // 12 C
		554,      // 13 C#
		587       // 14 D
};

/* 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_TIM2_Init();
  /* USER CODE BEGIN 2 */
	lcd_init();

    GPIOB->OTYPER = 0x0000;		// GPIOB (Keypad) pins, when outputs, are "push-pull" type
	GPIOB->MODER = 0x0000;	// All bits of GPIOB are initially inputs
	GPIOB->ODR = 0xFFFF;		// When GPIOB (keypad row) bits are output, the are logic 1

	ENABLE_SPKR;           // OK, I'll do this one for you

	TIM2->CR1 |= 0x0001;		//  Timer enable ***************************************************

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
//	  GPIOC->ODR = GPIOB->IDR>>4;        // An idea to help in testing
//	  continue;

// ECE177 main code here
      
    /* 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_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();
  }
}

/* USER CODE BEGIN 4 */
//ECE177 Put your functions here (finish them up)

signed char getkey(void) {
// This routine will get a key on the keypad and will return the key number
// below, or -1 if no key is pressed.
// Keys are numbered top to bottom and left to right and the keypad is mapped
// as follows

//             GPIO->ODR
//             Output	Key                 KEY
//             Bits     Number            LABELING
//              4 |  0  1  2  3        | 1  2  3  A
//              5 |  4  5  6  7        | 4  5  6  B
//              6 |  8  9 10 11        | 7  8  9  C
//              7 | 12 13 14 15        | *  0  #  D
//                 ------------         ------------
//                   8  9 10 12
//             GPIO->IDR Input Bits

// Your code here	
}

signed char mapkey(signed char key) {
//	Return the mapping of the given key according to the following

//             GPIO->ODR
//             Output	Key                 KEY
//             Bits     Number            LABELING
//              4 |  0  1  2  3        | 1  2  3  A
//              5 |  4  5  6  7        | 4  5  6  B
//              6 |  8  9 10 11        | 7  8  9  C
//              7 | 12 13 14 15        | *  0  #  D
//                 ------------         ------------
//                   8  9 10 12
//             GPIO->IDR Input Bits

// Your code here	
}

void delaycycles(int cycles) {

// Your code here	
}

void mydelayms(unsigned int ms) {

// Your code here	
}

void playnote(struct note n) {
	unsigned int numcycles2, ttime, i;

// Your code here	
}

void playsong(const struct song* s) {

// Your code here	
}

unsigned char serialRead(void) {

// Your code here	
}
void serialWrite(unsigned char c) {
    
// Your code here	
}
/* 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 */
