/*
 * user_io.c
 *
 *  Created on: Jun 23, 2023
 *      Author: true
 */


#include "hk32f030m.h"
#include "user_io.h"



void user_io_init()
{
	/* --original method, not space efficient
	// enable gpio clocks
	// RCC_AHBPeriphClockCmd(BTN_CLK | LED_CLK | RCC_AHBPeriph_GPIOB, ENABLE);

	// configure led
#if LED_ACT_DIR == 0
	LED_PORT->BSRR    = (1 << LED_PIN);								// idle high
#else
	LED_PORT->BRR     = (1 << LED_PIN);								// idle low
#endif
	LED_PORT->OTYPER  &= ~(GPIO_OTYPER_OT_0      <<     LED_PIN);	// push pull
	LED_PORT->OSPEEDR &= ~(GPIO_OSPEEDR_OSPEEDR0 << 2 * LED_PIN);	// slow
	LED_PORT->MODER   &= ~(GPIO_MODER_MODER0     << 2 * LED_PIN);
	LED_PORT->MODER    =  (GPIO_Mode_OUT         << 2 * LED_PIN);	// output

	// configure button
	BTN_PORT->MODER   &= ~(GPIO_MODER_MODER0     << 2 * BTN_PIN);	// input
	BTN_PORT->PUPDR   &= ~(GPIO_PUPDR_PUPDR0     << 2 * BTN_PIN);
#if BTN_ACT_DIR == 0
	//BTN_PORT->PUPDR   |=  (GPIO_PuPd_UP          << 2 * BTN_PIN);	// pulled high
	BTN_PORT->PUPDR    = (GPIO_PuPd_UP   << 2 * BTN_PIN);	// pulled high
#else
	//BTN_PORT->PUPDR   |=  (GPIO_PuPd_DOWN        << 2 * BTN_PIN);	// pulled low
	BTN_PORT->PUPDR    = (GPIO_PuPd_DOWN << 2 * BTN_PIN);	// pulled low
#endif
	*/

	/* new method, configure USART pins at the same time as LED and btn
	 * at they are on the same ports
	 */

	// default MODER for GPIOB and GPIOD are 0xFBFF
	// pin 5 _must_ be configured as AF, otherwise you'll kill debugging!

	// configure button as input
	BTN_PORT->MODER    = 0x0;
#if BTN_ACT_DIR == 0
	//BTN_PORT->PUPDR   |=  (GPIO_PuPd_UP          << 2 * BTN_PIN);	// pulled high
	BTN_PORT->PUPDR    = (GPIO_PuPd_UP   << 2 * BTN_PIN);	// pulled high
#else
	//BTN_PORT->PUPDR   |=  (GPIO_PuPd_DOWN        << 2 * BTN_PIN);	// pulled low
	BTN_PORT->PUPDR    = (GPIO_PuPd_DOWN << 2 * BTN_PIN);	// pulled low
#endif

	// configure LED as PP output, USART TX as AF
	LED_PORT->OTYPER   = 0;
	LED_PORT->ODR      = 0;
	LED_PORT->MODER    = 0x800
					 	 | (GPIO_Mode_OUT << (2 * 7))
						 | (GPIO_Mode_AF  << (2 * 1));

	// configure I2C SCK as low PP output
	GPIOC->ODR         = 0;
	GPIOC->MODER	   = (GPIO_Mode_OUT << (2 * 6));

	// configure USART RX as AF
	GPIOB->MODER	   = 0x800	| (GPIO_Mode_AF << (2 * 4));
}
