Put arduino in SLEEP_MODE_PWR_DOWN and wake up after x hours

Hi!
I'm working on an irrigation project and I need that my Arduino (AtMega328P) goes to sleep mode to preserve battery. And I need that after x hour (a choice that makes the user the first time) the Arduino wake up, do some things (in my case water the plants) and then come to sleep again.
I do some research and I find the LowPower library, but after the 8 second the library needs an interrupt and it seems that can only be wake up with a pin change state.
How can I do that?
Thanks a lot for all the people that will find a little of their time for my problem!

How much battery capacity are you planning on using? What nominal voltage?
What other things are drawing power in the circuit? regulators, relays, other chips? How often will they be turned on and off?

1 uA drawn from a 3,000 mAh alkaline AA battery will last three and a half centuries. The battery only has a shelf life of 10 years. It's far more likely that whatever you're doing during that on time will have a bigger effect on your battery life than the standby current.

The LowPower library has two drawbacks:

  1. It most likely uses the watchdog timer, which sucks for accuracy. If you want good timekeeping, you need to clock off a crystal. The Timer2 peripheral can have a separate crystal attached to drive it. It's designed to use a 32.768 kHz crystal, which is the standard value used by real-time clocks and will keep very good time (0.001% accurate instead of 10%). Timer2 is left on if you use Power-save mode instead of Power-down.

  2. Power-save mode with the external crystal actually uses less current than Power-down with the watchdog timer (1uA vs ~5uA). The electrical characteristics section of the datasheet have numerous graphs showing current usage for the different power modes and how they are affected by ambient temperature and supply voltage.

Forget using some opaque premade library and use the functions from AVRlibc directly. What you want is in the avr/sleep.h header.

Also make sure that you are turning off all unused peripherals when you don't need them using the functions in avr/power.h.

I'm planning to use a 9V battery, using it with an Arduino nano (5V). Every x hours, I want it to wake up, turn on a MOSFET (FQP30N06L) that open a solenoid valve for 30/60 sec, then turn it off and put again the Arduino to sleep mode.

Forget using some opaque premade library and use the functions from AVRlibc directly. What you want is in the avr/sleep.h header.

So, how can I do it? It's possible to program it with the Arduino language in the IDE?

Also make sure that you are turning off all unused peripherals when you don't need them using the functions in avr/power.h

How can I do it?
Many thanks!

I'm planning to use a 9V battery, using it with an Arduino nano (5V). Every x hours, I want it to wake up, turn on a MOSFET (FQP30N06L) that open a solenoid valve for 30/60 sec, then turn it off and put again the Arduino to sleep mode.

This is why I asked.

9V batteries suck for the most part for these kinds of projects. They have as much energy capacity as a AA battery, but when you put that through a linear regulator you're pissing away half of the energy to heat.

What is the spec for that solenoid? Do you have a datasheet for it? How much voltage and current does it require?

Also, the Nano board has more than just the microcontroller on it. It also has a UA78M05 voltage regulator and an FT232RL chip to convert USB to TTL serial. These two chips have a quiescent current of about 20 mA. Even if you completely removed the microcontroller chip, those two chips alone will drain a 9V battery with 600 mAh capacity totally flat in less than 2 days and there's nothing you can do to stop it. There's no sense shaving microamps off your microcontroller's current usage when the other chips are flushing away 10,000 time more than that.

You need to get off a premade board and use only the bare minimum components that you need. There are any number of "Arduino on a breadboard" tutorials, google and read a few of them. Focus on ones that don't have an external crystal or resonator. Order some spare ATmega328P chips from somewhere online so you can play with them outside the development board.

Low power usage and maximizing battery life is a proper engineering challenge in its own right, and if you really want to wring maximum capacity out of your batteries you will need to take off some of the Arduino training wheels.

So, how can I do it? It's possible to program it with the Arduino language in the IDE?

Yes, it's possible. You need to #include <avr/sleep.h> and #include <avr/power.h> to have access to those functions, just like you would #include a library header file.

