Go Down

Topic: progmem function (Read 405 times) previous topic - next topic

LittleDice

I am working on creating a function that reads strings from progmem and serial prints them.  I am not sure what I am doing wrong but my function is spitting out every string in progmem all at once without printing the variable that follows.

Code: [Select]

#include <avr/pgmspace.h>

#define line 1
#define no_line 0

//speak function
prog_char string_0[] PROGMEM = "Finished Initializing Ready for commands";   // "String 0" etc are strings to store - change to suit.
prog_char string_1[] PROGMEM = "Temp(C):";
prog_char string_2[] PROGMEM = "Pressure(Pa):";
prog_char string_3[] PROGMEM = "Humidity ";
prog_char string_4[] PROGMEM = "Compass Heading = ";
prog_char string_5[] PROGMEM = " degrees";

PROGMEM const char *string_table[] =    // change "string_table" name to suit
{   
  string_0, string_1, string_2, string_3, string_4, string_5
};

void setup()
{
  Serial.begin(9600);
  //speak(0,1,line);
}
void loop()
{
  speak(1,1,no_line);
  Serial.println("21");
  speak(2,1,no_line);
  Serial.println("40000");
  speak(3,1,no_line);
  Serial.println("50");
  delay(3000);
}

void speak(int string_num, int num_strings, int ln)
{
  char write_buffer[44];
 
  if (ln = 0)
  {
    for (string_num; string_num <= string_num + (num_strings - 1) ; string_num++)
    {
      strcpy_P(write_buffer, (char*)pgm_read_word(&(string_table[string_num]))); // Necessary casts and dereferencing, just copy.
      Serial.print( write_buffer );
    }
  }
  if (ln = 1)
  {
    for (string_num; string_num <= string_num + (num_strings - 1) ; string_num++)
    {
      strcpy_P(write_buffer, (char*)pgm_read_word(&(string_table[string_num]))); // Necessary casts and dereferencing, just copy.
      Serial.println( write_buffer );
    }
  }
}

davekw7x

#1
Jul 01, 2011, 08:38 pm Last Edit: Jul 01, 2011, 10:33 pm by davekw7x Reason: 1

...is spitting out every string in progmem all at once...

If you want it to print one line, why are you calling a function that tells it to print not only a given line but all of the lines after that one?  (See Footnote.)


Maybe you can try:
Code: [Select]

void loop()
{
   printPgmLine(1, no_line);
   Serial.println("21");
   printPgmLine(2, no_line);
   Serial.println("40000");
   printPgmLine(3, no_line);
   Serial.println("50");
   delay(3000);
}

void printPgmLine(int string_num, int ln)
{
   char write_buffer[44];
   strcpy_P(write_buffer, (char *)pgm_read_word(string_table + string_num));
   Serial.print(write_buffer);
   if (ln) {
       Serial.println();
   }
}


Or some such thing.


Regards,

Dave

Footnote:
The "speak" function that you showed us has undefined behavior since the loops can try to access memory beyond the end of the array of strings.  

Go Up