基于51单片机BH1750光照传感器,使用四脚OLED显示代码
时间: 2024-01-24 10:05:36 浏览: 188
好的,以下是基于51单片机BH1750光照传感器,使用四脚OLED显示的代码:
```c
#include <reg51.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
#define SCL P3_6
#define SDA P3_7
sbit OLED_SCL = P1^0;
sbit OLED_SDA = P1^1;
void delay(uint t)
{
uint i;
while(t--)
{
for(i=0; i<125; i++);
}
}
void IIC_Start()
{
SDA = 1;
SCL = 1;
_nop_();
_nop_();
_nop_();
SDA = 0;
_nop_();
_nop_();
_nop_();
SCL = 0;
}
void IIC_Stop()
{
SDA = 0;
_nop_();
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
SDA = 1;
}
void IIC_SendByte(uchar dat)
{
uchar i;
for(i=0; i<8; i++)
{
SDA = dat & 0x80;
dat <<= 1;
_nop_();
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
SCL = 0;
}
}
uchar IIC_ReadByte()
{
uchar i, dat = 0;
SDA = 1;
for(i=0; i<8; i++)
{
_nop_();
_nop_();
_nop_();
SCL = 1;
dat <<= 1;
dat |= SDA;
_nop_();
_nop_();
_nop_();
SCL = 0;
}
return dat;
}
void OLED_Init()
{
OLED_SCL = 1;
OLED_SDA = 1;
delay(100);
OLED_SCL = 0;
delay(200);
OLED_SCL = 1;
OLED_SDA = 0;
delay(200);
OLED_SDA = 1;
delay(200);
}
void OLED_WriteCmd(uchar cmd)
{
IIC_Start();
IIC_SendByte(0x78);
IIC_SendByte(0x00);
IIC_SendByte(cmd);
IIC_Stop();
}
void OLED_WriteData(uchar dat)
{
IIC_Start();
IIC_SendByte(0x78);
IIC_SendByte(0x40);
IIC_SendByte(dat);
IIC_Stop();
}
void OLED_SetPos(uchar x, uchar y)
{
OLED_WriteCmd(0xb0+y);
OLED_WriteCmd(((x&0xf0)>>4)|0x10);
OLED_WriteCmd((x&0x0f)|0x01);
}
void OLED_Fill(uchar dat)
{
uchar i, j;
for(i=0; i<8; i++)
{
OLED_WriteCmd(0xb0+i);
OLED_WriteCmd(0x00);
OLED_WriteCmd(0x10);
for(j=0; j<128; j++)
{
OLED_WriteData(dat);
}
}
}
void OLED_ShowChar(uchar x, uchar y, uchar chr)
{
uchar i;
chr -= 32;
OLED_SetPos(x, y);
for(i=0; i<6; i++)
{
OLED_WriteData(font6x8[chr][i]);
}
}
void OLED_ShowString(uchar x, uchar y, uchar *str)
{
while(*str != '\0')
{
OLED_ShowChar(x, y, *str);
x += 6;
str++;
}
}
void BH1750_Init()
{
IIC_Start();
IIC_SendByte(0x46);
IIC_Stop();
}
uchar BH1750_ReadData()
{
uchar dat1, dat2;
IIC_Start();
IIC_SendByte(0x46);
IIC_Stop();
delay(20);
IIC_Start();
IIC_SendByte(0x47);
dat1 = IIC_ReadByte();
dat2 = IIC_ReadByte();
IIC_Stop();
return dat2;
}
void main()
{
uchar dat;
OLED_Init();
BH1750_Init();
OLED_Fill(0x00);
OLED_ShowString(0, 0, "Light:");
while(1)
{
dat = BH1750_ReadData();
OLED_SetPos(48, 0);
OLED_ShowChar(48, 0, '0'+dat/100);
OLED_ShowChar(54, 0, '0'+dat%100/10);
OLED_ShowChar(60, 0, '0'+dat%10);
delay(500);
}
}
```
需要注意的是,此代码中引用了一个字库,需要在代码中自己添加字库的定义。
阅读全文