PRJ - Progmem Example 1#

2024-05-29

/*
# PROGMEM

## Description

The PROGMEM keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "put this information into flash memory", instead of into SRAM, where it would normally go.

## Question

为什么字符串长点之后,程序会跑飞? 

例如,signMessage[] 中的字符超过三行后,它会造成本程序不停地打印(程序的逻辑是只打印1遍)。

答案: 循环的次数 k 如果是 byte, (byte k = 0; k < strlen_P(signMessage); k++)

(int k = 0; k < strlen_P(signMessage); k++)

## See also

eeprom_long_text.ino

## Reference

https://www.arduino.cc/reference/en/language/variables/utilities/progmem/
*/

// save some unsigned ints
const PROGMEM uint16_t charSet[] = { 65000, 32796, 16843, 10, 11234};

// save some chars
const char signMessage[] PROGMEM = {""
"\nI AM PREDATOR,  UNSEEN COMBATANT. CREATED BY THE UNITED STATES DEPART"
"\nI AM PREDATOR,  UNSEEN COMBATANT. CREATED BY THE UNITED STATES DEPART"
"\nI AM PREDATOR,  UNSEEN COMBATANT. CREATED BY THE UNITED STATES DEPART"
"\nI AM PREDATOR,  UNSEEN COMBATANT. CREATED BY THE UNITED STATES DEPART"
"\nI AM PREDATOR,  UNSEEN COMBATANT. CREATED BY THE UNITED STATES DEPART"};

unsigned int displayInt;
char myChar;


void setup() {
  Serial.begin(9600);
  while (!Serial);  // wait for serial port to connect. Needed for native USB

  // put your setup code here, to run once:
  // read back a 2-byte int
  for (byte k = 0; k < 5; k++) {
    displayInt = pgm_read_word_near(charSet + k);
    Serial.println(displayInt);
  }
  Serial.println();

  // read back a char
  for (int k = 0; k < strlen_P(signMessage); k++) {
    myChar = pgm_read_byte_near(signMessage + k);
    Serial.print(myChar);
  }

  Serial.println();
}

void loop() {
  // put your main code here, to run repeatedly:
}