I know that, but I need 9V to use the solenoid valve. I don't find any datasheet and I will measure myself the current that the valve requires. ( When I find the current that it requires, how can I calculate how much time a battery work before flat?)
I also know that the 5V regulator is not efficient, and I have planning to change it with one more efficient, but I totally ignore the USB to TTL converter. Does it drain much current?
The only solution is to make an Arduino on a breadboard myself?
Also, you mentioned two libraries about power saving mode, but not one that manage the time and wake up the Arduino after x hours, can you tell me one?
Thanks!

But the very problem remains the software: How can I do some action every x hours and then put the Arduino again to sleep. (The problem is not how to put the chip in sleep mode, but how I can wake it up every x hours)

Where did you buy the solenoid from? They've probably got a product page with specs on it. Finding this out is priority 1 right now. Even only turning it one for a minute every few hours, the solenoid is such a massive power suck that averaging it out of such a low duty cycle might still leave it as the dominant energy consumer.

A proper datasheet will tell you everything you could even possibly need to know about a component (far more than a hobbyist usually needs), you just need to know what it's called. The important figure that I looked at here is usually called quiescent current (IQ)or supply current in the datasheet. I searched for a schematic of a Nano board, saw the chips on there labeled UA78M05 and FT232RL, and searched for their datasheets ("UA78M05 datasheet" in google will work, or you can go to the manufacturer's website, Texas Instruments and FTDI for these two).

The 78M05 as speced with a typical supply current of 5 mA, and the FT232 is 15 mA typical. Adding those together is where I got the 20 mA from. Using that to estimate the expected battery life is fairly straightforward. Using an Energizer Alkaline 9V (google "9V battery capacity") as a generic stand-in, it has 600 milliamp-hour (mAh) capacity when the discharge current is 25 mA. Close enough to the calculated discharge current, I used that figure. Divide the milliamp-hours by milliamps and you have the estimated battery life: 30 hours.

When you get your solenoid's current consumption, you do the opposite: multiply the milliamps used by the amount of hours it will use those milliamps and you get milliamp-hours to see how much of the battery's capacity is used. As an example, suppose the solenoid needs 500 mA and you leave it on for 1/60th of an hour (1 minute). That's 8.3 mAh used each cycle of the solenoid. 350 / 8.3 = 42 activates before the battery goes flat. That's a week if you activate the solenoid 6 times a day. This is not factoring in the other uses of power, so every other thing you add the the circuit will reduce that time.

Given the limited knowledge you have of this, I imagine that your idea of a "more efficient regulator" is a switching one. The regulator is only going to be powering the microcontroller, which is going to be using every trick that it can to reduce current consumption and squeeze out every last microamp it can. At that low level, the dominating power-waster in the regulator will not be the conversion efficiency but the IQ of the regulator. If the 5V microcontroller is averaging 5 uA current consumption, the difference in current draw from a 9V battery between an ideal linear regulator (55% efficient) and an ideal switch-mode regulator (100% efficient) is less than 3 uA. The difference in IQ is far greater. A cheap linear regulator like MCP1702 has a typical IQ of 2 uA. A switch mode regulator that has a low-load switching mode like this SX1308 still has an IQ 50x greater than that. Linear wins this efficiency contest by a landslide.

The development boards are meant to make prototyping and development easier. They are most definitely NOT optimized for low-power usage. You need to have tight control over what hardware is on the board and how much power it's using. It's simply not possible with the preassembled boards that have extra stuff on them.

For the software side of things, I don't believe there is a premade library to do it, especially if you're using Timer2 in asynchronous mode like I recommend for this. I will admit that I haven't actually looked for one though. The effort it would take you to search for a premade library and study and test it to figure out if it suits your needs would be better spent just making your own functionality. Everything done in a library can be done in your own sketch, there's nothing special about them. Making a library just lets you reuse that code in different sketches and share that functionality with other people.

The software part of this is easy. In outline, you set Timer2 to generate an interrupt at regular, slow time periods. With a 32 kHz crystal you have options for every 8ms, 62 ms, 250 ms, 0.5 s, 1 s, 2 s, or 8 s depending on what you set the prescaler to. 1s will make the math easier, so let's call that variable rtc_current_seconds. You have the TIMER2_OVF interrupt increment a variable every time it ticks, that will give you a running count of the number of seconds since the program has started (a slower version of millis(), basically). Before you go to sleep, store the current # of seconds in a variable (start_of_interval) and the # of seconds until the next solenoid activation (length_of_interval). then you just enter into a loop like this:

