Softly To Sleep, My Raspberry Pi

For all their capacity, shutting down a Raspberry Pi can be a bothersome routine depending on how you have it set up — historically and abrupt cut to the power risks corrupting the SD card. [madlab5] had to make a few changes to a Pi running in headless mode, requiring them to access it externally to shut it down to prevent any damage from pulling the plug. So, why not take the opportunity to whip up a soft shut-down switch?

This is a great beginner project to get one accustomed to working with a Pi. With this in mind, [madlab5] went through two revisions of this idea: the simple way, and the fun way. For the simple way just press the button and the Pi activates a script which shuts it down in thirty seconds. Job done. But, realizing there may be a few circumstances where they’d need more functionality, [madlab5] decided to take a second swing at this.

[madlab5]’s fun way involves a button with a built-in LED and a speaker to blare an announcement that the Pi will self destruct shut down after a short time. Setting the switch up this way takes a little more doing, but you get to add a little more character to your Pi with a custom shutdown report, as well as the option to cancel an accidental button-press.

For any newbies out there, [madlab5] is kind enough to provide their code and diagrams in their blog post. If remotes are more your thing, we have also featured a similar beginner project to shut down your Pi.

[via /r/Raspberry_Pi_Projects]

45 thoughts on “Softly To Sleep, My Raspberry Pi

  1. Well done!
    I find it extremely interesting–as should everyone–that the designers of the Raspberry Pi have simply ignored the problem of shutting down the machine, ever since it was introduced.

    What a great way to teach kids about computers!

      1. On/off switches cost money. Instead we made sure that the hardware wouldn’t corrupt the filesystem – easier when you’re not using SD cards mounted on Linux, granted…

        1. Good answer. Typical Raspberry Pi Foundation answer and strategy: a negative is really a valuable benefit.

          See [John]’s solution (below) using a PIC microprocessor in a RPi design to ensure a clean shut-down.
          This is not the first time someone has employed a microprocessor to correct a RPi “benefit”.

          “On/off switches cost money.”
          Admittedly. You are to be commended for not even considering using a costly switch when a simple microprocessor will do…and for pointing this out to us.

          1. Ugh, RPi is such a disaster from a robust design standpoint. SD card for OS Storage, really? USB ports with no data lines? Why doesn’t Raspbian have a USB serial console enabled by default? BeagleBones do it so much better (except for the USB Host port on the Black, not sure about later ones). I get that the Pi is for “educational” purposes, but that shouldn’t mean as an example of what not to do.

          2. Another way to solve this is to mount the filesystem read-only. When it’s time to shutdown just kill the power and done.

            I personally don’t fault the RPF for cutting corners; that makes it cheaper. But I am very, very eager to find a Linux board with microamp deep sleep and millisecond wake like a microcontroller.

            I long for that in a Linux board. I could see Linux on an AA lasting months, depending on the duty cycle.

      2. You could allocate 1 GPIO pin to a switch and use that to generate a clean power down, I do not see it as a flaw (OS’es need time to tidy up before you yank away the power supply).

      3. Most of us use readonly (perhaps cryptolooped) filesystems. You don’t want to send things out into the world with read-write filesystems if you care at all about system integrity or having a reliably bootable device. An on-off switch isn’t going to save you from all of the possible corruption opportunities, and you don’t want people asking why their box won’t come up.

        Also, you don’t typically see switches on little boxes that are meant to run 24/7 forever – or at least for the next 10yrs. Perhaps you are referring to more mobile or user-facing products, though, than I’m familiar with. That said, it is a pain to work on kernel things when there is no switch. I use a power strip with a rocker switch to keep from having to unplug the power brick 1000 times a day.

      4. We ship embedded systems without on/off systems all the time. Usually, however, we try to be asleep whenever we’re not actively doing things. Plus, reliable code has to safely deal with power interruptions, so SD corruption on reset would be a priority 1 issue.

        As you learn embedded programming, pay attention to your assumptions about power and resets and memory integrity. You can lose state at any time due to loss of power, electrostatic discharge, etc, so plan on a safe recovery mechanism.

      5. I worked for a major European telecom company that had cell-tower equipment (running various versions of Windows Server) that weren’t designed to shut down, ever.

        1. You have eloquently elucidated an answer to the “Raspberry Pi Problem”:

          In order to solve The Raspberry Pi problem, one must simply design a Raspberry-Pi system which will never be turned off.

          I think you have, in one concise sentence, made two things absolutely crystal-clear: (a) the only correct–and possible– solution to the “Raspberry Pi Problem”, and (2) the real reason Eben Upton hasn’t solved this problem since he released the design back in 2012.

          Thank you. Sometimes the real solution is the simplest.

          1. Think of the mindset — if something were to go wrong with “product X”, you don’t want to have to troubleshoot it over a serial console or haul your laptop in to perform a 12 hour RDP-based reload session in an unheated/uncooled shack in the middle of nowhere. You instead rip the 10U chassis out of the rack, put in the replacement, plug in 4 wires, and power up. You take the old “X” (which has been upgraded to “X+1” by the swap, most of the time) and scrap it at that point.

  2. The problem is that the shutdown time is really variable so I used a PIC to monitor the video out signal then remove power once that went away. It was the only way I could find to be absolutely sure it was shut down before power was removed.

    1. Do you need to do that? Can’t you just monitor the 5V power supply? Maybe get your own USB port and wire it to the Pi’s 5V, through a diode (a low voltage-drop one eg Schottky). Run a battery pack to the same pin, also through a diode. Then detect power loss by wiring from the power supply before the diode to a GPIO. Actually best to add one more diode, from the power supply to your GPIO pin, just so the GPIO voltage isn’t slightly higher than the Pi’s supply voltage, cos theoretically chips don’t like that.

      3 diodes and some wire, it’s simple.

      If you don’t want to use the battery pack, you could just put a big cap between 5V and gnd. No diode needed for that, just the one from the power supply lead. Maybe a few ohm resistor in series with the cap, if it’s a really big one.

          1. Mine was a suggestion for how to provide cheap backup power, which the Pi can detect and shutdown gracefully. John’s idea was detecting when the Pi has shutdown normally, so it’s safe to turn the power off.

            Don’t they say “wrong end of the stick” where you come from? It’s an idiom. “I’ve got the wrong end of the stick” means you’ve misunderstood the situation, or rather understood it in the wrong way, from the wrong point of view.

          2. If I recall correctly, the idiom derives from the days of outhouses when a stick was kept at hand to manage the pile height. A variant where I grew up was “Sh*t end of the stick.”

          3. “Shitty end of the stick” means getting a bad deal, or the unfavourable option, in a deal. “Wrong end of the stick” just means not understanding something properly. Making the wrong assumptions or misunderstanding some basic principle, causing you to then come to an incorrect understanding of the situation.

            Whoever it is goes round shitting on sticks, or sticking them up their arse, or gods know whatever else, I dunno. Maybe there really was an apocryphal stick. It would be the wrong end to grab of it, but the “wrong end” idiom has developed a meaning that’s nothing to do with poop sticks.

    2. You can configure the RPi to set the level of a GPIO pin upon shutdown. You use the gpio-poweroff overlay. I’ve used this to trigger power down (e.g. via MOSFET, or external PSU shutdown pin) on a couple of projects.

      You simply add this to the `/boot/config.txt’:


  3. I’ve always meant to have a go at a soft shutdown trigger linked to a UPS, meaning that the device simply shuts down when the power is pulled. A good solution for pi-based consumer equipment, etc.

    1. Me too. But because a UPS is more expensive than a PI, I was thinking about using a USB battery bank between the charger and the Pi and a small circuit that triggers a GPIO pin when power is lost.

  4. I’m wondering if You can use distro like eg slax, put it on sdcard in read only.
    This should work like system booting from CD, so it should be resistant to shut down by cutting power.
    If Yu want a change in system eg add new software You can remount sdcard and download package or put scdard to pc and add it there.

  5. I have tried to corrupt my Raspberry Pi by disconnecting power hundreds of times at different points in booting and operation and couldn’t get it to happen. Has anyone compared disk images between corrupted and OK cards to see what is actually wrong? Is it the SD Card that is corrupted or just some files? If it’s only a few files that were being written to and corrupted then it should be possible to fix the code that can’t presently recover. I mostly use SanDisk cards so maybe it is primarily cheap cards that fail.

    1. The couple times it happened to me, it rendered the sd card unusable so it’s not like I could compare.

      I suspect it was more pronounced with earlier versions of Raspbian that were doing more active swapping because it only happened with my original 256MB model B. But I haven’t tried to keep one always on since then either.

    2. How did you check for corruption? Did you check every last bit, of all software?
      This is a very well documented “feature” of the Raspberry Pi, and has been since Day One; it has been aggessively ignored by the Raspberry Pi people. Since Day One.
      It ain’t ‘cheap cards’ or ‘slow cards’ that’s the problem, although I wouldn’t be a bit surprised that if, in all the words which have been written about this “feature, the RPi Group hasn’t posited this as the problem

      Egregious Part: If this “feature” were easy to fix, then Eben Upton should have fixed it eleven million RPi s ago. Shouldn’t he? And your conclusion is…?

      [A little (gallows) humor for your entertainment, and you too, [Dielectric]:
      someone did write, a while back, that this “feature” was of benefit to all the little children learning computers, since they needed to learn about real-world computer hardware problems!]

      1. I defined corrupted as being unable to automatically start up and run my data logger. I couldn’t find any documentation beyond people claiming “my RPI won’t boot anymore” and the solution being to reflash the card. Can you please show me where this is well documented so I can reproduce it and try to figure out what is happening?

    3. I accidentally plugged my Pi B+ and Pi B into a socket that’s connected to the main light switch in my living room and lost power at least once a day. This meant the Pi’s where corrupted every couple of weeks. Initially only the data was corrupted, but I was never able to recover anything. After a while the cards went corrupt and went to into a read-only state.
      The corruptions could be caused by the multiple reformats, but they were quite decent cards and I think don’t think this was the sole cause.

      These are just observations, but I hope they give you a bit of a better image.

    4. It happens regularly to me, the file that gets corrupted is always the /etc/network/interfaces file. I’d say about 40% of the time if I just pull the power. Quite often it’s the backup copies in that directory as well. I overwrite a new copy and it’s good to go again.

  6. Is everybody sure that the file corruption is from shutdown? Can it be that it is from read disturb issues on sd cards? These problems arise in less robust cards that use multulayer (mlc, tlc) nand flash. The system could work perfectly well when the corrupted locations aren’t being accessed, then when the system tries to power up after a shutdown those locations are accessed causing the system not to load properly. I have seen a read disturb so bad that the firmware on the sd card was corrupted rendering the sd card completely unusable.

  7. “an announcement that the Pi will self destruct / shut down after a short time”

    Reminds me of an old episode of Get Smart:
    “This message will self destruct in five seconds”
    “Maybe a bit longer”

  8. A little off-topic: do you know any SBC with good power management, so you can run it for a few days on smartphone battery if they are in sleep mode for most of the time?

  9. Really?

    “The Raspberry Pi Problem” has been around an awfully long time–five years and over 12 000 000 of the Raspberry Pi units–for the Raspberry Pi Foundation to have NOT offered up this solution.

    Then again, perhaps they don’t KNOW…

  10. This is probably a bit more involved than just a switch alluded to here.

    I made a MOSFET Raspi power switch;
    The schematic and boards along with shutdown script for the raspi 3B are in the link below

    First press turns on pi, short press shutdown through the script, and long press forces power off.

    you can order the boards through easy-eda if you like.

    the first revision I hand etched and the second I ordered they were very nice.

    In PCB V1 the P-Channel device is TO-220 while the N-Channel is DPAK
    In PCB V2 both are DPAK footprint

    The DPAKs are actually quite easy to solder

    PCB V2 uses a phoenix connector but is designed to be easily cut off if you need the space

    Both designs have a need for P-channel fets with Low RDS(on).

    I had issue with finding a high amperage USB with a long enough cord for my use case.

    I even made my own cord but didn’t like the way it looked, then I turned to the power brick
    design with a long mains cord and short usb cord. Finally I settled on a design I think works well

    I used a dc-dc buck boost converter so now I use a 12v 1A wall wart on input into the case there is a reverse protection diode just in case and I have had no Issues with 7.2v – 19v. (You could also get away with fets with higher RDS(on) this way)

    Now for powerctl_pin.c, the shutdown script

    gcc -o powerctl_pin powerctl_pin.c -l wiringPi && chmod +x powerctl_pin && sudo cp powerctl_pin /bin/

    sudo /bin/powerctl_pin 21 install

    sudo /bin/powerctl_pin 21 uninstall

    sudo /bin/powerctl_pin 21 poweroff

    /bin/powerctl_pin Broadcom_pin#, mode
    Valid Modes: poweroff, poweron, install, uninstall

    I had a hard time getting Jessie to run my scripts reliably so this program writes and installs the services for you.

Leave a Reply

Please be kind and respectful to help make the comments section excellent. (Comment Policy)

This site uses Akismet to reduce spam. Learn how your comment data is processed.