|      这个实例,通过PORTA来驱动LCD1602.具体代码如下:#include <mega16.h>
 #include <delay.h>
 
 #define LCD_DATA_PORT  PORTA   //the next three port should be the same
 #define LCD_DATA_DDR   DDRA    //must use the high 4bit
 #define LCD_DATA_PIN   PINA
 #define LCD_RS         PORTA.0 //RS lcd#define LCD_WR         PORTA.1//WR lcd
 #define LCD_EN         PORTA.2 //EN lcd
 #define LCD_DRS        DDRA.0  //WR direction define
 #define LCD_DWR        DDRA.1  //RS direction define
 #define LCD_DEN        DDRA.2  //EN direction define
 #define LCD_DATA       0xf0    //DATA PORT
 #define uchar unsigned char
 #define uint unsigned int
 /*LCD_Write(1,command)
 1602 command:0x0f show cursor and flash
 0x0c do now show cursor
 
 */
 void LCD_en_write(void)  //enable LCD
 {
 LCD_DEN=1;//SET LCD_EN OUTPUT
 LCD_EN=1;//EN=1
 delay_us(10);
 LCD_EN=0;//EN=0
 }
 //cord:when 1,write command when 0,write data
 //data:command or data you want to write to 1602
 void LCD_Write(char cord,unsigned char data) //write data
 {
 delay_us(25);
 LCD_DRS=1;//SET RS OUTPUT
 if(cord==0)LCD_RS=1; //RS=1,write data
 else LCD_RS=0;//RS=0,write command
 LCD_DATA_PORT&=0X0f;       //clr high 4bit
 LCD_DATA_PORT|=data&0xf0;  //wirte high 4bit
 LCD_en_write();
 data=data<<4;               //turn the low 4bit to high 4bit
 LCD_DATA_PORT&=0X0f;        //clr high 4bit
 LCD_DATA_PORT|=data&0xf0;   //write low 4bit
 LCD_en_write();
 }
 void LCD_init(void)       //lcd init
 {
 LCD_DWR=1;//set en output
 LCD_WR=0;//write enable
 LCD_DATA_DDR|=LCD_DATA;   //set data port out
 LCD_EN=1;// set EN out
 LCD_RS=1;// set RS out
 delay_us(40);
 LCD_Write(1,0x28);  //4bit show
 LCD_Write(1,0x0c);  //do now show cursor
 LCD_Write(1,0x01);  //clr
 delay_ms(2);
 }
 //orientation a dress
 //x:0 or 1
 //y:0-15
 void LCD_set_xy( unsigned char x, unsigned char y )  //write address funcation
 {
 unsigned char address;
 if (y==0) address=0x80+x;
 else address=0xc0+x;
 LCD_Write(1,address);
 }
 //from a appointed address write string to 1602
 //col x=0~15,row y=0,1
 void LCD_write_string(unsigned char X,unsigned char Y,unsigned char flash *s)
 {
 LCD_set_xy(X,Y); //write address
 while (*s)  // write the char to show
 {
 LCD_Write(0,*s);
 s++;
 }
 
 }
 //write a char to appointed address
 void LCD_write_char(unsigned char X,unsigned char Y,unsigned char data) //col x=0~15,row y=0,1
 {
 LCD_set_xy(X,Y); //write address
 LCD_Write(0,data);
 
 }
 void main(void)
 {
 unsigned char temp[]="HELLO WORLD!!";
 unsigned char t,i;
    delay_ms(200);//delay 4sLCD_init();
 LCD_Write(1,0x0c);
 for(;;)
 {
 for(t=0;t<16;t++)
 {
 LCD_write_char(t,0,temp[t]);
 delay_ms(200);
 }
 LCD_write_string(0,1,"haha ^_^ haha...");
 delay_ms(1000);
 LCD_Write(1,0x01);//clr
 delay_ms(5);//between two command must delay at list 5ms
 LCD_write_char(0,0,223);//temp
 delay_ms(4000);
 LCD_init();
 
 }
 
 }
 |