Skip to content

Instantly share code, notes, and snippets.

@hector6872
Last active December 2, 2018 12:19
display Arduino sketch
#include <U8g2lib.h>
// constructor
U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 4, /* data=*/ 5);
// fake data
const String SYMBOL = "Bitcoin";
const String QUOTE = "USD";
const float PRICE = 20000.12345;
const float PERCENT_1h = -1.12345;
const float PERCENT_24h = -2.23456;
const float PERCENT_7d = 3.45678;
const float CAP = 1234567890.1234;
const String LAST_UPDATED = "2022-01-01T00:01:00.000Z";
const int SEPARATOR = 2;
const String PERCENTAGE = " "; // or "% "
int x = 0;
int y = 0;
void setup(void) {
u8g2.begin();
u8g2.setFontMode(0);
}
void loop(void) {
u8g2.firstPage(); // + info https://github.com/olikraus/u8glib/wiki/tpictureloop
do {
// symbol
u8g2.setFont(u8g2_font_fub11_tf);
x = 0;
y = 11; // from below, capital A size. +info https://github.com/olikraus/u8g2/wiki/fntgrpfreeuniversal
u8g2print(SYMBOL);
// price
u8g2.setFont(u8g2_font_fub14_tf);
x = 0;
y += 14 + SEPARATOR;
String priceFormatted = String(PRICE, 2);
u8g2print(priceFormatted);
x = getStringWidth(priceFormatted) + SEPARATOR; // measure before changing font size
// y = same baseline
u8g2.setFont(u8g2_font_fur11_tf);
u8g2print(QUOTE);
// percentages
String percent1hFormatted = String(PERCENT_1h, 1) + PERCENTAGE;
String percent24hFormatted = String(PERCENT_24h, 1) + PERCENTAGE;
String percent7dFormatted = String(PERCENT_7d, 1) + PERCENTAGE;
u8g2.setFont(u8g2_font_fub11_tf);
x = 0;
y += 11 + SEPARATOR;
u8g2print(percent1hFormatted);
x += getStringWidth(percent1hFormatted) + SEPARATOR;
u8g2print(percent24hFormatted);
x += getStringWidth(percent24hFormatted) + SEPARATOR;
u8g2print(percent7dFormatted);
// cap
u8g2.setFont(u8g2_font_profont15_tf);
x = 0;
y += 9 + SEPARATOR;
String capFormatted = String(CAP, 2);
u8g2print(capFormatted);
u8g2.setFont(u8g2_font_profont15_tf);
y += 9 + SEPARATOR;
u8g2print(convertToTime(LAST_UPDATED));
} while ( u8g2.nextPage() );
}
int getStringWidth(String string) {
char *charString = const_cast<char*>(string.c_str());
return u8g2.getStrWidth(charString);
}
void u8g2print(String string) {
u8g2.setCursor(x, y);
u8g2.print(string);
}
String convertToTime(String timestamp) {
return timestamp.substring(11, 16); // extract HH:mm
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment