//
// MSP430 LCD Code
//

#include  "msp430g2553.h"


#define HD44780_H_

#define LCM_DIR P1DIR
#define LCM_OUT P1OUT

// Определяем карту соответствия пинов индикатора контроллеру
// Для простоты зададим соответствие пинов номерам выводов порта 4,5,6,7

#define LCM_PIN_RS BIT0 // P1.0
#define LCM_PIN_EN BIT1 // P1.1
#define LCM_PIN_D7 BIT7 // P1.7
#define LCM_PIN_D6 BIT6 // P1.6
#define LCM_PIN_D5 BIT5 // P1.5
#define LCM_PIN_D4 BIT4 // P1.4



#define     LCM_PIN_MASK  ((LCM_PIN_RS | LCM_PIN_EN | LCM_PIN_D7 | LCM_PIN_D6 | LCM_PIN_D5 | LCM_PIN_D4))

#define     FALSE                 0
#define     TRUE                  1

void PulseLcm()
{
    LCM_OUT &= ~LCM_PIN_EN;    // pull EN bit low
    __delay_cycles(200);
    LCM_OUT |= LCM_PIN_EN;    // pull EN bit high
    __delay_cycles(200);
    LCM_OUT &= (~LCM_PIN_EN);    // pull EN bit low again
    __delay_cycles(200);
}

void SendByte(char ByteToSend, int IsData)
{
    LCM_OUT &= (~LCM_PIN_MASK);
    LCM_OUT |= (ByteToSend & 0xF0);

    if (IsData == TRUE)
    {
        LCM_OUT |= LCM_PIN_RS;
    }
    else
    {
        LCM_OUT &= ~LCM_PIN_RS;
    }
    PulseLcm();
    LCM_OUT &= (~LCM_PIN_MASK);
    LCM_OUT |= ((ByteToSend & 0x0F) << 4);

    if (IsData == TRUE)
    {
        LCM_OUT |= LCM_PIN_RS;
    }
    else
    {
        LCM_OUT &= ~LCM_PIN_RS;
    }
    PulseLcm();
}
void LcmSetCursorPosition(char Row, char Col)    // construct address from (Row, Col) pair
{
    char address;
    if (Row == 0)//     Row - zero based row number
    {
        address = 0;
    }
    else
    {
        address = 0x40;
    }
    address |= Col;//     Col - zero based col number
    SendByte(0x80 | address, FALSE);
}
void ClearLcmScreen()
{
    SendByte(0x01, FALSE);
    SendByte(0x02, FALSE);
}
void InitializeLcm(void)
{
    LCM_DIR |= LCM_PIN_MASK;    // set the MSP pin configurations
    LCM_OUT &= ~(LCM_PIN_MASK);    // and bring them to low
    __delay_cycles(100000);
// 1. Set 4-bit input
    LCM_OUT &= ~LCM_PIN_RS;
    LCM_OUT &= ~LCM_PIN_EN;
    LCM_OUT = 0x20;
    PulseLcm();
    SendByte(0x28, FALSE);    // set 4-bit input - second time.(as reqd by the spec.)
    SendByte(0x0C, FALSE);    // 2. Display on, cursor off, blink cursor off
    SendByte(0x06, FALSE);    // 3. Cursor move auto-increment
}
void PrintStr(char *Text)
{
    char *c;

    c = Text;

    while ((c != 0) && (*c != 0))
    {
        SendByte(*c, TRUE);
        c++;
    }
}
void HD44780_outdec(long data, unsigned char ndigits){
	unsigned char sign, s[6];
	unsigned int i;
	sign = ' ';
	if(data < 0) {
		sign='-';
		data = -data;
	}
	i = 0;
	do {
		s[i++] = data % 10 + '0';
		if(i == ndigits) {
			s[i++]='.';
		}
	} while( (data /= 10) > 0);
	s[i] = sign;
for (i = 0; i<5; i++){
    SendByte(s[4-i], TRUE);
}
}


