Search code examples
clcditoa

Issue with itoa() and char array in regards to C (interfacing an LCD)


Doing my best to be brief; I am trying to program an LCD to print out an integer variable (of more than 1 digit). I'm trying to do this using the itoa function as the LCD takes ASCII characters. The below code compiles and prints "Set Temp: " when I want it to, the problem is that it doesn't print out the chars (digits) stored in the numberString array like I want it to. The writeString function is working fine but I cant figure out why it's just not printing the value of int setTemp after "Set Temp: ". All that's outputted is: "Set Temp: " with the cursor just hanging.

Probably worth mentioning that the cursor is hanging ON the position where the value should be printed on the LCD, indicating that it isn't just printing an empty value, it just isn't printing anything at all or waiting for something.

Apologies for any incorrect formatting of question, I'm new.

void writeChar(unsigned char ch)
{
  lcd = ch;
  RS = 1;
  RW =0;
  E = 1;
  lcdDelay();
  E=0;
}

void writeString(char *stringToLcd)
{
  while(*stringToLcd > 0)
  {
    writeChar(*stringToLcd++);
  }
}



int changeTriggTemp(void)
{
  char numberString[4]; //buffer, -99 -> 99
  int setTemp = 50;

  clearDisplay();
  writeString("Set Temp: ");

  itoa(setTemp,numberString,10);
  lcdDelay();

  writeString(numberString);

  while(1); //placeholder before I return the int I want

}

Solution

  • If you don't define a function prototype, the compiler can make incorrect assumptions about it, and code its use wrongly. Having drawn your attention to that I asked what the definition is, because the usual definition (at least in MSVC) is

    char *itoa(int value, char *str, int radix);
    

    This agreed with your own usage of the function,

    itoa(setTemp, numberString, 10);
    

    however on closer inspection of your library header file, you stated that it defines

    itoa(char * buf, int val, int base);
    

    In other words, the first two arguments are switched. Since itoa() is not a standard function, this is allowed, but you have to call it accordingly:

    itoa(numberString, setTemp, 10);
    

    (Thanks to @Eric whose suggestions revealed that it could well be itoa at fault).