set_sleep_mode(SLEEP_MODE_PWR_SAVE);
while( rtc_current_seconds - start_of_interval < length_of_interval )
{
  cli();
  sleep_enable();
  sei();
  sleep_cpu();
  sleep_disable();
}

There is no way I can conceive of to get several hours of continuous sleeping time without external hardware. Using just the peripherals on the chip and a 32.768 kHz crystal, the maximum sleep interval I can come up with is 2048 seconds (about 34 minutes) if you put all the prescalers on their maximum setting. There is likely no need to go that far though. The increased power usage during the awake periods will only be for the briefest of moments until it falls back asleep. The solenoid it probably going to have a much bigger impact on battery life than these periodic wakeups.

Download and study the microcontroller's datasheet and study what is necessary to set up Timer2 in asychronous mode. Go to the folder where the Arduino IDE is installed, and go down these folders: hardware/arduino/avr/cores/arduino and open wiring.c in a text editor. Study how ISR(TIMER0_OVF_vect) and millis() are coded, because you will need to recreate something similar on Timer2.

I made some measurement, and these are the results: AtMega328P-PU on breadboard at 3.3V consume, with a blank sketch, 6.90mA in average. If I put it in LowPower mode with this library (I know that you recommended me to don't use this type of library, but I wanted to try immediatly the SleepMode without spending many times on documentation) the mA changed radically: 4.3μA in 3.3V and 6.2μA in 5V. I also measure the mA require by the valve, and in average is 320mA. Now I have a problem: I need 9V to use the valve, but how can I power my AtMega? It's better to have two power supply, or one with a switching power regulator that conver 9V to 3.3V(and which one I must choose?)
And another question: the mA that I measured are mA/h right?
Thanks!

I didn't say you couldn't use it, just that I thought it might be suboptimal for this project. Those values seem about right if you are turning everything off with that library and using one of the times to wake up instead of SLEEP_FOREVER. Here's the table from the datasheet for reference:


4.2 uA typical at 3V Power-down with WDT enabled. You're measuring about 4.3 uA @ 3.3V so that fits perfectly.

Also, it looks like it does have a Power-save function, so you can still use it with the Timer2 crystal idea.

You will not want to use a switching regulator to power your microcontroller. I directly addressed this in my paragraph starting with "Given the limited knowledge..." in my last post, and also linked to a linear regulator (MCP1702) that is perfect for this application. If there's anything in there you didn't understand I can try to explain it better.

mA (millliamps), mAh (milliamp-hours), and mA/h (milliamps per hour) are not measuring the same thing, just like meters (m), meters per second (m/s), and meters per second per second (m/s/s) measure three different things (distance, speed, and acceleration). To calculate mAh from mA, you need to multiple by the amount of time you are drawing that current. For example, 320 mA draw for 1/60th of an hour (1 minute) is 5.3 mAh. 320 mAh drawn for 1/120th of an hour (30 seconds) is half that, 2.7 mAh.

It's just like calculating distance by taking your speed and multiplying by the amount of time you were traveling at that speed.

It is pretty clear that the solenoid is the most critical part of this project. It is by far the largest energy user; even being on only for 1 minute every few hours, my rough estimate shows that it's using over 1,000 times as much energy as the rest of the circuit. Power reduction on the microcontroller is pretty trivial, it's the solenoid that you need to think about.

In addition to the power usage, another concern is the voltage your solenoid requires. It's unfortunate that there isn't a datasheet for this. The Ebay page only gives a nominal figure of 9V, but the voltage of a battery drops as it's discharged. If you look at the datasheet for the 9V I linked in the last post, you can see in the fine print of the capacity graph that it is for "Continuous discharge to 4.8 volts at 21°C". If your solenoid can't operate below 7V for example, the actual usable battery capacity will be significantly smaller, reducing the battery life. You need to determine what the lowest usable voltage is for the solenoid. I don't know how it's constructed, but it may be more difficult to operate in a plumbing system rather than free air, so you should test it hooked up to the water source you want to control with it.

Here's the current list of things you need to decide and discover:

  • How much accuracy do you need? The watchdog timer used by the period argument in the LowPower library has an accuracy of +/- 10%. For a 5 hour sleep period, it could be up to half an hour early or late. I recommend the 32 kHz crystal approach. It's 3 extra components for 1,000 times better accuracy.
  • How long does the solenoid need to be powered each time? A 30 second opening time will have double the battery life of 60 seconds. Because the solenoid is the largest energy user, reducing the amount of time it needs to be actuated will have the most significant impact on your battery life.
  • Find out the minimum voltage that will cause your solenoid to actuate acceptably. If this turns out to be too high, we will need to explore other options like a boost regulator.
  • How much space are you willing to use for a battery pack? You're fine with a 9V, but what about a battery of 6 x AAA cells? 6 x AAs? a 6V lantern battery?
  • What is the minimum battery life you would consider acceptable? A week? A month? Half a year?

Thanks for the answer!
So:
1- I need a quite good accuracy because I'm planning to active it every 8-10-12 hours, so an error to 1/1.5 hours is really too much. So, if I use a code like this I'll have an error of 1.5 hours?(obviously, I'll increase the counter to reach the 8-10-12 hours)

void sleepTenMinutes()
{
  for (int i = 0; i < 75; i++) { 
     LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); 
  }
}

2-I don't know because I'm planning to share it with other people and everyone can change the watering time setting to 30 seconds or to one minute. No more than one minute, anyway.
3-It seem it still acceptable working at 5V (using 220mA), but I'm not sure because I only verified that the water pass throws the hole, and not if the hole is completely open. So the 6V lantern battery solution can fit well in my project (i don't understand very well the discharge graph, so I'll wait for your comment about it)
4-The space is not a problem, I'm going to use it in the garden, so no problem of space (obviously I can't accept a battery car anyway).
5-Less than a month is unacceptable, but my intention is to find a 2-3 month solution (or better, obviously).

  1. Correct. The period argument for the LowPower library functions uses the watchdog timer as a wake-up source. The WDT is clocked from an RC oscillator in the controller which has poor tolerance.

