自从在Arduino IDE 下跑通了STM32的闪灯程序之后 (//www.greatytc.com/p/8a8d4cba910f),点亮OLED屏幕应该也是小CASE,遗憾的是还是折腾了好几个小时,最终才搞定。
用的STM32F401CxUx芯片,OLED是SSD1306芯片的128x32点阵屏幕
oled_ssd1306.JPG
STM32F401.JPG
首先在Arduino IDE下载Wire库和SSD1306Ascii库。
SSD1306ASCII_LIB.jpg
代码如下:
// Simple I2C test for ebay 128x32 oled.
#include <Wire.h>
#include "SSD1306Ascii.h"
#include "SSD1306AsciiWire.h"
// 0X3C+SA0 - 0x3C or 0x3D
#define I2C_ADDRESS 0x3C
// Define proper RST_PIN if required.
#define RST_PIN -1
SSD1306AsciiWire oled;
//------------------------------------------------------------------------------
void setup() {
Wire.setSDA(PB7);
Wire.setSCL(PB6);
Wire.begin();
Wire.setClock(800000L); //fast clock
#if RST_PIN >= 0
oled.begin(&Adafruit128x32, I2C_ADDRESS, RST_PIN);
#else // RST_PIN >= 0
oled.begin(&Adafruit128x32, I2C_ADDRESS);
#endif // RST_PIN >= 0
oled.setFont(Adafruit5x7);
oled.clear(); //clear display
oled.set2X(); //double-line font size - better to read it
oled.println("Welcome!"); //print a welcome message
oled.println("SSD306"); //print a welcome message
delay(3000);
}
//------------------------------------------------------------------------------
void loop() {}
程序中关键的一句是:
Wire.setSDA(PB7);
Wire.setSCL(PB6);
设置SDA和SCL引脚。看到STM32F401的手册上有这样一段:
I2C_mapping.jpg
把引脚接到I2C2 (PB10/PB3) I2C3(PA8/PB4)也是可以的。
例如:
Wire.setSDA(PB3);
Wire.setSCL(PB10);
或:
Wire.setSDA(PB4);
Wire.setSCL(PA8);
编译,上传。成功点亮OLED。
SSD1306_DEMO.JPG