Wednesday, May 15, 2013

On Using ROM Space for Non-variable Arrays in the Arduino IDE

Overview
This article assumes that the reader is familiar with using arrays in the Arduino IDE. When using arrays as per normal, the Arduino stores them in working memory. By storing non-variable arrays in program memory, larger arrays are accessible.



Using Program Memory
The Arduino has approx. 2KB of RAM and approx. 30KB of ROM for program space. Normally, the maximum length of an array is around 1900 bytes, due to the limitations brought about by the amount of RAM. Data can be stored and recalled from (large) arrays (up to ~30,000 bytes in length) by using program space.

To do this, the program space library has to be included by adding the following line to the start of the code:

#include



Creating an Array
Normally, arrays are initialised using RAM with something like:
byte sample_data[4] = {50, 31, 55, 87};

The above line of code creates a new array named sample_data. An element of sample_data is retrieved using the following formula:
data = sample_data[0]; // read element zero of sample_data into the variable named data
// data now equals 50

However, the maximum length of an array is approx. 1900 bytes. To overcome this shortcoming, we can create a non-variable array in program memory.



Creating An Array in Program Memory
To create an array in program memory looks complicated, but as long as it is formulised correctly, there shouldn't be any issues.

prog_char array_name[length] PROGMEM = {
// insert array data
};



Change the name "array_name" to the actual name of the array. Replace "length" with the actual length of the array.



Retrieving Data From an Array in Program Memory
To retrieve data from the program array, use the following code snippet:

data = pgm_read_byte_near(array_name + length); // read a value into the variable named data

Of course, change the name "array_name" to the actual name of the array. Replace "length" with the actual length of the array.



Putting it All Together - Sample Playback
The following code includes:
• The inclusion of the program space library
• The creation of an array with 22050 bytes in program space
• Playback of the array from program space
• This assumes that some sort of DAC is connected to PORTD of the Arduino


No comments:

Post a Comment