在PROGMEM(Arduino)中制作链接列表

Making a linked list in PROGMEM (Arduino)

本文关键字:链接 列表 PROGMEM Arduino      更新时间:2023-10-16

我正在处理一个问题,我认为这个问题基本上可以通过(乘法)链表很好地解决。然而,我的平台是一个Arduino,SRAM非常有限,所以我想把它全部保存在PROGMEM中(使用avr/pgmspace.h库)。

引用有指针的结构的字段时遇到问题。或者,换句话说,我在关注我的链接列表时遇到了问题。

这里有一些代码(我试着把它缩短):

#include <avr/pgmspace.h>
typedef struct list_item
{ 
   const prog_char * header;
   const struct list_item *next_item;
}; 
// declarations 
extern const list_item PROGMEM first_item; 
extern const list_item PROGMEM second_item; 
extern const list_item PROGMEM third_item; 
// name
const prog_char first_header[] PROGMEM = "Foo";
const prog_char second_header[] PROGMEM = "Bar";
const prog_char third_header[] PROGMEM = "Baz";
// instantiation & initialization 
const list_item first_item = { &first_header[0], &second_item }; 
const list_item second_item = { &second_header[0], &third_item }; 
const list_item third_item = { &second_header[0], &first_item }; 
// pointers to our items, just for testing
list_item const * const pointer_to_first_item = &first_item;
list_item const * const pointer_to_second_item = &second_item;
list_item const * const pointer_to_third_item = &third_item;
// prints the address of the pointer passed to it
void print_pointer_address( char * description, const void * pointer)
{
    Serial.print(description);
    Serial.println((unsigned int) pointer,HEX);
}
// a test
void setup()
{
    Serial.begin(57600);
    Serial.println("n--addresses of everything--");
    print_pointer_address("pointer to first_item = ", pointer_to_first_item);
    print_pointer_address("pointer to second_item = ", pointer_to_second_item);
    print_pointer_address("pointer to third_item = ", pointer_to_third_item);
    Serial.println("n--go through list via pointers--");
    list_item const * the_next_item;
    the_next_item = pointer_to_first_item;
    print_pointer_address("item 1 = ", the_next_item);
    the_next_item = the_next_item->next_item;
    print_pointer_address("item 2 = ", the_next_item);
    the_next_item = the_next_item->next_item;
    print_pointer_address("item 3 = ", the_next_item);
    the_next_item = the_next_item->next_item;
    print_pointer_address("item 4 = ", the_next_item);
}
void loop()
{
}

它输出:

--addresses of everything--
pointer to first_item = 68
pointer to second_item = 6C
pointer to third_item = 70
--go through list via pointers--
item 1 = 68
item 2 = 6C
item 3 = 1
item 4 = 5350

我的问题是:为什么第3项不等于"70"

我想可能,我应该使用一个pgmspace函数来读取结构,但我不明白为什么它似乎适用于第一项。谢谢你给我的任何帮助或建议,我应该读一读才能理解这一点。

好的,解决了它。在PROGMEM中获取结构字段中指针的正确方法是:

the_next_item = (list_item*) pgm_read_byte(&(the_next_item->next_item));

我确实很困惑。此外,它似乎适用于前几个例子,这是转移注意力,让我走上了错误的道路。我仍然无法完全解释这一点——可能只是运气?我不确定。

有关指针和PROGMEM的最有用的资源,请参阅此处:http://www.nongnu.org/avr-libc/user-manual/pgmspace.html