51单片机LCD1602水平滚动代码只显示一行
时间: 2023-07-15 16:14:53 浏览: 49
以下是51单片机LCD1602水平滚动代码,可以显示多行并且水平滚动:
```
#include<reg52.h>
#include<intrins.h>
#define LCD1602_DB P0
sbit LCD1602_RS = P2^6;
sbit LCD1602_RW = P2^5;
sbit LCD1602_E = P2^7;
void delay(unsigned int i);
void write_cmd(unsigned char cmd);
void write_data(unsigned char dat);
void init_lcd1602(void);
void display_string(unsigned char x,unsigned char y,unsigned char *s);
void scroll_display(unsigned char x,unsigned char y,unsigned char *s,unsigned char mode);
void main()
{
init_lcd1602();
while(1)
{
scroll_display(0,1,"Hello World! I am scrolling...",1);
}
}
void delay(unsigned int i)
{
while(i--);
}
void write_cmd(unsigned char cmd)
{
LCD1602_RS = 0;
LCD1602_RW = 0;
LCD1602_E = 0;
LCD1602_DB = cmd;
delay(5);
LCD1602_E = 1;
delay(5);
LCD1602_E = 0;
}
void write_data(unsigned char dat)
{
LCD1602_RS = 1;
LCD1602_RW = 0;
LCD1602_E = 0;
LCD1602_DB = dat;
delay(5);
LCD1602_E = 1;
delay(5);
LCD1602_E = 0;
}
void init_lcd1602(void)
{
write_cmd(0x38); //function set
write_cmd(0x0c); //display on, cursor off, blink off
write_cmd(0x06); //entry mode set, increment cursor
write_cmd(0x01); //clear display
delay(5);
}
void display_string(unsigned char x,unsigned char y,unsigned char *s)
{
unsigned char i;
if (x > 15) x = 0;
if (y > 1) y = 0;
if (y) x |= 0x40;
x |= 0x80;
write_cmd(x);
for(i=0;s[i]!='\0';i++)
{
write_data(s[i]);
}
}
void scroll_display(unsigned char x,unsigned char y,unsigned char *s,unsigned char mode)
{
unsigned char len,i,j;
len = strlen(s);
if(len > 16)
{
for(i=0;i<len-15;i++)
{
display_string(x,y,&s[i]);
delay(1000);
for(j=0;j<16;j++)
{
if(mode == 1) write_cmd(0x18); //scroll left
else write_cmd(0x1c); //scroll right
delay(200);
}
}
}
}
```
这个代码使用了字符串滚动的方式来实现多行显示。函数 `scroll_display()` 可以控制滚动的方向,参数 `mode` 为 1 时表示向左滚动,为 0 时表示向右滚动。