帮我写一个基于51单片机的lcd1602显示浮点数的程序,精确到小数点后两位
时间: 2024-03-10 15:43:21 浏览: 179
1602显示程序
5星 · 资源好评率100%
好的,以下是基于51单片机的lcd1602显示浮点数的程序,精确到小数点后两位:
```c
#include <reg51.h>
#include <stdio.h>
#include <string.h>
#define LCD_DATAPORT P0
sbit LCD_RS = P2^0;
sbit LCD_RW = P2^1;
sbit LCD_EN = P2^2;
void LCD_Init();
void LCD_WriteCommand(unsigned char cmd);
void LCD_WriteData(unsigned char dat);
void LCD_WriteString(unsigned char x, unsigned char y, unsigned char *str);
void LCD_WriteFloat(unsigned char x, unsigned char y, float num);
void main()
{
float num = 3.14;
char str[16];
LCD_Init();
while(1)
{
LCD_WriteFloat(0, 0, num);
}
}
void LCD_Init()
{
LCD_WriteCommand(0x38); // function set
LCD_WriteCommand(0x0c); // display on, cursor off, blink off
LCD_WriteCommand(0x06); // entry mode set
LCD_WriteCommand(0x01); // clear display
LCD_WriteCommand(0x80); // set DDRAM address
}
void LCD_WriteCommand(unsigned char cmd)
{
LCD_RS = 0;
LCD_RW = 0;
LCD_EN = 1;
LCD_DATAPORT = cmd;
LCD_EN = 0;
}
void LCD_WriteData(unsigned char dat)
{
LCD_RS = 1;
LCD_RW = 0;
LCD_EN = 1;
LCD_DATAPORT = dat;
LCD_EN = 0;
}
void LCD_WriteString(unsigned char x, unsigned char y, unsigned char *str)
{
unsigned char addr;
if(y == 0)
{
addr = 0x80 + x;
}
else
{
addr = 0xc0 + x;
}
LCD_WriteCommand(addr);
while(*str != '\0')
{
LCD_WriteData(*str);
str++;
}
}
void LCD_WriteFloat(unsigned char x, unsigned char y, float num)
{
char str[16];
sprintf(str, "%.2f", num);
LCD_WriteString(x, y, str);
}
```
注:该程序中使用了 `sprintf()` 函数,需要包含 `<stdio.h>` 库。
阅读全文