在51开发板将503写入开发板的AT24C02储存器,并读出来显示在LCD上,按键控制数字加一,用c写出相应的代码
时间: 2024-02-12 22:06:38 浏览: 61
51单片机源码程序-将按键次数写入AT24C02,再读出并用1602LCD显示.zip
5星 · 资源好评率100%
好的,下面是一份在51单片机开发板上实现的代码,仅供参考:
```c
#include <reg51.h>
#include <intrins.h>
#define I2C_SCL P2_1
#define I2C_SDA P2_0
#define LCD_RS P1_0
#define LCD_RW P1_1
#define LCD_EN P1_2
#define LCD_DAT P0
void delay(unsigned int t)
{
unsigned int i;
while (t--)
{
for (i = 0; i < 125; i++);
}
}
void i2c_start()
{
I2C_SDA = 1;
I2C_SCL = 1;
delay(1);
I2C_SDA = 0;
delay(1);
I2C_SCL = 0;
}
void i2c_stop()
{
I2C_SDA = 0;
I2C_SCL = 1;
delay(1);
I2C_SDA = 1;
delay(1);
}
void i2c_write(unsigned char dat)
{
unsigned char i;
for (i = 0; i < 8; i++)
{
I2C_SCL = 0;
I2C_SDA = dat & 0x80;
delay(1);
I2C_SCL = 1;
delay(1);
dat <<= 1;
}
I2C_SCL = 0;
I2C_SDA = 1;
delay(1);
I2C_SCL = 1;
delay(1);
}
unsigned char i2c_read(unsigned char ack)
{
unsigned char i, dat = 0;
I2C_SCL = 0;
I2C_SDA = 1;
delay(1);
for (i = 0; i < 8; i++)
{
I2C_SCL = 1;
delay(1);
dat <<= 1;
dat |= I2C_SDA;
I2C_SCL = 0;
delay(1);
}
I2C_SDA = ack;
delay(1);
I2C_SCL = 1;
delay(1);
I2C_SCL = 0;
I2C_SDA = 1;
return dat;
}
void lcd_write_cmd(unsigned char cmd)
{
LCD_RS = 0;
LCD_RW = 0;
LCD_DAT = cmd;
LCD_EN = 1;
_nop_();
_nop_();
LCD_EN = 0;
}
void lcd_write_dat(unsigned char dat)
{
LCD_RS = 1;
LCD_RW = 0;
LCD_DAT = dat;
LCD_EN = 1;
_nop_();
_nop_();
LCD_EN = 0;
}
void lcd_init()
{
lcd_write_cmd(0x38);
lcd_write_cmd(0x0c);
lcd_write_cmd(0x06);
lcd_write_cmd(0x01);
}
void lcd_clear()
{
lcd_write_cmd(0x01);
}
void lcd_puts(unsigned char x, unsigned char y, unsigned char *str)
{
if (y == 1) lcd_write_cmd(0x80 + x);
else lcd_write_cmd(0xc0 + x);
while (*str)
{
lcd_write_dat(*str++);
}
}
void main()
{
unsigned char num = 0;
unsigned char str[16];
unsigned char i2c_ack;
lcd_init();
lcd_clear();
// 将数字503写入AT24C02储存器中
i2c_start();
i2c_write(0xa0);
i2c_ack = i2c_read(1);
i2c_write(0x00);
i2c_ack = i2c_read(1);
i2c_write(5);
i2c_ack = i2c_read(1);
i2c_write(0);
i2c_ack = i2c_read(1);
i2c_write(3);
i2c_ack = i2c_read(0);
i2c_stop();
// 读取AT24C02储存器中的数据并显示在LCD屏幕上
i2c_start();
i2c_write(0xa0);
i2c_ack = i2c_read(1);
i2c_write(0x00);
i2c_ack = i2c_read(1);
i2c_start();
i2c_write(0xa1);
i2c_ack = i2c_read(1);
num = i2c_read(0);
i2c_stop();
sprintf(str, "Number: %d", num);
lcd_puts(0, 0, str);
// 循环检测按键输入并更新数字
while (1)
{
if (P3_4 == 0)
{
num++;
sprintf(str, "Number: %d", num);
lcd_clear();
lcd_puts(0, 0, str);
delay(500);
}
}
}
```
需要注意的是,51单片机开发板的I2C总线通信需要手动模拟,因此需要编写一些底层的I2C读写函数。此外,LCD显示屏的控制也需要编写相应的底层驱动程序。具体实现细节和调整可能会因为硬件设备的不同而有所变化,如果遇到问题,可以适当调整代码或者咨询专业人士。
阅读全文