[英]Using Arduino F() Macro with string arrays
我正在開發一個Arduino項目,可以在LCD屏幕上打印隨機引用。 大約有一百種不同的引號,但其中包含超過10種引號會使SRAM過載。
我已經調查了它,似乎我需要使用PROGMEM
或F()
將字符串存儲在閃存而不是SRAM中,但我無法弄清楚要存儲的語法,然后檢索它們。 當前程序看起來像這樣(偽代碼刪除不相關的部分):
String quotes[] = {"quote 1", "quote2", "quote3", ... "quoteN"};
String currentQuote;
void setup() {
currentQuote = quotes[0];
}
void loop() {
if (condition)
currentQuote = quotes[random(N)];
}
如何將我的字符串數組存儲在閃存中,然后在需要時檢索單個元素?
直接來自http://arduino.cc/en/Reference/PROGMEM
It is important to use the datatypes outlined in pgmspace.h.
Some cryptic bugs are generated by using ordinary datatypes for program memory calls.
Below is a list of variable types to use.
Floating point numbers in program memory do not appear to be supported.
prog_char - a signed char (1 byte) -127 to 128
prog_uchar - an unsigned char (1 byte) 0 to 255
prog_int16_t - a signed int (2 bytes) -32,767 to 32,768
prog_uint16_t - an unsigned int (2 bytes) 0 to 65,535
prog_int32_t - a signed long (4 bytes) -2,147,483,648 to * 2,147,483,647.
prog_uint32_t - an unsigned long (4 bytes) 0 to 4,294,967,295
所以你不能使用String類型。 我建議使用引號[]的另一個定義,例如:
char a[][]={
"quote1",
"quote2",
"...",
"quoten",
};
順便說一句,同一頁http://arduino.cc/en/Reference/PROGMEM有一個你需要的例子:
/*
PROGMEM string demo
How to store a table of strings in program memory (flash),
and retrieve them.
Information summarized from:
http://www.nongnu.org/avr-libc/user-manual/pgmspace.html
Setting up a table (array) of strings in program memory is slightly complicated, but
here is a good template to follow.
Setting up the strings is a two-step process. First define the strings.
*/
#include <avr/pgmspace.h>
prog_char string_0[] PROGMEM = "String 0"; // "String 0" etc are strings to store - change to suit.
prog_char string_1[] PROGMEM = "String 1";
prog_char string_2[] PROGMEM = "String 2";
prog_char string_3[] PROGMEM = "String 3";
prog_char string_4[] PROGMEM = "String 4";
prog_char string_5[] PROGMEM = "String 5";
// Then set up a table to refer to your strings.
PROGMEM const char *string_table[] = // change "string_table" name to suit
{
string_0,
string_1,
string_2,
string_3,
string_4,
string_5 };
char buffer[30]; // make sure this is large enough for the largest string it must hold
void setup()
{
Serial.begin(9600);
}
void loop()
{
/* Using the string table in program memory requires the use of special functions to retrieve the data.
The strcpy_P function copies a string from program space to a string in RAM ("buffer").
Make sure your receiving string in RAM is large enough to hold whatever
you are retrieving from program space. */
for (int i = 0; i < 6; i++)
{
strcpy_P(buffer, (char*)pgm_read_word(&(string_table[i]))); // Necessary casts and dereferencing, just copy.
Serial.println( buffer );
delay( 500 );
}
}
我在代碼中看到String類中支持F()。 但我不知道如何使用它。
我建議查看http://arduino.cc/en/Reference/PROGMEM,它解釋了PROGMEM的使用相當好,並且與您的應用程序相關。 我認為PROGMEM更適用於char字符串,而不是字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.