0

I'm trying to write a function as part of my code, and the function basically has to write the name of a parameter, but I can't get it to print properly to the screen. Here is what I've got:

void dataprint(char parameterName, float dataNum, char unitName);
{
 Serial.print(",");
 Serial.print(parameterName);
 Serial.print(",");
 Serial.print(dataNum);
 Serial.print(",");
 Serial.print(unitName);
}

In the actual program part I have something like this:

char temp = "temperature";
float t = tempsensor.readTempC(); // just some number that comes from sensor
char unit = "C";
dataprint(temp,t,unit);

Right now in the serial monitor I get a question mark or something like that instead of the name I have saved in parameterName or unitName. I want this function to print the same way something like this would show up:

Serial.print(",");
Serial.print("temperature");
Serial.print(",");
Serial.print(c);
Serial.print(",");
Serial.print("C");

Thanks in advance for any help.

3
  • 1
    char unit = "C"; won't compile, and that's quite important to your question. Could you edit the question with the code you really have please?
    – Mark Smith
    Jun 21 '17 at 21:57
  • @MarkSmith Funny thing with that is: it'll compile. (@ Arduino IDE 1.8.1)
    – KIIV
    Jun 22 '17 at 7:23
  • @KIIV Just tested it, and so it does. That's mad. Confirmed not compile on the (older) version I was using!
    – Mark Smith
    Jun 22 '17 at 12:38
2

To make your code work, you must use character array pointers. A "char" holds only one character, while "char*" can point to a string.

char foo = 'a';
char *bar = "string with lots of stuff.";

So the full code to implement your example is:

void setup()
{
  Serial.begin(9600);
}

void dataprint(char *parameterName, float dataNum, char *unitName)
{
  Serial.print(parameterName);
  Serial.print(",");
  Serial.print(dataNum);
  Serial.print(",");
  Serial.println(unitName);
}

void loop() {
  char *temp = "temperature";
  float t = 123.4;
  char *unit = "C";
  dataprint(temp,t,unit);

  while(1)
  {
    //do nothing
  }
}

Which prints the following to the serial port:

temperature,123.40,C
1
  • 1
    It works, but it's bad C++: warning: deprecated conversion from string constant to ‘char*’. This means you should replace every char * with const char *. Jun 22 '17 at 7:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.