51单片机控制LCD1602中LCD_Display_String(, , );如何加入变量进行显示
时间: 2023-06-18 19:06:39 浏览: 118
51单片机控制1602LCD显示程序.pdf
如果你想要在LCD1602上显示变量,你可以使用C语言中的sprintf()函数将变量转换成字符串,然后再将字符串输出到LCD1602上。
以下是一个示例代码:
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <reg51.h>
#define LCD_DATA P1
sbit RS = P2^0;
sbit RW = P2^1;
sbit EN = P2^2;
void LCD_Init();
void LCD_Write_Cmd(unsigned char cmd);
void LCD_Display_Char(unsigned char dat);
void LCD_Display_String(unsigned char x, unsigned char y, unsigned char *str);
void LCD_Delay(unsigned int t);
void main()
{
unsigned int num = 1234;
unsigned char str[16];
LCD_Init();
sprintf(str, "Num = %d", num);
LCD_Display_String(0, 0, str);
}
void LCD_Display_String(unsigned char x, unsigned char y, unsigned char *str)
{
if(x < 16)
{
if(y == 0)
{
LCD_Write_Cmd(0x80 + x);
}
else if(y == 1)
{
LCD_Write_Cmd(0xC0 + x);
}
while(*str)
{
LCD_Display_Char(*str++);
}
}
}
void LCD_Display_Char(unsigned char dat)
{
RS = 1;
RW = 0;
LCD_DATA = dat;
EN = 1;
LCD_Delay(1);
EN = 0;
LCD_Delay(1);
}
void LCD_Init()
{
LCD_Write_Cmd(0x38);
LCD_Write_Cmd(0x0C);
LCD_Write_Cmd(0x06);
LCD_Write_Cmd(0x01);
}
void LCD_Write_Cmd(unsigned char cmd)
{
RS = 0;
RW = 0;
LCD_DATA = cmd;
EN = 1;
LCD_Delay(1);
EN = 0;
LCD_Delay(1);
}
void LCD_Delay(unsigned int t)
{
unsigned int i, j;
for(i = 0; i < t; i++)
{
for(j = 0; j < 120; j++);
}
}
```
在这个例子中,我们定义了一个整数变量num,然后使用sprintf()函数将它转换成字符串,并将结果存储在数组str中。然后,我们调用LCD_Display_String()函数将字符串输出到LCD1602上。在LCD_Display_String()函数中,可以看到我们使用了while循环来逐个输出字符串中的字符。
阅读全文