#include <em_device.h>
#include "hardware.h"
#include "dogs_10x4.h"
#include "i2c.h"
extern void Delay_ms(uint32_t);
uint8_t DOGSbuf[20];
uint8_t DOGSview;

void DOGS_setup()
{
	uint8_t initSeq[] = {0x00, 0x3A, 0x09, 0x06, 0x1E, 0x39, 0x1B, 0x6E, 0x56, 0x7A, 0x38, 0x01, 0x0C};
	(GPIO->P[1]).DOUTCLR = DOGS_RST;
	Delay_ms(1);
	(GPIO->P[1]).DOUTSET = DOGS_RST;
	Delay_ms(60); 										//Wait 50 msec after power is applied	
	I2CMasterWriteBuf(DOGS_SLAVE_ADDRESS, initSeq, 13); // send init sequence
	Delay_ms(5);
	DOGS_SetViewMode(BOTTOM_VIEW, THREE_LINES_TOP); 
} 

void DOGS_SetViewMode(uint8_t view, uint8_t lines)
{
	uint8_t modeSet[4];
	DOGSview = view;
	modeSet[0] = 0;
	modeSet[1] = 0x3A;
	modeSet[3] = 0x3C; 
	switch (lines)
	{
		case 0:	modeSet[1] = 0x38;
				I2CMasterWriteBuf(DOGS_SLAVE_ADDRESS, modeSet, 2);
				break;
		case 1: modeSet[2] = 0x1F;
				I2CMasterWriteBuf(DOGS_SLAVE_ADDRESS, modeSet, 4);
				break;
		case 2: modeSet[2] = 0x17;
				I2CMasterWriteBuf(DOGS_SLAVE_ADDRESS, modeSet, 4);
				break;
		case 3: modeSet[2] = 0x13;
				I2CMasterWriteBuf(DOGS_SLAVE_ADDRESS, modeSet, 4);
				break;		
		case 4: modeSet[2] = 0x1B;
				I2CMasterWriteBuf(DOGS_SLAVE_ADDRESS, modeSet, 4);
				break;		
		default:	
				break;
	}
}

void DOGS_WriteRow(char* s, uint8_t len, uint8_t row)	// send line to the LCD 
{
	uint8_t i;
	char c;
	DOGSbuf[0] = 0x80;					// 1st control byte
	DOGSbuf[1] = row + DOGSview;		// set cursor
	DOGSbuf[2] = 0x40;					// last control byte
	for (i=0; i<len; i++)				// add string to buffer
	{
		c = *s;
		if (c)
		{
			DOGSbuf[i+3] = (uint8_t) c;
			s++;
		}
		else 
			break;
	}
	for ( ; i<10; i++)
		DOGSbuf[i+3] = ' ';	
	I2CMasterWriteBuf(DOGS_SLAVE_ADDRESS, DOGSbuf, 10+3); 
}
