转载请注明出处:小锋学长生活大爆炸[xfxuezhang.cn]
先安装库
1. 打开 Arduino IDE,然后转到 Sketch > Include Library > Manage Libraries。
2. 在搜索框中输入“SSD1306”,然后从 Adafruit 安装 SSD1306 库。
3. 选择“install all”。如果没有跳出弹窗,则从 Adafruit 安装 SSD1306 库后,在搜索框中键入“GFX”并安装该库。
4. 安装库后,重新启动 Arduino IDE。(实测非必须)
再编写代码
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels// Define I2C Pins
#define I2C_SDA 14
#define I2C_SCL 15// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);void setup() {// Initialize with the I2C addr 0x3C (for the 128x32)Wire.begin(I2C_SDA, I2C_SCL);if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C, false, false)) { Serial.println(F("SSD1306 allocation failed"));for(;;); // Don't proceed, loop forever}// Clear the buffer.display.clearDisplay();display.setTextSize(1); // Normal 1:1 pixel scaledisplay.setTextColor(SSD1306_WHITE); // Draw white textdisplay.setCursor(0,0); // Start at top-left cornerdisplay.println(F("Hello, World!"));display.display();
}
连线并烧录
要将代码上传到 Lolin32 OLED 板,请将其插入计算机。在 Arduino IDE 中,转到“工具”>端口,然后选择它连接到的 COM 端口。完成连线。
然后,转到“工具>板”并选择“WEMOS LOLIN32”。
然后就可以看到效果:
例子:连接指定WiFi并显示IP地址
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>#define CAMERA_MODEL_AI_THINKER
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels// WiFi credentials
const char* ssid = "xxxx";
const char* password = "xxxx";// Define I2C Pins for ESP32-CAM
#define I2C_SDA 14
#define I2C_SCL 15// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);void setup() {Serial.begin(115200);// Initialize I2CWire.begin(I2C_SDA, I2C_SCL);// Initialize OLEDif(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Use the correct I2C address here (commonly 0x3C or 0x3D for 128x32 displays)Serial.println(F("SSD1306 allocation failed"));for(;;); // Don't proceed, loop forever}display.clearDisplay();display.setTextSize(1);display.setTextColor(SSD1306_WHITE);display.setCursor(0,0);// Connect to WiFiWiFi.begin(ssid, password);Serial.print("Connecting to WiFi...");display.println("Connecting to WiFi...");display.display();while (WiFi.status() != WL_CONNECTED) {delay(500);Serial.print(".");}Serial.println("\nWiFi connected.");Serial.print("IP address: ");Serial.println(WiFi.localIP());// Display IP address on OLEDdisplay.clearDisplay();display.setCursor(0,0);display.println("WiFi connected");display.print("IP: ");display.println(WiFi.localIP());display.display();
}void loop() {// Your loop code here. In this example, the loop does not contain additional code.
}