PRJ - Place Const In Program Memory#

2024-05-29

/*
# 使用 PROGRAM 减少 SRAM 占用

## Question 

SRAM 非常有限, UNO 只有2KB。 现在有 1K~2K 大小的数据需要保存,然后写入 EEPROM。如何处理?

  
## Solution

使用 PROGMEM 限定

注意: const 只能限定变量不能被修改,并不能将它放到程序空间。


## Discussion



## Reference

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.

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


注: 当 SRAM 占用量过大时,程序可能会出现怪异的不正确现象。

*/


// 修改 ptext[1000] 数组的大小,如 1000 或 2000, 编译后可以看到 program storage space 会变化,不影响(占用) dynamic memory。
// 删除限定词 PROGMEM 后,  Global variables 就会占用 dynamic memory (SRAM)

const char ptext[1000] PROGMEM = {"Hello world Hello world Hello world Hello world ..."};

void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);
  delay(1000);
}

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


  for (int i = 0; i<strlen(ptext); i++) {
    Serial.print(ptext[i]);
  }
  // Serial.println("again");
  Serial.print('\n');
  delay(2000);
}