#include <msp430.h>
#include <msp430xgeneric.h>
#include <stdint.h>

#include "mw_main.h"

#include "mw_acc.h"

void mw_init_acc_i2c(void)
{
	/* enable reset before configuration */
	ACCELEROMETER_CTL1 |= UCSWRST;

	/* configure as master using smclk / 40 = 399.5 kHz */
	ACCELEROMETER_CTL0 = UCMST + UCMODE_3 + UCSYNC;
	ACCELEROMETER_CTL1 = UCSSEL__SMCLK + UCSWRST;
	ACCELEROMETER_BR0 = 42;

	ACCELEROMETER_BR1 = 0;
	ACCELEROMETER_I2CSA = KIONIX_DEVICE_ADDRESS;

	/* release reset */
	ACCELEROMETER_CTL1 &= ~UCSWRST;
}

/*
 * DMA2 = SPI for LCD
 */
static void mw_acc_i2c_write_byte(uint8_t byte)
{
	ACCELEROMETER_TXBUF = byte;
	while ((ACCELEROMETER_CTL1 & ACCELEROMETER_IFG) == 0)
		nop();
}

/* OK this is polling write, but data is small and 400kHz I2C, it should "just work" :) */
void mw_acc_i2c_write(const uint8_t addr, const void *data, const uint8_t len)
{
	int i;

	if (len == 0) {
		return;  
	}
  
	while (UCB1STAT & UCBBUSY)
		nop();
  
	/* 
	 * setup for write and send the start condition
	 */
	ACCELEROMETER_IFG = 0;
	ACCELEROMETER_CTL1 |= UCTR + UCTXSTT;
	while (!(ACCELEROMETER_IFG & UCTXIFG))
		nop();
  
	/* 
	 * clear transmit interrupt flag,
	 * send the register address
	 */
	ACCELEROMETER_IFG = 0;

	mw_acc_i2c_write_byte(addr);

	for (i=0; i<len; i++)
		mw_acc_i2c_write_byte(*(uint8_t *)(data+i));

	while (ACCELEROMETER_CTL1 & UCTXSTP)
		nop();
}