[SOLVED] How to use an int value in getTextBounds to center that value

So I'm trying to center a text with an OLED module, the problem is it is an int value "now.day", I found an example on how to do it but the examples used a char array. I tried converting the "now.day" to char but it doesn't work. My question is how to do it properly with the getTextBounds?
Here's what I started with:

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SH110X.h>

#include <RTClib.h>
RTC_DS3231 rtc;

#define i2c_Address 0x3c
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SH1106G display = Adafruit_SH1106G(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

int x;
char *dateNow;

void setup() {
  Serial.begin(9600);
  display.begin(i2c_Address, true);
  rtc.begin();
}

void loop() {
  DateTime now = rtc.now();

  x = now.day();
  
  //dateNow = x; 
  itoa(x, dateNow, 10); //this uploads the sketch but the display on screen is garbled
  
  display.setTextSize(2);
  drawCentreString(dateNow, 0, 36);
  //Serial.print(dataD[0]);

  Serial.println(dateNow);
  display.display();
  //display.clearDisplay();
}

void drawCentreString(const char *buf, int x, int y)
{
    int16_t x1, y1;
    uint16_t width,height;;
    display.getTextBounds(buf, x, y, &x1, &y1, &width, &height);
    display.setCursor((SCREEN_WIDTH - width + x) / 2, y);
    display.print(buf);
}


I think you want something like:
display.setCursor(x - (width / 2), y);
That should center the string on the x you pass in. If you want to center the y axis as well, try:
display.setCursor(x - (width / 2), y - height/2);
or
display.setCursor(x - (width / 2), y + height/2);

I don't think the null pointer you initialized winds up pointing at the resulting null-terminated string created by itoa.

//char* dateNow;
char dateNow[3] = {}; //two digits plus null

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