Hi All,
I've written a simple program to make the string "Hello" move up and down the screen of a 128x64 OLED display as seen here:
#include <Wire.h> //include the wire library
#include <Adafruit_GFX.h> //include the GFX library
#include <Adafruit_SSD1306.h> //include the SSD1306 library
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET 4
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT);
float y = 0;
float yspeed = 1;
float x = 0;
float xspeed = 1;
void setup() {
Serial.begin(9600);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); //start screen
display.setTextColor(SSD1306_WHITE); //set colour
}
void loop() {
display.clearDisplay(); //clear screen
display.setTextSize(1); //text size
display.setCursor(x,y); //cursor position
display.print("Hello"); //text to print
display.display(); //send to screen
y = y + yspeed;
//x = x + xspeed;
Serial.println(y);
if (y>=56 || y<=0){ //if y is less than 56 or more than 0
yspeed = yspeed * -1; // invert the value of yspeed
}
if (x>=96 || x<=0){ //if x is less than 96 or more than 0
xspeed = xspeed * -1; // invert the value of xspeed
}
}
As I'm learning Object Oriented Programming (OOP), I decided to rewrite the program in this format. My tabs are as follows:
//IMPLEMENTATION
#include "Oled.h"
OLEDDisplay::OLEDDisplay()
{
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
}
float y = 0;
float yspeed = 1;
float x = 0;
float xspeed = 1;
void OLEDDisplay::init()
{
Serial.begin(115200);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.setTextColor(WHITE);
display.clearDisplay();
display.display();
}
void OLEDDisplay::update()
{
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, y);
display.print("Hello");
display.display();
y = y + yspeed;
//x = x + xspeed;
Serial.println(y);
if (y>=56 || y<=0){ //if y is less than 56 or more than 0
yspeed = yspeed * -1; // invert the value of yspeed
}
// if (x>=96 || x<=0){ //if x is less than 96 or more than 0
// xspeed = xspeed * -1; // invert the value of xspeed
// }
}
The display is already an object.
What you do is putting an extra layer (object) around it.
If the compiler cannot optimize it adds an extra indirection (slower)
Have you quantified the performance difference (measurements)?
That is a serious difference.
First note that the code in init() is not identical to the code in setup()
Second note that the code in update() and in loop() differ.
What I have discovered is that the code "display.begin(SSD1306_SWITCHCAPVCC, 0x3C);" under "void OLEDDisplay::init()" was causing the slow down. By moving it under "void setup" of the main tab, the output to the serial monitor is considerably better. In fact, the output is now faster than the simple sketch and I now have a different problem:
The text "Hello" appears at a random y-position and does not update itself despite the serial monitor proving that the y-position is updating. Here are the new sketches: