C51用GY39光强检测通过串口通信CT连RXD,DR连TXD,用LCD1602显示代码
时间: 2024-05-03 18:18:00 浏览: 127
以下是基于C51单片机使用GY39光强检测器并通过串口通信将数据显示在LCD1602上的代码,你可以参考一下:
```
#include <reg51.h>
#include <stdio.h>
#define LCD1602_DB P0
sbit LCD1602_RS = P2^0;
sbit LCD1602_RW = P2^1;
sbit LCD1602_E = P2^2;
sbit CT = P3^0;
sbit DR = P3^1;
sbit LED = P1^0;
unsigned char LCD1602_Read_Busy()
{
unsigned char sta;
LCD1602_DB = 0xFF;
LCD1602_RS = 0;
LCD1602_RW = 1;
do
{
LCD1602_E = 1;
sta = LCD1602_DB;
LCD1602_E = 0;
}while(sta & 0x80);
return sta;
}
void LCD1602_Write_Command(unsigned char cmd)
{
LCD1602_Read_Busy();
LCD1602_RS = 0;
LCD1602_RW = 0;
LCD1602_DB = cmd;
LCD1602_E = 1;
LCD1602_E = 0;
}
void LCD1602_Write_Data(unsigned char dat)
{
LCD1602_Read_Busy();
LCD1602_RS = 1;
LCD1602_RW = 0;
LCD1602_DB = dat;
LCD1602_E = 1;
LCD1602_E = 0;
}
void LCD1602_Init()
{
LCD1602_Write_Command(0x38); //8位数据接口,2行显示,5x7点阵字符
LCD1602_Write_Command(0x0C); //显示开,关游标,不闪烁
LCD1602_Write_Command(0x06); //光标移动,不移动屏幕
LCD1602_Write_Command(0x01); //清屏
}
void LCD1602_Show_String(unsigned char x, unsigned char y, unsigned char *str)
{
unsigned char i = 0;
if(x < 16 && y < 2)
{
if(y == 0)
LCD1602_Write_Command(0x80 + x);
else
LCD1602_Write_Command(0xC0 + x);
while(str[i] != '\0')
{
LCD1602_Write_Data(str[i]);
i++;
}
}
}
void UART_Init()
{
TMOD = 0x20;
TH1 = 0xFD;
TL1 = TH1;
SCON = 0x50;
TR1 = 1;
}
unsigned char UART_IsRxReady()
{
return RI;
}
unsigned char UART_ReadByte()
{
RI = 0;
return SBUF;
}
void UART_WriteByte(unsigned char dat)
{
SBUF = dat;
while(TI == 0);
TI = 0;
}
unsigned char GY39_ReadData(unsigned char reg_addr)
{
unsigned char dat;
CT = 0;
DR = 1;
DR = 0;
UART_WriteByte(reg_addr);
dat = UART_ReadByte();
CT = 1;
return dat;
}
void main()
{
unsigned char str[16];
unsigned char data;
LCD1602_Init();
UART_Init();
while(1)
{
data = GY39_ReadData(0x10);
LED = data > 128 ? 1 : 0; // 光强度大于128时点亮LED
sprintf(str, "Light: %d", data);
LCD1602_Show_String(0, 0, str);
delay(500);
}
}
```
注意:此代码仅供参考,具体实现可能需要根据实际情况进行修改。
阅读全文