Display a numeric Variable with u8g2 in ST7920

I have a ST7920 and a matrix keypad (3x4), my goal is to display the pressed key on the LCD, but I can't make it work. I can read the key but I'm not able to displayit, furthermore I can't display any "variable".
u8g2.drawStr() doesn't work, I also tryed u8g2.print(). But if I use:

u8g2.firstPage();
     do {
      u8g2.setFont(u8g2_font_ncenB10_tr);
      u8g2.drawStr(0,24,"1234");
     } while(u8g2.nextPage());

works just fine.

BOARD: Arduino Mega 2560

CODE:


#include <U8g2lib.h>
#include <SPI.h>
#include <SD.h>
#include <Keypad.h>

U8G2_ST7920_128X64_1_SW_SPI u8g2(U8G2_R0, 13, 11, 10, /* reset=*/ U8X8_PIN_NONE);
 
const byte rowsCount = 4;
const byte columsCount = 3;
 
char keys[rowsCount][columsCount] = {
   { '1','2','3'},
   { '4','5','6'},
   { '7','8','9'},
   { '#','0','*'}
};
 
const byte rowPins[rowsCount] = {23, 25, 27, 29 };
const byte columnPins[columsCount] = {31, 33, 35};
 
Keypad keypad = Keypad(makeKeymap(keys), rowPins, columnPins, rowsCount, columsCount);
 
void setup() {
   Serial.begin(9600);
   u8g2.begin();
   u8g2.enableUTF8Print(); 
}

void loop() {
  // put your main code here, to run repeatedly:
   char key = keypad.getKey();  
   if (key) {
     u8g2.firstPage();
     do {
      u8g2.setFont(u8g2_font_ncenB10_tr);
      u8g2.drawStr(0,24,key);
     } while(u8g2.nextPage());
    delay(2000);
    u8g2.clearDisplay();
   } 
}

Did you try converting key to a string u8g2.drawStr(0,24,String(key)); so that drawStr, Draw STRING, receives a String?

Hello, thanks for the answer, yes I tryed that but I get an error :frowning:

Oi! a Secret Error Message or can you share the error message?

If you want to print different types of expression use u8g2.print() with any necessary u8g2.setCursor() first.

The u8g2.drawStr() only accepts char* arguments.
You can convert an integer to char[] e.g. with sprintf()
Or you can use C++ String contortions and then use c_str() to return a regular C char*

In your particular example you can just provide a char array as a buffer. Fill the first element with your key. And the second element with a NUL terminator. e.g.

   if (key) {
     u8g2.firstPage();
     do {
      u8g2.setFont(u8g2_font_ncenB10_tr);
      char buf[2];   //big enough to hold one letter C string with NUL terminator
      buf[0] = key;
      buf[1] = 0;    // the NUL terminator
      u8g2.drawStr(0, 24, buf);  // send the C string
     } while(u8g2.nextPage());

David.

Thanks for the replies, is not a secret error but I can't recall what it says and I'm not in my house to test it again :sweat:

I will try your solution David, thank you!

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