Home > Mobile >  Writing an long integer to an string as char* in Arduino function
Writing an long integer to an string as char* in Arduino function

Time:10-11

i am fighting with this problem for all night long, and nothing working for me... I have tried with alot of methods founded on the internet, but i'm still locked here.

All I want is to write an number in the middle of an char string to display it on an oled screen using an nodemcu v3 based on ESP8266. This is what I want to have on my screen: S7:3.55V
3.55 could be an number between 3.02 and 4.87.


Actual error is: invalid conversion from 'long int' to 'char*' [-fpermissive]

#include <Wire.h>
#include "OLED.h"
#include <sstream>
#include <iostream>
#include <string>
#include <cstring>
#include <iomanip>
#include <locale>
        
OLED display(2, 14); //OLED Declarare SDA, SCL
long randNumber;

void setup() {
  Serial.begin(9600);
  Serial.println("OLED test!");

  // Initialize display
  display.begin();
  //display.off();
  //display.on();
  display.clear();
  delay(3*1000);
}

void loop() {
  randNumber = random(3.02, 4.87);

  display.print("S7:", 5);
  display.print(randNumber, 5);
  display.print("V", 5);
  //display.print("Banc: ", 7);
  //display.print(randNumber1, 7);
  //display.print("V", 7);
  delay(3*200);
}

CodePudding user response:

sprintf is your friend here, write the number to a buffer first and then print that buffer. However you still need a different way to get to that number, random returns a long value, so to get your desired result you should adjust your parameters first:

randNumber = random(302, 487);

Don't worry about the decimals we'll get them back by appropriate formatting (in any case avoiding floating point entirely avoids at the same time quite a number of trouble mainly concerning rounding issues).

char buffer[16];
snprintf
(
    buffer, sizeof(buffer),
    "S7:%ld.%.2ldV", randNumber / 100, randNumber % 100
//      ^3^ ^55 ^    ^------ 3 -----^  ^----- 55 -----^
);

Now simply print out buffer...

Alternatives involve e.g. std::ostringstream, but these are not as convenient (and not as efficient) as good old C stdio API:

std::ostringstream buffer;
buffer << "S7:" << randNumber / 100 << '.'
       << std::setw(2) << std::setfill('0') << randNumber % 100 << 'V';
print(buffer.str().c_str());
  • Related