SSD1309 IIC驱动
时间: 2023-07-22 17:16:47 浏览: 474
SSD1309是一款常用的OLED显示屏驱动芯片,支持I2C和SPI两种通信协议。下面是基于I2C协议的驱动代码示例:
首先,需要定义一些寄存器地址和常量:
```c
#define SSD1309_I2C_ADDRESS 0x3C
#define SSD1309_WIDTH 128
#define SSD1309_HEIGHT 64
#define SSD1309_SETCONTRAST 0x81
#define SSD1309_DISPLAYALLON_RESUME 0xA4
#define SSD1309_DISPLAYALLON 0xA5
#define SSD1309_NORMALDISPLAY 0xA6
#define SSD1309_INVERTDISPLAY 0xA7
#define SSD1309_DISPLAYOFF 0xAE
#define SSD1309_DISPLAYON 0xAF
#define SSD1309_SETDISPLAYOFFSET 0xD3
#define SSD1309_SETCOMPINS 0xDA
#define SSD1309_SETVCOMDETECT 0xDB
#define SSD1309_SETDISPLAYCLOCKDIV 0xD5
#define SSD1309_SETPRECHARGE 0xD9
#define SSD1309_SETMULTIPLEX 0xA8
#define SSD1309_SETLOWCOLUMN 0x00
#define SSD1309_SETHIGHCOLUMN 0x10
#define SSD1309_SETSTARTLINE 0x40
#define SSD1309_MEMORYMODE 0x20
#define SSD1309_COLUMNADDR 0x21
#define SSD1309_PAGEADDR 0x22
#define SSD1309_COMSCANINC 0xC0
#define SSD1309_COMSCANDEC 0xC8
#define SSD1309_SEGREMAP 0xA0
#define SSD1309_CHARGEPUMP 0x8D
#define SSD1309_EXTERNALVCC 0x1
#define SSD1309_SWITCHCAPVCC 0x2
```
然后,初始化I2C总线和SSD1309 OLED驱动:
```c
#include <Wire.h>
void ssd1309_init() {
Wire.beginTransmission(SSD1309_I2C_ADDRESS);
Wire.write(SSD1309_DISPLAYOFF);
Wire.write(SSD1309_SETDISPLAYCLOCKDIV);
Wire.write(0x80);
Wire.write(SSD1309_SETMULTIPLEX);
Wire.write(0x3F);
Wire.write(SSD1309_SETDISPLAYOFFSET);
Wire.write(0x00);
Wire.write(SSD1309_SETSTARTLINE | 0x00);
Wire.write(SSD1309_CHARGEPUMP);
Wire.write(0x14);
Wire.write(SSD1309_MEMORYMODE);
Wire.write(0x00);
Wire.write(SSD1309_SEGREMAP | 0x01);
Wire.write(SSD1309_COMSCANDEC);
Wire.write(SSD1309_SETCOMPINS);
Wire.write(0x12);
Wire.write(SSD1309_SETCONTRAST);
Wire.write(0xCF);
Wire.write(SSD1309_SETPRECHARGE);
Wire.write(0xF1);
Wire.write(SSD1309_SETVCOMDETECT);
Wire.write(0x40);
Wire.write(SSD1309_DISPLAYALLON_RESUME);
Wire.write(SSD1309_NORMALDISPLAY);
Wire.write(SSD1309_DISPLAYON);
Wire.endTransmission();
}
```
接下来是一些常用的函数,比如设置显示位置、清屏、写入数据等:
```c
void ssd1309_set_position(unsigned char x, unsigned char y) {
Wire.beginTransmission(SSD1309_I2C_ADDRESS);
Wire.write(SSD1309_COLUMNADDR);
Wire.write(x);
Wire.write(SSD1309_WIDTH - 1);
Wire.write(SSD1309_PAGEADDR);
Wire.write(y);
Wire.write((SSD1309_HEIGHT / 8) - 1);
Wire.endTransmission();
}
void ssd1309_clear_screen() {
for (int i = 0; i < (SSD1309_WIDTH * SSD1309_HEIGHT / 8); i++) {
Wire.beginTransmission(SSD1309_I2C_ADDRESS);
Wire.write(0x40);
Wire.write(0x00);
Wire.endTransmission();
}
}
void ssd1309_write_data(unsigned char data) {
Wire.beginTransmission(SSD1309_I2C_ADDRESS);
Wire.write(0x40);
Wire.write(data);
Wire.endTransmission();
}
```
最后,使用上面的函数就可以在OLED屏幕上显示文字或图像了:
```c
ssd1309_init(); // 初始化
ssd1309_set_position(0, 0); // 设置位置
for (int i = 0; i < (SSD1309_WIDTH * SSD1309_HEIGHT / 8); i++) {
ssd1309_write_data(0xFF); // 写入数据
}
ssd1309_clear_screen(); // 清屏
```
以上是基于I2C协议的驱动代码示例,使用SPI协议的驱动方式类似,只需要修改一些通信方式的细节就可以了。
阅读全文