Jul 28, 2013

A function for positioning text on an OLED display

Building on the previous post which explains how to position text on the Adafruit Display, here is a function to save some math and some code. (applicable to 32 and 64 pixel heights)

Keep in mind that 64 pixels high is equivalent to 8 lines of the smallest text 6x8 pixels (size=1) or 4 lines of text 12x16 pixels (size=2). If you're going to use both (and you probably will), you'll have to adjust your positions accordingly. Note that you can actually put the text at any x-y location; the lines are just a convenient way to organize it.


// Create a function to print text at an x,y location
// uses monochrome OLED and the SSD1306 driver (SPI) from Adafruit
// David Smith, 2013
// This code is in the public domain.


#include <Wire.h>
#include <Adafruit_GFX.h>      // graphics library
#include <Adafruit_SSD1306.h>  // device driver for 128x64 SPI

// assign SPI control functions to pins (with silkscreen labels shown in order)
#define OLED_MOSI   9  // Data
#define OLED_CLK   10  // Clk
#define OLED_DC    11  // DC
#define OLED_RESET  8  // Rst
#define OLED_CS    12  // CS
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

void setup()   {
    Serial.begin(57600);
    display.begin(SSD1306_SWITCHCAPVCC);  // enable internal HV supply for display
    display.clearDisplay();   // clears the OLED screen
    display.display();        // refresh the screen

    // you can use string arrays or a literal
    char str1[22] = "small text: line 1";
    char str2[22] = "medium txt";
    printOLED(str1, 1,1,1,1); refresh included in fctn call
   
printOLED(str2, 1,2,2,1);
   
printOLED("# at 3,4", 3,4,2,1); // bottom line (4), size 2
}


void
printOLED(char sbuf[], byte xpos, byte ypos, byte fsize, byte clr) { 

// (chars and lines are defined to start at 1,1 for upper-left)    const byte h = 8;
    const byte w = 6;
    if (xpos < 1) xpos = 1;
    if (ypos < 1) ypos = 1;
    display.setTextColor(clr);  // 1=WHITE, 0=BLACK
    display.setTextSize(fsize); // font size
    display.setCursor((xpos-1)*w*fsize,(ypos-1)*h*fsize);
    display.print(sbuf);   // print string at xy location
    display.display();     // refresh the screen
}

void loop() {
}