51单片机驱动OLED屏幕代码
时间: 2023-07-02 22:21:52 浏览: 353
以下是一个简单的51单片机驱动OLED屏幕的代码示例:
```c
#include <reg51.h>
#include <intrins.h>
sbit OLED_SCL=P1^0; //时钟线
sbit OLED_SDA=P1^1; //数据线
#define OLED_ADDRESS 0x78 //OLED屏幕的地址
//OLED屏幕初始化函数
void OLED_Init()
{
OLED_Write_Command(0xAE); //关闭OLED屏幕显示
OLED_Write_Command(0xD5); //设置时钟分频因子,震荡频率
OLED_Write_Command(0x80); //分频因子为1,频率为约1000kHz
OLED_Write_Command(0xA8); //设置驱动路数
OLED_Write_Command(0x3F); //默认为0x3F(1/64duty)
OLED_Write_Command(0xD3); //设置显示偏移
OLED_Write_Command(0x00); //默认为0x00
OLED_Write_Command(0x40); //设置起始行
OLED_Write_Command(0x8D); //设置电荷泵
OLED_Write_Command(0x14); //开启电荷泵
OLED_Write_Command(0x20); //设置内存地址模式
OLED_Write_Command(0x02); //设置为页寻址模式
OLED_Write_Command(0xA1); //段重定向设置
OLED_Write_Command(0xC8); //设置COM扫描方向
OLED_Write_Command(0xDA); //设置COM硬件引脚
OLED_Write_Command(0x12); //默认为0x02(COM63~COM0)
OLED_Write_Command(0x81); //设置对比度
OLED_Write_Command(0xCF); //默认为0x7F
OLED_Write_Command(0xD9); //设置预充电周期
OLED_Write_Command(0xF1); //默认为0x22(1个时钟,0x22为2个时钟)
OLED_Write_Command(0xDB); //设置VCOMH
OLED_Write_Command(0x40); //默认为0x20,范围0x00~0x7F
OLED_Write_Command(0xA4); //设置全局显示开启
OLED_Write_Command(0xA6); //设置显示方式
OLED_Write_Command(0xAF); //开启OLED屏幕显示
}
//向OLED屏幕写入命令
void OLED_Write_Command(unsigned char command)
{
unsigned char i;
OLED_SCL=0;
OLED_SDA=0;
OLED_SCL=1;
OLED_SCL=0;
OLED_SDA=0;
for(i=0;i<8;i++)
{
if(command&0x80) OLED_SDA=1;
else OLED_SDA=0;
OLED_SCL=1;
OLED_SCL=0;
command=command<<1;
}
}
//向OLED屏幕写入数据
void OLED_Write_Data(unsigned char data)
{
unsigned char i;
OLED_SCL=0;
OLED_SDA=1;
OLED_SCL=1;
OLED_SCL=0;
OLED_SDA=0;
for(i=0;i<8;i++)
{
if(data&0x80) OLED_SDA=1;
else OLED_SDA=0;
OLED_SCL=1;
OLED_SCL=0;
data=data<<1;
}
}
//清除OLED屏幕显示
void OLED_Clear()
{
unsigned char i,j;
for(i=0;i<8;i++)
{
OLED_Write_Command(0xB0+i); //设置页地址
OLED_Write_Command(0x00); //设置列地址低位
OLED_Write_Command(0x10); //设置列地址高位
for(j=0;j<128;j++) OLED_Write_Data(0x00); //清空这一页的所有列
}
}
//在OLED屏幕上显示一个字符
void OLED_Write_Char(unsigned char x,unsigned char y,unsigned char c)
{
unsigned char i,j;
c=c-' '; //将字符转化为字模编号,从' '开始
OLED_Write_Command(0xB0+y); //设置页地址
OLED_Write_Command(((x&0xF0)>>4)|0x10); //设置列地址高位
OLED_Write_Command((x&0x0F)|0x01); //设置列地址低位
for(i=0;i<8;i++)
{
OLED_Write_Data(font[c*8+i]); //写入8个字节的字模数据
}
}
//在OLED屏幕上显示一串字符串
void OLED_Write_String(unsigned char x,unsigned char y,unsigned char *s)
{
while(*s) //逐个字符显示
{
OLED_Write_Char(x,y,*s);
x+=8;
s++;
}
}
//延时函数
void delay(unsigned int t)
{
unsigned int i,j;
for(i=0;i<t;i++)
{
for(j=0;j<120;j++);
}
}
void main()
{
OLED_Init(); //初始化OLED屏幕
OLED_Clear(); //清除OLED屏幕显示
OLED_Write_String(0,0,"Hello, world!"); //在OLED屏幕上显示一串字符串
while(1);
}
```
需要注意的是,这段代码中使用的字模数据需要根据具体的OLED屏幕型号进行修改。
阅读全文