Here's an anecdote about the WDT: I did a school project once attempting to use as little power as possible to synchronize a transmitter-receiver pair. We used ATtiny84 microcontrollers and nRF24 transceivers for the wireless radio. There was about 1.5 seconds in between transmissions, so we put the radios into SLEEP_MODE_POWER_DWN in between, using the WDT to wake them up. The receiver was coded to wake up with about 30 ms early and wait for the transmission. If it got the transmission it immediately went back to sleep; if it didn't, it stayed awake for one full transmission period to catch the next message. If it missed two transmission in a row it would beep and flash a light to alert that the transmitter was offline or out of range.

We made 3 pairs of breadboard prototypes and investigated how well they functioned. The result was quite amazing. 1 worked perfectly, 1 pair the receiver frequently woke up too late to catch the transmission and had to stay awake until the next one, and 1 pair the receiver always woke up late.

I've attached the presentation we gave to the class at the end. Slides 13, 14, and 15 show oscilloscope measurements of a 47 ohm current shunt resistor measuring the current draw of the receiver's ATtiny. It looks like a digital signal, but it's actually current draw. The high level is 71 mV, which is about 1.5 mA the controller uses when active. When it goes low, that's when the microcontroller went to sleep and its current usage dropped to a level too small to measure with that setup.
EDIT: Nevermind, it was too big.

The difference in battery usage between Pair #1 (always late) and Pair #2 (ideal operation) was huge. We calculated that the ideal one would last a month on a CR2032 battery, but the always late one would drain the same battery in less than a day.

So I learned directly on that project that the WDT sucks for keeping accurate time. Even with all the devices at the same voltage and temperature, the tolerance difference was too much to be worth using. This will be even worse for your project. The WDT oscillator varies quite a bit with temperature, so an outdoor project will have additional variations.


