#include "main.h"

void I2Cinit()
{
	SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C0);		// I²C interface for external communication
	SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C3);		// I²C interface for internal communication
	GPIOPinConfigure(GPIO_PB2_I2C0SCL);				// Configure port pins as I²C pins
	GPIOPinConfigure(GPIO_PB3_I2C0SDA);
	GPIOPinConfigure(GPIO_PG0_I2C3SCL);
	GPIOPinConfigure(GPIO_PG1_I2C3SDA);
	GPIOPinTypeI2CSCL(GPIO_PORTB_BASE, GPIO_PIN_2);	// Set clock pins
	GPIOPinTypeI2CSCL(GPIO_PORTG_BASE, GPIO_PIN_0);
	GPIOPinTypeI2C(GPIO_PORTB_BASE, GPIO_PIN_3);	// Set data pins
	GPIOPinTypeI2C(GPIO_PORTG_BASE, GPIO_PIN_1);

	I2CMasterInitExpClk(I2C0_BASE, SysCtlClockGet(), true); // Set I²C0 as master with system clock and 400kbps baudrate
	I2CMasterInitExpClk(I2C3_BASE, SysCtlClockGet(), true); // Set I²C3 as master with system clock and 400kbps baudrate

	I2CMasterEnable(I2C3_BASE);								// Enable I²C module 3 master
}

void setBassVolume(int level)
{
	I2CMasterEnable(I2C0_BASE);									// Enable I²C module 0 master
    I2CMasterSlaveAddrSet(I2C0_BASE, 0x002E, false);			// I²C module 0 , adress of bass volume poti, send data to slave
    I2CMasterDataPut(I2C0_BASE,level/100*0x007F);				// Put scaled level data in TX FIFO
    I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_SINGLE_SEND);	// Send data
    while(I2CMasterBusy(I2C0_BASE));							// Wait till data is send
    I2CMasterDisable(I2C0_BASE);								// Disable I²C module 0 master to save energy
}

void setBassFreq(int freq)
{
	I2CMasterEnable(I2C0_BASE);										// Enable I²C module 0 master
    I2CMasterSlaveAddrSet(I2C0_BASE, 0x0050, false);				// I²C module 0 , adress of bass cut off frequenzy poti, send data to slave
    I2CMasterDataPut(I2C0_BASE,0x0000);								// Put adress of poti a register in TX FIFO
    I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_START);	// Start to send data for poti A
    while(I2CMasterBusy(I2C0_BASE));								// Wait till data is send
    I2CMasterDataPut(I2C0_BASE,(160-freq)/160*0x00FF);				// Put scaled level for the register A in TX FIFO
    I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_CONT);	// Send secound data byte
    while(I2CMasterBusy(I2C0_BASE));								// Wait till data is send
    I2CMasterDataPut(I2C0_BASE,(160-freq)/160*0x00FF);				// Put scaled level for the register B in TX FIFO
    I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_FINISH);	// Send last data
    while(I2CMasterBusy(I2C0_BASE));								// Wait till data is send
    I2CMasterDisable(I2C0_BASE);									// Disable I²C module 0 master to save energy
}
