stm32写I2c驱动oled代码
时间: 2023-09-16 09:15:07 浏览: 61
下面是使用STM32的I2C驱动OLED的基本代码示例:
```
#include "stm32f10x.h"
#include "i2c.h"
#define OLED_I2C_ADDR 0x78 // OLED I2C地址
// OLED初始化命令序列
const uint8_t oled_init_cmds[] = {
0xAE, // 关闭显示
0xD5, 0x80, // 设置时钟分频因子,震荡器频率
0xA8, 0x3F, // 设置驱动路数
0xD3, 0x00, // 设置显示偏移
0x40, // 设置显示开始线--0
0x8D, 0x14, // 设置显示模式,开启内部电源
0x20, 0x00, // 设置内存地址模式
0xA1, // 设置SEG方向
0xC8, // 设置COM方向
0xDA, 0x12, // 设置COM硬件引脚配置
0x81, 0xCF, // 设置对比度
0xD9, 0xF1, // 设置预充电周期
0xDB, 0x40, // 设置VCOMH
0xA4, // 全局显示开启
0xA6, // 设置显示方式
0xAF // 开启显示
};
void oled_init(void) {
i2c_start();
i2c_send_byte(OLED_I2C_ADDR << 1);
i2c_send_byte(0x00);
for (uint8_t i = 0; i < sizeof(oled_init_cmds); i++) {
i2c_send_byte(oled_init_cmds[i]);
}
i2c_stop();
}
void oled_set_pos(uint8_t x, uint8_t y) {
i2c_start();
i2c_send_byte(OLED_I2C_ADDR << 1);
i2c_send_byte(0x00);
i2c_send_byte(0xB0 + y);
i2c_send_byte(((x & 0xF0) >> 4) | 0x10);
i2c_send_byte((x & 0x0F) | 0x01);
i2c_stop();
}
void oled_clear(void) {
for (uint8_t i = 0; i < 8; i++) {
oled_set_pos(0, i);
for (uint8_t j = 0; j < 128; j++) {
i2c_start();
i2c_send_byte(OLED_I2C_ADDR << 1);
i2c_send_byte(0x40);
i2c_send_byte(0x00);
i2c_stop();
}
}
}
void oled_write_char(uint8_t x, uint8_t y, char ch) {
uint8_t c = ch - 32;
if (x > 120) {
x = 0;
y++;
}
oled_set_pos(x, y);
for (uint8_t i = 0; i < 6; i++) {
i2c_start();
i2c_send_byte(OLED_I2C_ADDR << 1);
i2c_send_byte(0x40);
i2c_send_byte(Font6x8[c][i]);
i2c_stop();
x++;
}
}
void oled_write_string(uint8_t x, uint8_t y, char *str) {
while (*str != '\0') {
oled_write_char(x, y, *str++);
}
}
int main(void) {
i2c_init();
oled_init();
oled_clear();
oled_write_string(0, 0, "Hello, world!");
while (1) {
}
}
```
以上代码使用了一个Font6x8数组来存储字形数据。你可以使用自己的字形数据替换它。同时,你需要根据你的硬件环境来修改i2c_init()和i2c_send_byte()函数,以确保它们能够正确地工作。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)