C++ array of pointers to objects

I was driving multiple TFT LCDs on the same microcontroller. Each LCD had its own instance and I needed an easy method of iterate through all of them.

The platform I used is a ST Nucleo F411RE board, the programming enviroment is mbed and the TFT LCDs are 2.2 inch ILI9341 display.

By using a single screen, the code could look like this:


// https://ee-programming-notepad.blogspot.com/2016/10/c-array-of-pointers-to-objects.html
#include "mbed.h"
#include "ILI9340_Driver.h"
#define LCD_MOSI D11
#define LCD_MISO D12
#define LCD_SCK D13
#define LCD_CS D5
#define LCD_RST D3
#define LCD_DC D7
ILI9340_Display lcd(LCD_MOSI, LCD_MISO, LCD_SCK, LCD_CS, LCD_RST, LCD_DC); // MOSI, MISO, SCK, CS, RST, D/C
int main() {
lcd.DispInit();
lcd.SetRotation(0);
lcd.FillScreen(ILI9340_BLUE);
lcd.DrawString("Test", 0, 0, 2, ILI9340_WHITE); // draw a text with 8px font
}

On the other hand, by using multiple screens, the code could look like this:


// https://ee-programming-notepad.blogspot.com/2016/10/c-array-of-pointers-to-objects.html
#include "mbed.h"
#include "ILI9340_Driver.h"
#define LCD_MOSI D11
#define LCD_MISO D12
#define LCD_SCK D13
#define LCD_DC D7
#define LCD1_RST D3
#define LCD1_CS D5
#define LCD2_RST A1
#define LCD2_CS A0
#define LCD_NO_SCREENS 2
ILI9340_Display * tft_lcds[LCD_NO_SCREENS];
int main() {
char i = 0;
PinName cs_pin, rst_pin;
ILI9340_Display * tft_lcd; // array of pointers to objects
while (i < LCD_NO_SCREENS) // iterate the screens
{
switch (i)
{
case 0: // first screen
cs_pin = LCD1_CS;
rst_pin = LCD1_RST;
break;
case 1: // second screen
cs_pin = LCD2_CS;
rst_pin = LCD2_RST;
break;
}
// instantiate the LCD class
tft_lcd = new ILI9340_Display(LCD_MOSI, LCD_MISO, LCD_SCK, cs_pin, rst_pin, LCD_DC); // MOSI, MISO, SCK, CS, RST, D/C
tft_lcd->DispInit();
tft_lcd->SetRotation(0);
tft_lcd->FillScreen(ILI9340_BLUE);
// push the new instance to the array of pointers
tft_lcds[i] = tft_lcd;
i++;
}
// ... code ...
wait(2);
// later on, display some text on LCD
i = 0;
while (i < LCD_NO_SCREENS)
{
tft_lcds[i]->FillScreen(ILI9340_RED);
char buff[20];
sprintf(buff, "Loading %d...", i);
tft_lcds[i]->DrawString(buff, 0, 0, 2, ILI9340_WHITE); // draw a text with 8px font
i++;
}
}

The code is not elegant, but it gets the job done.
Note that the LCDs RST and CS pins need to be individually connected to the microcontroller.

Reference: www.java2s.com

No comments:

Post a Comment