Helper functions

Helper functions, also known as utility functions or support functions, are a fundamental programming concept. They are small, reusable subroutines or methods that perform specific tasks within a larger program. Helper functions are designed to simplify code, improve readability and promote code reusability. They are a crucial part of writing clean, maintainable and efficient code.

Center Text

This is simple easy to use function for Adafruit GFX library. This is especially useful with relatively high resolution displays such as OLED and TFT screens.

void centerText(String text, int yOffset) {
  int16_t x, y, textWidth, textHeight;

  // Calculate text bounds
  display.getTextBounds(text, 0, 0, &x, &y, &textWidth, &textHeight);

  int centerX = (SCREEN_WIDTH - textWidth) / 2;
  int centerY = (SCREEN_HEIGHT - textHeight) / 2 + yOffset;

  display.setCursor(centerX, centerY);
  display.println(text);
}

    Examples how to use with Adafruit GFX library:
    Instead of: 
    display.print("hello, world!");
    use: 
    centerText("hello, world!", yOffset);

    For vertically and horizontally centered texts use 0 for yOffset:
    centerText("hello, world!", 0);
    Negative value for yOffset moves text up from the center line:
    centerText("hello, world!", - 25);
    Positive value for yOffset moves text down from the center line:
    centerText("hello, world!", + 25);

    You can also add xOffset for similar horizontal controls.


← Back