0

I use a small SG90 servo with arduino. When I call attach() servo moves to its default position or whatever I set with write() before it.

I’d like to make servo stay at the current position when I call attach() in setup().

How can I achieve it?

I believe I can simply store last position in EEPROM. It’ll help a little. However, I’m afraid that EEPROM won’t last long.

1
  • Why would you call attach() time and again? – G-aura-V Feb 2 '20 at 1:48
1

You can't read the servo's position, so your sketch has no chance to know the real current position.

And you found that you have to set up the initial value of the servo "driver" to the one your sketch thinks is the last known position of the servo.

So your problem boils down to these questions: "How do I store a value during power-down times?" This leads to the common solution of storing the value in the EEPROM. This is a well-known and widely accepted solution, but you already found a problem: "How could a value be stored in the EEPROM without over-stressing it?"

You need to look up the guaranteed number of write cycles for a EEPROM cell. Then you need to think about the rate you would like to save the value. Divide the values and you know how long this will work. However, in reality the EEPROM will have much better endurance.

Some ideas how to "get better":

  • Reduce the rate of saving. I see at least two factors: The refresh rate of the servo controlling pulse is just 50 Hz. And a servo will move between (extreme) positions only a few times per second. There might be no need to save more than once per second, or even slower, depending on your application.
  • Don't save if the value has not changed. Well, this should be done already at the driver level of the EEPROM. It won't hurt to read its documentation and/or its source code.
  • Use an as large as possible array to store the value. You will store a marker for "invalid" in all but one cell, and only this cell holds the real value. This will put the "load" of two writes per save on the EEPROM, but distribution over more than two cells will lower the average load. If you select an all-1s value as "invalid", it is actually just the same value as the erased value of the EEPROM, which is necessary the next time anyway.
  • Add a circuit that detects the power loss before the CPU stops. This is the most chosen solution, but only usable when the hardware can do it. You need just a few milliseconds to save the value, look up the documentation. If you implement an ISR that catches the coming power loss, save the value and await the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.