Arduino: How to scroll long text on OLED screen

 While exploring a new and tiny SSD 1306 OLED screen as a useful user interface I hit on the need to scroll some longish text across the screen. This did not seem to be a feature of the Adafruit library I was using to run the device. So I am introducing this working demo of my solution to the problem.

The solution is to position the start point of the text in steps towards the left and beyond the left hand edge of the screen. The screen "clips" the text and displays all it can across the width of the screen.



The demo includes some fixed text at the top of the screen and scrolls the long text below.

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 32 // OLED display height, in pixels #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) #define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32 Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); const char longText[] = "This is some text to scroll over OLED screen"; int displayLen, displayLimit, displayX; unsigned long lastMillis; const int timeStep = 100; void setup() { Serial.begin(115200); while (!Serial) {} if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) { Serial.println("SSD1306 allocation failed"); } displayLimit = strlen(longText) * -12 + SCREEN_WIDTH / 2; // (6 pixels * text size 2) less half a screen displayX = SCREEN_WIDTH; display.setTextWrap(false); display.setTextSize(2); display.setTextColor(SSD1306_WHITE); // Draw white text lastMillis = millis(); } void loop() { unsigned long curMillis = millis(); if(curMillis - lastMillis > timeStep){ if (displayX <= displayLimit){displayX = SCREEN_WIDTH;} displayX -=6; // move half a character left Serial.println(displayX); updateDisplay(); lastMillis = millis(); } } void updateDisplay(){ display.clearDisplay(); display.setCursor(10, 0); // fixed text at top of screen display.print("Fixed text"); display.setCursor(displayX, 18); // scrolling text below display.print(longText); display.display(); }
The displayLimit value is negative and calculated from the text length multiplied by the number of pixels assigned to a character (size 2) less half the screen width.




Comments

Popular posts from this blog

Unicode output from an Arduino.

Arduino Regular Expressions