#include <i2c1.h>

void I2C1_MEM8_Write(uint8_t dev_address, uint8_t dev_register,
		uint8_t *sendbuffer, uint16_t sendbuffer_length)
{
	uint16_t x;

	if ((dev_address == 0) || (sendbuffer_length == 0))
		return;
	while (LL_I2C_IsActiveFlag_BUSY(I2C1))
		;

	LL_I2C_AcknowledgeNextData(I2C1, LL_I2C_ACK);
	LL_I2C_GenerateStartCondition(I2C1);
	while (!LL_I2C_IsActiveFlag_SB(I2C1))
		;

	LL_I2C_TransmitData8(I2C1, dev_address | I2C_REQUEST_WRITE);//###
	while (!LL_I2C_IsActiveFlag_ADDR(I2C1))
		;
	LL_I2C_ClearFlag_ADDR(I2C1);
	LL_I2C_TransmitData8(I2C1, dev_register);

	x = 0;
	do
	{
		if (LL_I2C_IsActiveFlag_TXE(I2C1))
		{
			LL_I2C_TransmitData8(I2C1, sendbuffer[x]);
			x++;
		}
	} while (x < sendbuffer_length);

	while (!LL_I2C_IsActiveFlag_BTF(I2C1))
		;					//wacht tot BYTE TRANSFER FINISHED flag is set
	LL_I2C_GenerateStopCondition(I2C1);
}

void I2C1_MEM8_Read(uint8_t dev_address, uint8_t dev_register,
		uint8_t *readbuffer, uint16_t readbuffer_length)
{
	uint16_t x;

	if ((dev_address == 0) || (readbuffer_length == 0))
		return;
	while (LL_I2C_IsActiveFlag_BUSY(I2C1))
		;

	LL_I2C_AcknowledgeNextData(I2C1, LL_I2C_ACK);

	LL_I2C_GenerateStartCondition(I2C1);			//genereer start conditie
	while (!LL_I2C_IsActiveFlag_SB(I2C1))
		;
	LL_I2C_TransmitData8(I2C1, dev_address | I2C_REQUEST_WRITE);//### //device address + WRITE
	while (!LL_I2C_IsActiveFlag_ADDR(I2C1))
		;
	LL_I2C_ClearFlag_ADDR(I2C1);

	while (!LL_I2C_IsActiveFlag_TXE(I2C1))
		;
	LL_I2C_TransmitData8(I2C1, dev_register);//write register dat ik wil gaan uitlezen
	while (!LL_I2C_IsActiveFlag_BTF(I2C1))
		;

	LL_I2C_GenerateStartCondition(I2C1);				//herhaal start conditie
	while (!LL_I2C_IsActiveFlag_SB(I2C1))
		;
	LL_I2C_TransmitData8(I2C1, dev_address | I2C_REQUEST_READ);	//address + READ
	while (!LL_I2C_IsActiveFlag_ADDR(I2C1))
		;
	LL_I2C_ClearFlag_ADDR(I2C1);

	x = 0;
	readbuffer_length--;

	if (readbuffer_length > 0)
		while (x < readbuffer_length)
			if (LL_I2C_IsActiveFlag_RXNE(I2C1))
				readbuffer[x++] = LL_I2C_ReceiveData8(I2C1);//opslaan in readbuffer

	LL_I2C_AcknowledgeNextData(I2C1, LL_I2C_NACK);//NACK instellen voor laatste byte
	LL_I2C_GenerateStopCondition(I2C1);		//STOP instellen voor laatste byte

	while (x < (readbuffer_length + 1))
		if (LL_I2C_IsActiveFlag_RXNE(I2C1))
			readbuffer[x++] = LL_I2C_ReceiveData8(I2C1);//opslaan in readbuffer
}
