cpp - how to return a string vlue from a library

SBSP

Senior Member
Joined
Sep 7, 2007
Messages
667
Reaction score
16
I have an arduino project and need to create a library. I'm fine calling in a void in a constructor that does not return any value.
But I just cannot figure out how to return a string.

Below is just the template from a tutorial, please ignore the name of the header and source code file.

Morse.h.
Code:
/*
  Morse.h - Library for flashing Morse code.
  Created by David A. Mellis, November 2, 2007.
  Released into the public domain.
*/
#ifndef Morse_h
#define Morse_h
#include "Arduino.h"
class Eeprm
{
  public:
	Eeprm(int Nothing);
	void writedata(int addr,String datatowrite );
	void readdata(String addr);
  private:
};


#endif

Morse.cpp
/*
Morse.cpp - Library for flashing Morse code.
Created by David A. Mellis, November 2, 2007.
Released into the public domain.
*/
#include <WString.h> // include the String library
#include <EEPROM.h>
#include "Arduino.h"
#include "Morse.h"

Eeprm::Eeprm(int Nothing ){}
void Eeprm::readdata(int addr)
{
return "aaaa";
}
I left out void writedata(int addr,String datatowrite ); from the source code because its working fine.

in the end I want to be able to do this.
String Myreturneddata;

Myreturneddata=Eeprm.readdata(1);

Eeprm.readdata(1) passws the integer [1] to the void which then reads from address [1] and then returns the value which was read from address 1 in the memory of the arduino.

Please note: have basic experience with c++ i mostly make use standard if this then, some for loops.
 
Last edited:
Make readdata return "String" instead of "void" (in the declaration and implementation), and "return String("aaaaa")" to get a String object back.
 
I tried that before and it didnt work , the compiler gave an error, let me try again and report back
 
Yeah you need to return string. Also, the input parameter for readdata is string in the header, but an integer in the cpp
 
Void does what it says on the tin. Big black hole, nothing goes in or out...
 
Void does what it says on the tin. Big black hole, nothing goes in or out...
Using any return type you can accept inputs, it can perform actions, but it won't return anything using the void (but you can set variable values and call other methods). In simple terms using a void you are basically saying: "hey, here is some data (could be a string) or anything for that matter, do this, and then once done, don't return anything".
 
Last edited:
Top
Sign up to the MyBroadband newsletter
X