#include "CAP1296.h"

void CAP1296_write_reg_8 (uint8_t reg, uint8_t val)
{
	while(I2C_GetFlagStatus(CAP1296_I2C, I2C_ISR_BUSY) != RESET);
	I2C_TransferHandling(CAP1296_I2C, CAP1296_ADDR, 2, I2C_AutoEnd_Mode, I2C_Generate_Start_Write);

	while(I2C_GetFlagStatus(CAP1296_I2C, I2C_ISR_TXIS) == RESET);
	I2C_SendData(CAP1296_I2C, reg);

	while(I2C_GetFlagStatus(CAP1296_I2C, I2C_ISR_TXIS) == RESET);
	I2C_SendData(CAP1296_I2C, val);

	while(I2C_GetFlagStatus(CAP1296_I2C, I2C_ISR_STOPF) == RESET);
	I2C_ClearFlag(CAP1296_I2C, I2C_ICR_STOPCF);
}

uint8_t CAP1296_read_reg_8 (uint8_t reg)
{
	uint8_t temp=0;

	while(I2C_GetFlagStatus(CAP1296_I2C, I2C_ISR_BUSY) != RESET);
	I2C_TransferHandling(CAP1296_I2C, CAP1296_ADDR, 1, I2C_SoftEnd_Mode, I2C_Generate_Start_Write);

	while(I2C_GetFlagStatus(CAP1296_I2C, I2C_ISR_TXIS) == RESET);
	I2C_SendData(CAP1296_I2C, reg);

	while(I2C_GetFlagStatus(CAP1296_I2C, I2C_ISR_TC) == RESET);
	I2C_TransferHandling(CAP1296_I2C, CAP1296_ADDR, 1, I2C_AutoEnd_Mode, I2C_Generate_Start_Read);

	while(I2C_GetFlagStatus(CAP1296_I2C, I2C_ISR_RXNE) == RESET);
	temp|=0xff&I2C_ReceiveData(CAP1296_I2C);

	while(I2C_GetFlagStatus(CAP1296_I2C, I2C_ISR_STOPF) == RESET);
	I2C_ClearFlag(CAP1296_I2C, I2C_ICR_STOPCF);

	return temp;
}

void CAP1296_set_input(CAP1296_InputSetStruct *InputSet)
{

	CAP1296_write_reg_8(0x21,0b00011010);	//enable inputs
	CAP1296_write_reg_8(0x28,0b00010000);	//disable repeat
	CAP1296_write_reg_8(0x29,0b00011010);	//enable guard
}

uint32_t CAP1296_read_keys(void)
{
	uint32_t ret_val=0;
	if(!GPIO_ReadInputDataBit(GPIOC,GPIO_Pin_13))
	{
		uint8_t tlacitko=CAP1296_read_reg_8(0x03); //pusteni tlacitka
		if(tlacitko&0b00010000) ret_val=4;
		if(tlacitko&0b00001000) ret_val=5;
		if(tlacitko&0b00000010) ret_val=6;

		uint8_t temp=CAP1296_read_reg_8(0x00);
		temp&=0xFE;
		CAP1296_write_reg_8(0x00,temp);

		tlacitko=CAP1296_read_reg_8(0x03);	//stisk tlacitka
		if(tlacitko&0b00010000) {ret_val=1; Beep(20);}
		if(tlacitko&0b00001000) {ret_val=2; Beep(20);}
		if(tlacitko&0b00000010) {ret_val=3; Beep(20);}
	}
	return ret_val;
}

void CAP1296_init(void)
{
	CAP1296_write_reg_8(0x21,0b00011010);	//enable inputs
	CAP1296_write_reg_8(0x28,0b00000000);	//disable repeat
	CAP1296_write_reg_8(0x29,0b00011010);	//enable guard

	CAP1296_write_reg_8(0x34,0x30);	//1 citlivost (mensi cislo = vyssi citlivost)
	CAP1296_write_reg_8(0x33,0x30);	//2 citlivost
	CAP1296_write_reg_8(0x31,0x30);	//3 citlivost
}
