51单片机LCD1602滚动显示数字
时间: 2023-11-22 22:52:15 浏览: 139
以下是51单片机LCD1602滚动显示数字的示例代码:
```c
#include <reg51.h>
#define LCD1602_DB P0
sbit LCD1602_RS = P2^6;
sbit LCD1602_RW = P2^5;
sbit LCD1602_E = P2^7;
void LCD1602_Delay(unsigned int t);
void LCD1602_WriteCmd(unsigned char cmd);
void LCD1602_WriteData(unsigned char dat);
void LCD1602_Init(void);
void LCD1602_Clear(void);
void LCD1602_ShowStr(unsigned char x, unsigned char y, unsigned char *str);
void LCD1602_ShowNum(unsigned char x, unsigned char y, unsigned int num, unsigned char len);
void main()
{
unsigned int num = 0;
unsigned char str[6] = {0};
LCD1602_Init();
while(1)
{
num++;
if(num > 9999) num = 0;
LCD1602_ShowNum(0, 0, num, 4);
LCD1602_Delay(500);
LCD1602_Clear();
}
}
void LCD1602_Delay(unsigned int t)
{
unsigned int i, j;
for(i = 0; i < t; i++)
for(j = 0; j < 100; j++);
}
void LCD1602_WriteCmd(unsigned char cmd)
{
LCD1602_RS = 0;
LCD1602_RW = 0;
LCD1602_E = 1;
LCD1602_DB = cmd;
LCD1602_E = 0;
}
void LCD1602_WriteData(unsigned char dat)
{
LCD1602_RS = 1;
LCD1602_RW = 0;
LCD1602_E = 1;
LCD1602_DB = dat;
LCD1602_E = 0;
}
void LCD1602_Init(void)
{
LCD1602_WriteCmd(0x38); // 初始化LCD
LCD1602_WriteCmd(0x0c); // 打开显示,关闭光标
LCD1602_WriteCmd(0x06); // 设置输入方式为移动光标,不移动屏幕
LCD1602_WriteCmd(0x01); // 清屏
}
void LCD1602_Clear(void)
{
LCD1602_WriteCmd(0x01);
}
void LCD1602_ShowStr(unsigned char x, unsigned char y, unsigned char *str)
{
unsigned char i;
if(x < 16)
{
if(y == 0) LCD1602_WriteCmd(0x80 | x);
else if(y == 1) LCD1602_WriteCmd(0xc0 | x);
for(i = 0; str[i] != '\0'; i++)
LCD1602_WriteData(str[i]);
}
}
void LCD1602_ShowNum(unsigned char x, unsigned char y, unsigned int num, unsigned char len)
{
unsigned char i, j;
unsigned char str[6] = {0};
for(i = 0; i < len; i++)
{
str[i] = num % 10 + '0';
num /= 10;
}
j = i - 1;
for(i = 0; i < j; i++, j--)
{
str[i] ^= str[j];
str[j] ^= str[i];
str[i] ^= str[j];
}
LCD1602_ShowStr(x, y, str);
}
```
示例代码中使用了LCD1602驱动程序,可根据具体情况进行修改。主函数中通过循环不断更新数字,并使用LCD1602_ShowNum函数将数字显示在LCD上。其中LCD1602_ShowNum函数实现了滚动显示数字的功能,通过将数字转换成字符串并逐个显示实现了滚动效果。
阅读全文