Hello Everyone,
I have the following program which is working fine. It reads from the EEPROM and then shows the corresponding characters to the NOKIA 1100 LCD. I am confused in understanding the & and * signs in the code that what they are doing actually, I want to know step by step working of these lines also is it possible to further reduce it.
the function "lcd_String()" takes and ASCII string as input e.g: "lcd_String('Hello, How are you?')"
Regards:
The code is:
for (int i=6;i<lnt;i++)
{
char* c=(char*)(EEPROM.read(i));
char* ch=(char*)&(c);
lcd_string(ch);
}
That isn't supposed to work. It does, but that's really just luck. It's not defined by the compiler.
The & operator finds the address of a variable. The * operator uses the value found at the specified address.
char * c defines a new variable c which is a pointer to a char. But it doesn't point to any specific address. It may point to address zero, which on most computers will cause a segfault if you attempt to access that address.
(char*)(EEPROM.read(i)) executes the read() function for the EEprom address given by i. But then it attempts to cast that into a pointer. I would have said that this would give you the address of the ASCII code for "H" but since it's working, it's not doing that. It may be giving you the address of the temporary storage for the function return value.
char* ch=(char*)&(c); this appears somewhat normal but it isn't. It takes the address of (c) - which is probably the address of c - then casts it to a char type pointer and assigns that to the new char pointer ch. But c is already a pointer and you shouldn't point to a pointer as if it was of type char. C code can use (void *) to make a pointer to a pointer but that's not necessary in C++.
All of this acrobatics is because lcd_string() expects to be passed a pointer to a string, which has a null character on the end of the string. You are just lucky that whatever is after c in memory happens to be zero.
Two solutions are possible:
Allocate an area of memory large enough to fit the longest string you want to print. (Keep track of this size with a #define constant.) Then use your for() loop to copy the characters from EEprom into this area and append a null onto the end. Then send it to lcd_string().
Find a different LCD function that will allow you to print a single character and just read straight out of EEprom into the LCD.
#define EEpromMyStringStartAddress 6
for (int i=EEpromMyStringStartAddress;i<lnt;i++)
{
lcd_write(EEPROM.read(i));
}
And please think of a more descriptive name for lnt.