用stm32f103固件库的0.96oled的iic驱动程序
时间: 2023-10-01 19:10:50 浏览: 105
使用STM32F103固件库的0.96 OLED的I2C驱动程序,您需要以下步骤:
1. 初始化I2C总线
在初始化I2C总线之前,您需要定义I2C引脚的GPIO端口和引脚号。然后,使用以下代码初始化I2C总线:
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE); //开启I2C1时钟
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(GPIOB, &GPIO_InitStructure);
I2C_InitTypeDef I2C_InitStructure;
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = 0x00;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = 400000; //I2C 速率
I2C_Init(I2C1, &I2C_InitStructure);
I2C_Cmd(I2C1, ENABLE);
2. 写入命令或数据
在向OLED写入命令或数据之前,您需要确保OLED的I2C地址已知。下面的代码将OLED的I2C地址设置为0x78,然后向OLED写入命令或数据:
#define OLED_ADD 0x78
void OLED_WR_Byte(unsigned dat, unsigned cmd)
{
I2C_GenerateSTART(I2C1, ENABLE);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT)); //等待I2C总线空闲
I2C_Send7bitAddress(I2C1, OLED_ADD, I2C_Direction_Transmitter);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)); //等待写入模式选择完毕
if (cmd) {
I2C_SendData(I2C1, 0x00);
}
else {
I2C_SendData(I2C1, dat);
}
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED)); //等待数据传输完毕
I2C_GenerateSTOP(I2C1, ENABLE);
}
3. 显示信息
将信息显示在OLED屏幕上的代码如下:
void OLED_ShowStr(unsigned char x, unsigned char y, unsigned char ch[], unsigned char TextSize)
{
unsigned char c = 0, i = 0, j = 0, k = 0;
switch(TextSize)
{
case 1:
for (i = 0; ch[i] != '\0'; i++)
{
c = ch[i] - 32;
if(x > 127)
{
x = 0;
y++;
}
if(y > 7)
{
y = 0;
}
for (j = 0; j < 6; j++)
{
if (j == 5) {
OLED_WR_Byte(0x00, 0);
} else {
OLED_WR_Byte(OLED_ASCII[c][j], 0);
}
x++;
if (x > 127)
{
x = 0;
y++;
if(y > 7) y = 0;
}
}
}
break;
}
}
希望以上步骤能为您提供帮助!
阅读全文