1.9 KiB
Arduino classes
How do I make a class?
First you need to start out with a header file. This file will contain the class definition. And which functions of the class are public and which are private.
#ifndef DISPLAYTEXT_H
#define DISPLAYTEXT_H
#include "Adafruit_GFX.h"
#include "Adafruit_ST7796S_kbv.h"
class DisplayText {
private:
Adafruit_ST7796S_kbv& tft;
int centerText(char* text);
int bottomText(char* text);
void printWordsFull(char* text);
public:
DisplayText(Adafruit_ST7796S_kbv& tftDisplay);
void writeText(char* text, int size, int posX, int posY, int screenTime, bool center, bool bottom);
};
#endif
#ifndef
DISPLAYTEXT_H is a preprocessor directive that checks if DISPLAYTEXT_H is defined. If it is not defined, the code between #ifndef and #endif will be included in the compilation. If it is defined, the code will be excluded from the compilation. This is to prevent the same code from being included multiple times in the same file.
To start out with a class you need a constructor. This is a function that is called when the class is created. This function is used to initialize the class.
DisplayText::DisplayText(Adafruit_ST7796S_kbv& tftDisplay) : tft(tftDisplay) {
tft.fillScreen(0x0000);
}
The library gets passed to tftdisplay. And the tft gets initialized with the tftdisplay.
How do I create a function in a class?
void DisplayText::centerText() {
//insert code here
}
This is a example of a function in a class. The function is called centerText and it is a private function. This means that it can only be called from within the class.
When creating a class you also need to reference it in the header file like this
#include "DisplayText.h"
class DisplayText {
private:
int centerText();
//other functions
public:
//other functions
};