Bài cuối về LCD. Hoạt động theo 8bit interface, có hỏi cờ bận đảm bảo LCD luôn thực thi đúng lệnh yêu cầu ! Chú ý việc hỏi cờ bận là hết sức cần thiết!
Một điều nữa là Protues mô phỏng cho LCD hơi cà thoạt, nên dùng Picsimulator.Tốt nhất kiếm 1 chú LCD làm cho xom!
Chương trình hiển thị dòng chữ "WONDERFUL PICVIETNAM!",tham khảo source code của CCS C.
Code:
/*-----------------------------------------------------------------------------
* Author : nhh
* Date : 05/04/06
* Hardware : PIC16F877A
* Compiler : CCS C 3.249
* Description : Hien thi LCD
*=============================================================================*/
#include <16F877A.h>
#include <DEFS_16F877A.h>
#fuses XT,NOWDT,NOPROTECT,NOLVP
#use delay(clock=4000000)
#define E RD2
#define RS RD0
#define RW RD1
#byte lcd_data = 0x06 // Dia chi PORTB
/* Khai bao nguyen mau cac ham su dung */
byte lcd_read_byte();
void lcd_send_byte( byte address, byte n );
void lcd_init();
void lcd_gotoxy( byte x, byte y);
void lcd_putc( char c);
void lcd_refresh();
/* Doc mot byte tu LCD */
byte lcd_read_byte()
{
byte read_byte;
set_tris_B(0xFF); // PORTB = input
RW = 1;
delay_cycles(1);
E = 1;
delay_cycles(1);
read_byte = lcd_data;
E = 0;
set_tris_B(0x00); // PORTB = output
return(read_byte);
}
/* Goi 1byte den LCD */
void lcd_send_byte( byte address, byte n )
{
RS = 0;
while ( bit_test(lcd_read_byte(),7) ) ;
RS = address;
delay_cycles(1);
RW = 0;
delay_cycles(1);
E = 0;
lcd_data = n;
delay_cycles(1);
E = 1;
delay_us(2);
E = 0;
}
/* Khoi tao ban dau cho LCD */
void lcd_init()
{
byte const lcd_init_string[4] = {0x38, 0x0C, 1 , 6};
byte i;
set_tris_B(0x00);
RS = 0;
RW = 0;
E = 0;
delay_ms(15);
for(i=1;i<=3;++i)
{
lcd_data = 3;
delay_cycles(1);
E = 1;
delay_us(2);
E = 0;
delay_ms(5);
}
lcd_data = 2;
delay_cycles(1);
E = 1;
delay_us(2);
E = 0;
delay_ms(5);
for(i=0;i<=3;++i)
{
lcd_send_byte(0,lcd_init_string[i]);
}
}
/* Nhay den vi tri (x,y) tren LCD,nhay nham y se bao loi */
void lcd_gotoxy( byte x, byte y)
{
byte address;
switch(y)
{
case 1: address=0;
address+=x-1;
lcd_send_byte(0,0x80|address);
break;
case 2: address=0x40;
address+=x-1;
lcd_send_byte(0,0x80|address);
break;
default :lcd_init();
lcd_putc("ERROR Y POSITION");
while(true); // Dung tai day!
}
}
/* Hien thi ki tu hoac chuoi ra LCD */
void lcd_putc( char c)
{
lcd_send_byte(1,c);
}
/* Hien thi ki tu hoac chuoi ra LCD */
void lcd_refresh()
{
lcd_send_byte(0,1);
lcd_send_byte(0,6);
}
/* Ham main */
void main (void)
{
set_tris_B(0); //PORTB = output
set_tris_D(0); //PORTD = output
lcd_init();
lcd_gotoxy(5,1);
lcd_putc("WONDERFUL");
lcd_gotoxy(4,2);
lcd_putc("PICVIETNAM!");
}
Nên gom các hàm trên thành 1 file lcd_8bit.c chẳng hạn, đến khi sử dụng chỉ việc include nó vào cho khỏe...
