16×2 LCD(1602A) interfacing with ATMEGA328p 4-bit mode

The code is not tested for output.
Blocks are shown instead of chars.

#include <avr/io.h>
#include <util/delay.h>

#define LCD_DATA_DDR DDRD
#define LCD_CTRL_DDR DDRB
#define LCD_DataBus PORTD  //Using PD4 to PD7
#define LCD_CTRL_PORT PORTB

//function prototypes
void LCD_Write(unsigned char cmd, unsigned char reg_select);
void LCD_WriteData(char data);
void LCD_WriteCmd(char cmd);
void LCD_Init();

void LCD_Write(unsigned char cmd, unsigned char reg_select)
{
  char  tempCmd;
  if(reg_select == 1)
    LCD_CTRL_PORT |= (1<<PB0);   //Select Data Register
  else
    LCD_CTRL_PORT &= ~(1<<PB0);   //Select Command Register

  //Mask data/cmd
  tempCmd = cmd;
  tempCmd &= 0xf0;// mask Lower 4 bits

  //Set data/cmd
  LCD_DataBus &= 0xf0;           //Set PORTD LSB to HIGH since we use PD4 to PD7
  LCD_DataBus |= tempCmd;        //Set bits in PORTD

  //Send data/cmd
  LCD_CTRL_PORT |= (1<<PB1); // Send a High-to-Low pulse at Enable pin
  _delay_ms(400);
  LCD_CTRL_PORT &= ~(1<<PB1); // Send a High-to-Low pulse at Enable pin

  //******Send next 4bits

  //mask data/cmd
  tempCmd = cmd << 4; //shift left 4 times so the LSB bit can be sent.
  tempCmd &= 0xf0; //mask Lower 4 bits

  //Set data/cmd in bus
  LCD_DataBus &= 0xf0;
  LCD_DataBus |= tempCmd;

  //Send data/cmd
  LCD_CTRL_PORT |= (1<<PB1); // Send a High-to-Low pulse at Enable pin
  _delay_ms(400);
  LCD_CTRL_PORT &= ~(1<<PB1); // Send a High-to-Low pulse at Enable pin

  return ;
}

//Send data by setting RS=1.
void LCD_WriteData(char data)
{
  LCD_Write(data, 1);
}

//Send cmd by setting RS=0.
void LCD_WriteCmd(char cmd)
{
  LCD_Write(cmd, 0);
}

void LCD_Init()
{
    LCD_WriteCmd(0x02); // to initialize LCD in 4-bit mode.
    _delay_ms(1);
    LCD_WriteCmd(0x28); //to initialize LCD in 2 lines, 5X7 dots and 4bit mode.
    _delay_ms(1);
    LCD_WriteCmd(0x01); // clear LCD
    _delay_ms(1);
    LCD_WriteCmd(0x0E); // cursor ON
    _delay_ms(1);
    LCD_WriteCmd(0x80); // —8 go to first line and –0 is for 0th position
    _delay_ms(1);
    return;
}

int main(void)
{
    LCD_DATA_DDR |= 0xf0;  //set the LCD DDRD to output
    LCD_CTRL_DDR |= 0b00000011; //For RS, E

    LCD_Init();
    _delay_ms(30);
    LCD_WriteData('a');
    LCD_WriteData('2');
    while(1)
    {

    }//while
}

About PraveenMax
My Interests: ------------------ Programming , Drawing & Music

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: