/*
 *  for MB9BF618T on FRK-FM3
 * 
 *   Copyright (C) by Y.Ishioka.
 */
#include <basic.h>
#include <tk/tkernel.h>
#include <libstr.h>
#include <tk/syslib.h>
#include <drivers/lcd_char.h>

#include <tk/sysdef.h>


/***********************************************************/
/*
 * data: bit7-0
 * rs  : RS signal
 */
static  void  LCD_putchar( unsigned int data, unsigned int rs )
{
#if USE_CHR_LCD
    unsigned int  reg2 = 0x000;

    if( rs != 0 ) {
        reg2 = 0x100 ;
    }
    /* set RS */
    out_w( GPIO_PDOR7, (in_w(GPIO_PDOR7) & ~0x03ff) | reg2 ) ;
    /* set E */
    out_w( GPIO_PDOR7, (in_w(GPIO_PDOR7) | 0x200) ) ;
    /* set data */
    out_w( GPIO_PDOR7, (in_w(GPIO_PDOR7) | data) ) ;
    /* reset E */
    out_w( GPIO_PDOR7, (in_w(GPIO_PDOR7) & ~0x200) ) ;
    /* reset all */
    out_w( GPIO_PDOR7, (in_w(GPIO_PDOR7) & ~0x03ff) ) ;

    WaitUsec( 40 ) ;
#endif
}


void  lcd_putstr( char *buf, unsigned int line )
{
#if USE_CHR_LCD
    unsigned int  data, rs ;
    char  *pnt ;

    if( line == 0 ) {
        data = 0x80 ;
    } else {
        data = 0xc0 ; /* 0x80 + 0x40(=adrs) */
    }
    rs = 0 ;
    LCD_putchar( data, rs ) ;

    rs = 1 ;
    pnt = buf ;
    while( (data=((unsigned int)*pnt++)&0xff) != 0x00 ) {

#if       USE_CHAR_CHECK
        if( data < 0x20 || 0x7e < data ) {
            continue ;
        }
#endif /* USE_CHAR_CHECK */

        LCD_putchar( data, rs ) ;
    }
#endif
}


void  lcd_clear( void )
{
#if USE_CHR_LCD
    unsigned int  data, rs ;

    /* all clear */
    rs = 0 ;
    data = 0x01 ;
    LCD_putchar( data, rs ) ;
    WaitUsec( 1600 ) ;
#endif
}


/*
 * LCD initialize
 */
void  lcd_init( void )
{
#if USE_CHR_LCD
    unsigned int  data, rs ;

    /* set D0-D7,RS,E pin */
    out_w( GPIO_PFR7, in_w(GPIO_PFR7) & ~0x03ff ) ;  /* set GPIO to bit0-7,8,9 */
    out_w( GPIO_PCR7, in_w(GPIO_PCR7) & ~0x03ff ) ;  /* off pull-up to bit0-9 */
    out_w( GPIO_DDR7, in_w(GPIO_DDR7) |  0x03ff ) ;  /* set output mode to bit0-9 */

    rs = 0 ;

    /* all clear */
    data = 0x01 ;
    LCD_putchar( data, rs ) ;
    WaitUsec( 1600 ) ;

    data = 0x06 ;
    LCD_putchar( data, rs ) ;

    data = 0x0c ;
    LCD_putchar( data, rs ) ;

    data = 0x38 ;
    LCD_putchar( data, rs ) ;
#endif
}

