Skip to content

Arduino and memory how to

The most popular use of memory is the SRAM . By default when you declare a variable this variable is allocated on the RAM memory.
So you are using this type of memory by default.

// this constant won't change:
const int  buttonPin = 12;    // the pin that the pushbutton is attached to

// Variables will change:
int buttonPushCounter; // = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);

  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button
      // wend from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter, DEC);
    }
    else {
      // if the current state is LOW then the button
      // went from on to off:
      Serial.println("off");
    }
  }
  // save the current state as the last state,
  //for next time through the loop
  lastButtonState = buttonState;

}

Upload this code to your arduino and then press the screen monitor.
Try pressing the button. You should see that the clicks are counted

The code is pretty self explanatory . The program controls if the button is pressed. If it is pressed down then increase the buttonPushCounter.

As you can see the buttonPushCounter variable is stored at the RAM. This means that it is a volatile data. Every time the arduino starts this variable is re-setted to zero.

Below you can watch the SRAM demonstration video :

So the program counts only the run time clicks.  Some times this can be useful sometimes not.

What happens if we want to store buttonPushCounter? Let's say we wanted to count all the clicks even after a restart of arduino.
In this case you can store your variable at EEPROM.