Skip to content
Roberto Lo Giacco edited this page Dec 14, 2018 · 2 revisions

Sample reference code for memory footprint comparison: tests are compiled with avr-gcc-5.4.0-atmel3.6.1-arduino2.

Manual

section size
.data 46
.text 3352
.bss 1172
#define SAMPLE_PIN A0

int buffer[500];
unsigned long time = millis();

void setup() {
	Serial.begin(9600);
	pinMode(SAMPLE_PIN, INPUT);
	time = ;
}

uint16_t idx = 0;
void loop() {
	int reading = analogRead(SAMPLE_PIN);
	buffer[idx++ % 500] = reading;
	if (millis() - time >= 500) {
		time = millis();
		float avg = 0.0;
		for (uint16_t i = 0; i < (idx < 500 ? idx : 500); i++) {
			avg += buffer[i] / (idx < 500 ? idx : 500);
		}
		Serial.print("Average is ");Serial.println(avg);
	}
}

CircularBuffer

section size variation
.data 46 0
.text 3480 +128
.bss 1176 +4
#include "CircularBuffer.h"
#define SAMPLE_PIN A0

CircularBuffer<int, 500> buffer;
using index_t = decltype(buffer)::index_t; // ensures using the right type for the index variable
unsigned long time = millis();

void setup() {
	Serial.begin(9600);
	pinMode(SAMPLE_PIN, INPUT);
}

void loop() {
	int reading = analogRead(SAMPLE_PIN);
	buffer.push(reading);
	if (millis() - time >= 500) {
		time = millis();
		float avg = 0.0;
		for (index_t i = 0; i < buffer.size(); i++) {
			avg += buffer[i] / buffer.size();
		}
		Serial.print("Average is "); Serial.println(avg);
	}
}
Clone this wiki locally