Even with a consistent 3.3V supply voltage, varying the temperature between 5oC and 50oC results in a 2.6% change in frequency, running faster when it's cold and slower when it's warm.

Even a cheap watch crystal is less than 0.25 USD from a reputable supplier, has a 20 ppm tolerance (0.002 %) and 0.03 ppm/oC temp co. 20 ppm tolerance means it could get up to 10 minutes of error per year.

  1. So 60 seconds worse case it is then.

  2. If the water flow is sufficient, that's all that's necessary to know. The solenoid appears to have a resistance of 25 ohms. Using 7V as an average that a "9V battery" would be able to put out, that works out to about 4.6 mAh of capacity used per 60 second activation. A battery of 6 AA cells would probably be good for about 400 activates worst case. Energizer's datasheet says about 1,800 mAh for 250 mA drain current, but that's for continuous drain, not infrequent pulses. The real battery life is probably significantly higher.

If you have a 8 hr time between solenoid activations, that's at least 130 days of operation, over 4 months with the 60 second valve time. Reducing the valve time and reducing the activation frequency will only improve the battery life from there.

6 C cells will give you 3x more life than AAs, and 6 D cells twice as much time again over C cells.

I should mention that the calculations were done with alkaline batteries. Rechargeables have significantly less capacity.

  1. So there are limits, they just aren't the biggest constraint.

  2. By my calculations, 6 alkaline AAs is coming out to about 4 months worst case battery life. That should be perfect.

So, I will use an "Arduino on breadboard" powered with an MCP1702 to control an FQP30N06L MOSFET that switches on and off the solenoid valve, using 6 alkaline AA batteries. Is it all right?
Now the big question is, how can I make an interrupt with the Timer2 running asynchronously with an external 32kHz? I read the post where you mentioned this, but I don't understand very well how can I do the software. Can you explain to me how can I do or link some tutorial or documentation that can be useful, or just say me where to find some useful information?
Many, many thanks!

So, I will use an "Arduino on breadboard" powered with an MCP1702 to control an FQP30N06L MOSFET that switches on and off the solenoid valve, using 6 alkaline AA batteries. Is it all right?

Ding ding ding! We have a winner!

From the standard voltage options for the MCP1702, I recommend the 4.0V output.

Datasheet. I keep one on my Drive account, here's a link: https://drive.google.com/file/d/0B80Hh3Ka3Ob_R1JXRGNsX1ZqZ0U/view?usp=sharing

555 pages containing everything you need to know about every part of the chip. That's where I took the table and graph screenshots from that I posted above. Good thing it's got a table of contents.

The section you will be need to look at is #18. 8-bit Timer/Counter2 with PWM and Asynchronous Operation. There is a register description section in there that details all of the registers that control the operation of Timer2 and how they affect it. Registers can be assigned a value just like variables, for example:

OCR2A = 100;

You will also need to read the documentation about AVRLibc to learn how to define the timer's ISR.

If you aren't used to datasheets, a microcontroller's will be pretty intimidating. Just remember that you won't need to read the whole thing, just skip around and look for the bits and pieces concerning the particular part of it that you are currently working with.

Eternyt:
Hi!
I'm working on an irrigation project and I need that my Arduino (AtMega328P) goes to sleep mode to preserve battery. And I need that after x hour (a choice that makes the user the first time) the Arduino wake up, do some things (in my case water the plants) and then come to sleep again.
I do some research and I find the LowPower library, but after the 8 second the library needs an interrupt and it seems that can only be wake up with a pin change state.
How can I do that?
Thanks a lot for all the people that will find a little of their time for my problem!

Hello

Did you get solution for your question. even i am doing similar task i want device to wakeup after x hours do task and go to sleep. if you have can you please tell me details

Hi Jiggy-Ninja. I am a bigger noob do Ardunio. Got som basic programmin and U=IR skills.
I have done a remote contolled board to steer an anomal feeder station.
I want the board to sleep all day and wake up and poll for changes once per day, 5 minutes. With 7Ah battery it should last for 1/2 year if I can sleep at 2mA.

People seem to have done this on a 1300 board. How?