-
-
Save tibordp/a9fe405bc8ffa2cb325502041faed60e to your computer and use it in GitHub Desktop.
Chuck Norris jokes sketch for ESP32 and 128x64 OLED display
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <U8g2lib.h> | |
#include <Wire.h> | |
#include <WiFi.h> | |
#include <HTTPClient.h> | |
#include <ArduinoJson.h> | |
// ESP32 DevKitC has hardware I2C pins on 22 and 21 | |
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, U8X8_PIN_NONE, 22, 21); | |
StaticJsonDocument<8192> jsonDoc; | |
const char* lastText = ""; | |
long lastLineChange = 0; | |
int startOffset = 64; | |
void prepareDisplay() { | |
u8g2.setFont(u8g2_font_6x10_tf); | |
u8g2.setFontRefHeightExtendedText(); | |
u8g2.setDrawColor(1); | |
u8g2.setFontPosTop(); | |
u8g2.setFontDirection(0); | |
} | |
bool printWithOffset(const char* text, int offset) | |
{ | |
bool printedSomething = false; | |
int textLength = strlen(text); | |
for (int i = 0; i < (textLength + 20) / 21; ++i) { | |
if (10*i + offset < -20 || 10*i + offset > 74) { | |
// We are far outside the visible region, no need to draw | |
continue; | |
} | |
char buf[22]; | |
strncpy(buf, &text[i*21], 21); | |
u8g2.drawUTF8(2, 10*i + offset, buf); | |
printedSomething = true; | |
} | |
return printedSomething; | |
} | |
void setup() { | |
WiFi.begin("5G COVID-19 Transmitter", "hunter2"); | |
while (WiFi.status() != WL_CONNECTED) { | |
yield(); | |
} | |
u8g2.begin(); | |
prepareDisplay(); | |
} | |
void loop() { | |
u8g2.clearBuffer(); | |
if (!printWithOffset(lastText, startOffset)) { | |
// Since fetching is synchronous, we do it when the screen is blank | |
HTTPClient http; | |
http.begin("https://api.chucknorris.io/jokes/random"); | |
if (http.GET() == 200) { | |
if (!deserializeJson(jsonDoc, http.getString())) { | |
lastText = jsonDoc["value"]; | |
} | |
} | |
// If we fail to fetch, we just keep the old text around | |
http.end(); | |
startOffset = 64; | |
} | |
u8g2.sendBuffer(); | |
long currentTime = millis(); | |
if (currentTime - lastLineChange > 50) { | |
startOffset -= 1; | |
lastLineChange = currentTime; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment