Changing the value of a variable and keep it afterwards

Hello everyone,

I don't really know if this is possible, I am using processing, arduino and a force sensitive resistor to control a servo and I want to change the value of a variable and then if I reset the arduino, it will kept the new value. Is there anyway to do this?

This is the part of my code I want to change.

void fsrMovement(){
        int maxforce= 1023;  // THIS IS THE VARIABLE

        if(Serial.available()){  // SERIAL AVAILABLE TO USE WITH PROCESSING
        maxforce = Serial.read();
        }
        force = analogRead(FSR);  // Reads the FSR
      
        Serial.print("Force sensor reading = ");
        Serial.println(force); // This will print the raw force value
        int pos = map(force, 0, maxforce, 0, 175); // Scales the force reading to degrees for servo control
        Serial.print("servomotor degrees = ");
        Serial.println(pos); // This will print the adjusted servo reading (an angle)
        myservo1.write(pos); // Write the new angle to the servo
        delay(10); // Delay 10 milliseconds before taking another reading

In order to do this you would need to store (and read at initialization) the value in a memory that is not impacted by power cycling your arduino.

it turns out that the microcontroller on the Arduino boards have at least 512 bytes of EEPROM* which is a memory whose values are kept when the board is turned off.

You can see the EEPROM Write Tutorial to find out more on how this works.

Note that the EEPROM memory has a specified life time of 100,000 write/erase cycles, so you may need to be careful about how often you write to it.

An EEPROM write takes 3.3 ms to complete, so if you are cycling through your program and writing the value in EEPROM at every loop, lets say every 10ms, then in 17 minutes your arduino EEPROM is dead...

if you use it sparsely then that's fine.

An alternative would be to add a SPI Micro SD Storage Board (you can get one on eBay from China for $1.25 US including shipping), add a 1GB Class 10 SD card (less than $2 with shipping from china on eBay) and then you have a huge (1GB) repository where data won't be erased. The SD card will wear out as well with time, but then just throw away the damaged SD card and replace it for $2 instead of throwing away your arduino :slight_smile:

Those Micro SD Storage Board are driven from the SPI interface, here are some SD Card Notes and useful links for this


*Note:

The supported micro-controllers on the various Arduino and Genuino boards have different amounts of EEPROM: 1024 bytes on the ATmega328, 512 bytes on the ATmega168 and ATmega8, 4 KB (4096 bytes) on the ATmega1280 and ATmega2560. The Arduino and Genuino 101 boards have an emulated EEPROM space of 1024 bytes

Amazing! thank you!