Wrapping functionality in class

Hi everyone!

Can someone tell me why my code malfunctions when I call mScreen->clearDisplay() from my class? Everything compiles and seems to work fine until I add any call working with mScreen. I have separated this into an .ino, .cpp, and .h, but it throws the same error with just the .h file, so i'm putting it all there for brevity

Here is my code:


#include "Adafruit_SSD1306.h"
#include "Arduino.h"
#include "Wire.h"
#include "screen.h"

#define OLED_RESET     1
#define SCREEN_HEIGHT  64
#define SCREEN_WIDTH   128

Adafruit_SSD1306 ssd1306 = Adafruit_SSD1306(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
Screen *screen = new Screen(&ssd1306);

void setup() {

void loop() {


#ifndef SCREEN_H_
#define SCREEN_H_

#include "arduino.h"
#include "Adafruit_SSD1306.h"

#define OLED_RESET     1
#define SCREEN_HEIGHT  64
#define SCREEN_WIDTH   128

class Screen
    Screen(Adafruit_SSD1306* pScreen) : mScreen {pScreen} { };
    void init() {
       if(!mScreen->begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
        for(;;); // Don't proceed, loop forever
      mScreen->clearDisplay(); // this code or any code accessing mScreen blows up
    void draw();
    Adafruit_SSD1306* mScreen;

#endif // SCREEN_H_

edit: compiles fine.

What are the effects of this malfunction ?

You haven't called begin.

Hi @UKHeliBob , thanks for your response.

My computer says "USB device not recognized" on the NANO 33 IoT, the port is greyed out in the arduino IDE, and I have to reset the board (double tapping reset) to bring it back.

If I comment out screen->init(), it compiles fine and will write things out to the console if I add println statements.

I knew I had that at one point and removed it for brevity - added it back, thanks @anon73444976

edit: same result

Post code.

I did @anon73444976, what did I do wrong?

I can't see where you call begin for the display.

I had updated the code in a recent update, It looks like it's there to me now.

It appears to be working now! It probably was your code change, and I didn't reset the board properly. I'm sorry to ask such a simple thing and forget to retrace the basic example steps for this board. You guys responded so freaking fast, thank you so much.

...and it makes nonsense of earlier comments.

In the future, should I just change the code and post it in a new comment?


This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.