PROGMEM从字符串数组中获取单个字符?

时间:2016-01-12 10:24:24

标签: c++ arduino atmega progmem

我正在尝试从字符串数组中获取单个字符以写入Arduino上的LCD显示器。只有我没有真正得到任何有效的数据。

LCD写代码:

void LCD::drawString(uint16_t x, uint16_t y, uint16_t color, uint16_t background, uint8_t str_nr)
{
    for(uint16_t i=0; getChar(str_nr, i) != '\0'; i++)
    {
        drawChar(x + i * FONT_WIDTH, y, color, background, getChar(str_nr, i) );
    }
}

StringPool.h:

#ifndef STRINGPOOL_H_
#define STRINGPOOL_H_

#include <avr/pgmspace.h>

#define STR_SCREEN_CAL 0
#define STR_HIGHSCORE 1
#define STR_SETTINGS 2
#define STR_BACK 3
#define STR_MENU_MAIN_TITLE 4
#define STR_MENU_MAIN_PLAY 5
#define STR_MENU_SCORE_TEXT 6
#define STR_MENU_SETTINGS_RESETSCORE 7
#define STR_MENU_SETTINGS_SCORERESET 8
#define STR_MENU_SETTINGS_CAL 9
#define STR_MENU_SETTINGS_BRIGHTNESS 10
#define STR_GAME_SCORE_NEW 11
#define STR_GAME_SCORE_NONE 12
#define STR_GAME_TOUCH_SCREEN 13
#define STR_GAME_TO_CONTINUE 14

uint8_t getChar(uint8_t str_nr, uint8_t offset);

#endif /* STRINGPOOL_H_ */

StringPool.cpp:

#include "StringPool.h"

const PROGMEM char screen_cal[] = "Screen Calibration";
const PROGMEM char highscore[] = "Highscore";
const PROGMEM char settings[] = "Settings";
const PROGMEM char back[] = "Back";
const PROGMEM char menu_main_title[] = "Floppy Bird";
const PROGMEM char menu_main_play[] = "Play";
const PROGMEM char menu_score_text[] = "The current highscore is";
const PROGMEM char menu_settings_resetscore[] = "Reset Highscore";
const PROGMEM char menu_settings_scorereset[] = "Highscore Reset!";
const PROGMEM char menu_settings_cal[] = "Calibrate Touch";
const PROGMEM char menu_settings_brightness[] = "Set LCD Brightness";
const PROGMEM char game_score_new[] = "New Highscore!";
const PROGMEM char game_score_none[] = "No Highscore";
const PROGMEM char game_touch_screen[] = "Touch the screen";
const PROGMEM char game_to_continue[] = "to continue";

const char * StringPool[] =
{
    screen_cal,
    highscore,
    settings,
    back,
    menu_main_title,
    menu_main_play,
    menu_score_text,
    menu_settings_resetscore,
    menu_settings_scorereset,
    menu_settings_cal,
    menu_settings_brightness,
    game_score_new,
    game_score_none,
    game_touch_screen,
};

uint8_t getChar(uint8_t str_nr, uint8_t offset)
{
    char * ptr = (char *)pgm_read_word( &StringPool[str_nr] );
    return pgm_read_byte(ptr + offset);
    // return pgm_read_byte( &(StringPool[str_nr]) + offset); // doesn't work either
}

函数getChar似乎没有返回正确的数据。

我如何从progmem中的字符串数组中读取单个字符?

1 个答案:

答案 0 :(得分:1)

尝试

char * ptr = (char *)pgm_read_word( StringPool[str_nr] );

相反,省略&amp;,因为这会产生指向字符串的指针的地址。指针的地址在RAM中。 StringPool [str_nr]已经是你想要的闪存中的地址。