/*
 * hal_ENC424J600.c
 *
 *  Created on: Nov 14, 2011
 *      Author: RomanM
 */

#include "hal_Enc424j600.h"
#include "drivers/Periph/SPI/hal_SPI.h"

void hal_Enc424j600_Init(void) {
	hal_Enc424j600_RCC_Config();
	hal_Enc424j600_GPIO_Config();
	hal_SPI_Init(hal_ENC424J600_SPIx);
	hal_Enc424j600_EXTI_Config();
	hal_Enc424j600_NVIC_Config();
}

void hal_Enc424j600_GPIO_Config(void) {
	GPIO_InitTypeDef GPIO_InitStructure;

	GPIO_InitStructure.GPIO_Pin = hal_ENC424J600_NSS_PIN;	// NSS pin
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;		// Out push-pull
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(hal_ENC424J600_PORT, &GPIO_InitStructure);

	GPIO_InitStructure.GPIO_Pin = hal_ENC424J600_INT_PIN;	// INT pin
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;	// Input floating (external pull-up)
	GPIO_Init(hal_ENC424J600_PORT, &GPIO_InitStructure);

	hal_ENC424J600_NSS_High();
}

void hal_Enc424j600_RCC_Config(void) {
	RCC_APB2PeriphClockCmd(hal_ENC424J600_PORT_CLK, ENABLE);
}

void hal_Enc424j600_EXTI_Config(void) {
	EXTI_InitTypeDef EXTI_InitStructure;

	GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource3);

	EXTI_StructInit(&EXTI_InitStructure);
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
	EXTI_InitStructure.EXTI_Line = EXTI_Line3;
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;
	EXTI_Init(&EXTI_InitStructure);

	EXTI_ClearITPendingBit(EXTI3_IRQn);
}

void hal_Enc424j600_NVIC_Config(void) {
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
	NVIC_ClearPendingIRQ(EXTI3_IRQn);

	NVIC_InitStructure.NVIC_IRQChannel = EXTI3_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
}

void hal_ENC424J600_NSS_Low(void) {
	GPIO_ResetBits(hal_ENC424J600_PORT, hal_ENC424J600_NSS_PIN);
}

void hal_ENC424J600_NSS_High(void) {
	GPIO_SetBits(hal_ENC424J600_PORT, hal_ENC424J600_NSS_PIN);
}

uint8_t hal_Enc424j600_RW(uint8_t data) {
	return hal_SPI_RW(hal_ENC424J600_SPIx, data);
}

void hal_Enc424j600_WriteN(uint8_t *outBuff, uint8_t n) {
	hal_SPI_WriteN(hal_ENC424J600_SPIx, outBuff, n);
}

void hal_Enc424j600_ReadN(uint8_t *inBuff, uint8_t n) {
	hal_SPI_ReadN(hal_ENC424J600_SPIx, inBuff, n);
}

/*
 * Delay function
 */
void hal_Enc424j600_Delay(__IO uint32_t nTick) {
	for(; nTick != 0; nTick--);
}
