使用51单片机和lcd1602打招呼
1.LCD驱动程序
1.1 驱动头文件
lcd1602.h
#ifndef LCD1602_H #define LCD1602_H #include <reg51.h> // 定义LCD1602端口 sbit RS = P2^0; // 指令/数据选择 sbit RW = P2^1; // 读/写选择 sbit EN = P2^2; // 使能信号 void LCD_Init(); void LCD_CmdWrite(unsigned char cmd); void LCD_DataWrite(unsigned char dat); void LCD_Clear(); void LCD_WriteString(char *str); void LCD_SetCursor(unsigned char row, unsigned char col); #endif // LCD1602_H
1.2 驱动源文件
lcd1602.c
#include "lcd1602.h" void delay_ms(unsigned int count) { // 等待一段时间的延迟函数,具体实现根据需要调整 while(count--) { unsigned int i; for(i = 0; i < 1000; i++); } } void LCD_Init() { delay_ms(15); LCD_CmdWrite(0x38); LCD_CmdWrite(0x0C); LCD_CmdWrite(0x06); LCD_CmdWrite(0x01); delay_ms(2); } void LCD_CmdWrite(unsigned char cmd) { RS = 0; RW = 0; P0 = cmd; EN = 1; delay_ms(1); EN = 0; } void LCD_DataWrite(unsigned char dat) { RS = 1; RW = 0; P0 = dat; EN = 1; delay_ms(1); EN = 0; } void LCD_Clear() { LCD_CmdWrite(0x01); delay_ms(2); } void LCD_WriteString(char *str) { while (*str) { LCD_DataWrite(*str); str++; } } void LCD_SetCursor(unsigned char row, unsigned char col) { unsigned char address; if (row == 1) { address = 0x80 + col - 1; } else { address = 0xC0 + col - 1; } LCD_CmdWrite(address); }
2.主程序
main.c
#include <reg51.h> #include "driver/lcd1602.h" void main() { LCD_Init(); // 初始化LCD1602 LCD_Clear(); // 清屏 LCD_SetCursor(1, 1); // 设置光标位置为第一行第一列 LCD_WriteString("Hello, Navy!"); while (1); // 程序进入死循环 }
3.仿真电路
4.仿真效果
5。项目地址
https://gitee.com/navysummer/at89c51/tree/master/lcd1602