paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Controlled Shutdown at Power Failure

Thu Aug 08, 2013 12:41 pm

Got a little closer to the final solution.
All the circuits work, with two final details to sort out.

Here is the schematic of the circuits I have been working on:
ShutdownPower V5 Schematic.png
ShutdownPower V5 Schematic.png (22.57 KiB) Viewed 13224 times
[UPDATE] There is an error in the diagram. The input to Q2 should be VCC, not VDD, and R6 is connected to VDD and not VCC.
One thing I still need to solve is the right selection of the PowerFET that switches the 5V supply to the Pi. I ordered the Si3443DV based on the parameters, but I still loose too much voltage over the FET at 500mA.
The voltage drops from just over 5V to just about 4.75.
[update] Even at a Drain-Source On-Resistance of a mere 0.054 Ohm (typical @ 4.5V and 4A) the voltage drop should be only 0.027V, but I'm getting a total drop of 0.3V at 500mA and that is a problem. With a smaller load, the voltage is fine. Am I missing something? I'm certainly no expert on these devices, but if this is about the best you can get, that is not really good enough. I need to study this a bit more, to find out why I seem to get this deviation from the specifications. Can somebody please enlighten me? Otherwise it's back to the drawing board to soup-up the input to compensate for the loss, or use a relay. (The LT1302-5 is fixed, so I would need to change that to the variable version (LT1302) and set the output to 5.3V with two resistors - but I have that chip only in a very tiny SMD version) Stay tuned.

Working with parts that are so small has its challenges when you are testing. I resorted to the following contraption for the Si4334DV, which worked quite well (next to it a "normal" BS170):
Si3443DV.png
Si3443DV.png (33.56 KiB) Viewed 13224 times
I have some more parts on order to see if I can improve on the voltage drop. [update] No real improvement

I'm still waiting for my new NiMH's so that part of the circuit is not really complete, although it works.

I had to change some of my thinking regarding the pull-up or pull-down resistors for the GPIO pins. I tried to be smart and use the special function pins of the i2C or the UART, because they are pulled high "automatically". Well, yes and no. During the shutdown period, the PI changes all that, including, but that was to be expected the GPIO pins that you can program to be pulled-high or low.
Can't use that in this case.

In short, the circuit works as follows: When the power is applied, the Pi is halted by the circuit around IC2, a 555 timer, for about 10 seconds. The idea behind that is that when there has been a power glitch, the power may stutter a bit before it gets stable. The circuit I use strangles the Halt pin of the processor. I also use that together with a button and a circuit to halt/shutdown/reset the Pi. I described that in another post.

The circuit around the LT1302-5 has been explained in the posts above, there is basically no change.

The circuit around IC1, the other 555 timer is used to create a delay after a loss of power has been detected, and after the timer is done, the power to the Pi is cut, to preserve the energy in the NiMH cells. The parts that sense a loss of power from the 5.3V supply is not shown, but that is just a voltage divider to get to a nice 3.3V that is used to create a falling edge trigger in the software.

Q4 is used to "gate" the timer signal and avoid false triggering.

In the meantime, I wrote the code that looks for a loss of power, starts the timer and controls the gate that switches off the supply to the Pi.:

Code: Select all

#!/usr/bin/python2.7

from time import sleep
import subprocess
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

PWR_GATE  = 15 # GPIO-15 : P1-10
PWR_TIMER = 14 # GPIO-14 : P1-8
PWR_SENSE = 22 # GPIO-22 : P1-15

GPIO.setup(PWR_GATE, GPIO.OUT) # Turn power on regardless of timer
GPIO.setup(PWR_TIMER, GPIO.OUT) # kill power in 35 seconds after trigger
GPIO.setup(PWR_SENSE, GPIO.IN) # Senses the loss of the main 5V supply

# Init
GPIO.output(PWR_GATE, GPIO.HIGH) # Power on
GPIO.output(PWR_TIMER, GPIO.HIGH) # Trigger off

def system_action(PWR_SENSE):
    print ('Negative edge detected on channel %s'%PWR_SENSE)
    print ('Loss of power detected')
    GPIO.output(PWR_TIMER, GPIO.LOW) # Toggle timer with a negative edge
    print ("start timer")
    sleep(0.1)
    GPIO.output(PWR_TIMER, GPIO.HIGH)
    # When the timer starts, it changes the output of the 555.
    # Wait a moment, then release the power gate to let the 555 timer
    # switch off the power.
    sleep (0.1)
    print ("release power gate")
    GPIO.output(PWR_GATE, GPIO.LOW) # release power gate
    # Start the shutdown process
    print ("shutdown sequence started")
    subprocess.call(['shutdown -hP now "System shutdown due to power failure" &'], shell=True)


GPIO.add_event_detect(PWR_SENSE, GPIO.FALLING, callback=system_action, bouncetime=1000)
# setup the thread, detect a falling edge on channel 22 and debounce it with 1 Sec

# assume this is the main code...
try:
    while True:
        # do whatever
        # while "waiting" for power failure
        sleep (2)

except KeyboardInterrupt:
    GPIO.cleanup()       # clean up GPIO on CTRL+C exit
GPIO.cleanup()           # clean up GPIO on normal exit
This program is installed in /etc/init.d and installs itself when the Pi boots.

In the process of testing, I found that the power down sequence is such that I changed the timer delay from 45 seconds to about 35 seconds. The power down sequence between the sudo shutdown command and the last R/W activity and dropping of the current from 400-500 mA to about 120 mA is about 20-25 seconds so we have about 10 seconds to spare. The quicker we turn off the Pi, the more we preserve the capacity of the Ni-MH's, so we're ready for more power glitches if needed.

If you want to be more precise, you can also monitor the drop-off of the current by using a shunt in the power line and use a comparator to measure the drop and use it to kill the power.

Because my thermostat application is not time critical, I don't care if the power comes back up while the Pi has started the power down sequence. It will finish that before it restarts again.

Because I used a bread board for everything but the circuit around the LT1302, I may end up changing some R's and C's in the final built, but this should be very close.

More later!
Last edited by paulv on Sat Aug 17, 2013 5:39 am, edited 4 times in total.

nummy
Posts: 35
Joined: Tue Aug 14, 2012 12:07 am

Re: Controlled Shutdown at Power Failure

Thu Aug 08, 2013 9:22 pm

Great work!

I'm working on something similar but with a UPS. Since I have to shutdown multiple devices (NAS, PC, and RPi), I decided to get a UPS. The UPS I have doesn't have a way to communicate with devices to tell them to shutdown (I bought a cheap one and I'm too cheap to spring for the one that communicates). So I had to have a way to sense when it went on battery supply, then initiate shutdown sequences for everything.

The UPS has a 12V relay that I can sense to tell when it's gone to battery. I hook up that 12V to the input (diode) of an opto (MCT6) that I added on my Gertboard, and the output of the opto is driving a GPIO pin low. Once the relay trips and switches, the GPIO pin will go high and I'll know that I've lost AC power.

My Pi then proceeds to ssh into my NAS and PC and initiate shutdowns, then shuts itself down.

paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Controlled Shutdown at Power Failure

Fri Aug 09, 2013 12:02 pm

This is not really a topic for this forum, but since it is critical for the project, I ask for forgiveness...
Please help me to understand...

I have tried several P-channel MOSFETs that, judging from the datasheets, should be adequate for what I'm trying to do. I want to switch the 5V supply with a MOSFET, but I can't allow the voltage drop I'm getting.
None of the devices I tried seem to do what I expect and therefore are of no use for this project.

I'll be specific to what I did, so you can follow this and point out what is wrong.
The setup I used to test the MOSFET's is simple, apply 5.00V to the Source, ground the Gate, and load the Drain with different loads. The resistors I used to get the different loads are:
- 10 Ohm .25% 10W to create 500mA
- 20 Ohm (2 x 10 Ohm .25% 10W in series) to create 250mA
- 50 Ohm (2 x 100 Ohm 5% 1W parallel) to create 100mA
- 100 Ohm 5% 1W to create 50mA
- 500 Ohm (2 x 1K Ohm 5% 1W parallel) to create 10mA

For every measurement, I calibrated the 5.00V 2A supply, with the same Fluke 76 DMM, then took the voltage measurement across the load.

Here is a table of the results:
MOSFET table.png
MOSFET table.png (11.68 KiB) Viewed 13192 times
I included the typical On-Resistance from the datasheet with the stated voltage and current.

Here are the results in a graph:
MOSFET graph.png
MOSFET graph.png (12.77 KiB) Viewed 13192 times
The calculated curve is the typical On-Resistance of the Si3443DV multiplied by the current load, and subtracted that from the 5.00V supply to get the voltage drop.

Enlighten me please!

nummy
Posts: 35
Joined: Tue Aug 14, 2012 12:07 am

Re: Controlled Shutdown at Power Failure

Fri Aug 09, 2013 1:14 pm

With your load combinations, you're assuming your load is resistive and linear. Your Raspberry Pi is an active device and is therefore non-linear and has inductive and capacitive reactances. I'm no expert, but shouldn't this be taken into account also?

Have you seen the pi-supply.com design and how they did it? They have their schematic out there in the Downloads section.

paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Controlled Shutdown at Power Failure

Fri Aug 09, 2013 5:32 pm

Most, if not all devises are specified with resistive loads.
The pi-supply.com folks are using a relay to switch the 5V supply to the Pi.
Maybe they know more than I do...

paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Controlled Shutdown at Power Failure

Fri Aug 09, 2013 5:40 pm

The new Sanyo Ni-MH 2700mAh cells arrived and work like a charm.
Beware of old cells!

When I adjust the 5V supply to just about 50-100mV above the output from the Lt1302-5, you will see the high frequent switching noise of the Lt1302 on the 5V to the Pi disappear, and the 5V supply is in charge ;) of the Pi.
Yanking the power now is safe.

Next up is a bit more software to discard smaller glitches on the mains so we have a kind of UPS until we decide it's for real and need to power down the Pi.

Stay tuned...

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Controlled Shutdown at Power Failure

Sun Aug 11, 2013 1:33 am

Hi PaulV,

With respect to your MOSFET RDSon issue:
1. I checked out the first 3 FETs that you listed against their data sheets. All of them are specified with VGS = -10V. The load curves don't go below VGS=-4.5V. I suggest that you get a logic level FET. I used a Si2305DS in my circuit - its RDSon is specified at -4.5V and its normal VGSth is between -0.4V and -1.0V. Your FETs' VGSth can be as high as -4V.
2. I don't know what your test fixture is like but I'm sure you will find a good part of the on resistance is due to your fixturing. Is everything soldered in place with adequate gauge wiring? Are you making the measurements with kelvin connections right on the source and drain leads of the device?

(Relays are for weanies.;))

Bud.

paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Controlled Shutdown at Power Failure

Wed Aug 14, 2013 6:16 pm

Relays are for weanies.;) huh?

Bud, you were spot on with your comments, and I feel quite a fool for not getting to the problem myself.
I guess one cannot be warned enough about the pitfalls of the easy to use Breadboards. My experience (decades ago) was with current devices like ordinary transistors and I still have to get used to the very delicate voltage components like FET's and the likes. In any case, yeah, as soon as I soldered everything on a prototype PCB, the problems with the Si3443DV went away. Thanks for pointing that out!

paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Controlled Shutdown at Power Failure

Wed Aug 14, 2013 7:41 pm

I spent quite some time over the last week on trying to get all the separate components and circuits together, but as some of you know by experience, the system test typically unveils all the pitfalls of not well thought out ideas and overlooked details. This was by no means an exception...
Here is the result of the required changes:
ShutdownPower V6 Schematic.png
ShutdownPower V6 Schematic.png (37.23 KiB) Viewed 13061 times
Let me briefly explain the differences with the parts already published earlier.
R10 and R11 compose the circuit that senses the availability of the main supply voltage (this comes indirectly from the HVAC, and can be adjusted)
The circuit around the LT1302-5 has not seen any changes. The more I've worked with it, the more I like it. It's stable, reliable and very easy to use.

The PowerGate around Q1 needed a lot of changes, and I'll explain them along the way. Basically, I have created an OR gate at the Gate of Q4, turning Q1 on when: 1. there is a signal coming from the Pi through a GPIO channel (D4), 2. a Gate coming from the 555 timer, that is either triggered by the coming-on of the main 5V supply (more below), or the trigger sent by the Pi software through another GPIO channel. Lastly, 3, and this is the unfinished part, through D6, when there is a voltage level coming from the main supply.

The circuit around Q2 creates a negative trigger for the 555 timer when the 5 volt supply comes on line. The 555 has been composed to create a pulse of 45 seconds, keeping Q1 on, regardless of the inputs at D4 and D6. The reset of the 555 is delayed when the power comes on by R15 and C8, so it avoids a false trigger. The 45 seconds is just enough for the booting process (until my application is running) and more than enough for the shutdown process.

OK, now for the big picture, and here is where I had the rethink the design and make the changes at the system level. Despite the facts that all the previous circuits worked - stand alone, or even partially together.

Basically, what we need to do for the total system is to make sure that the Pi can boot without interruptions caused by the loss of power or glitches, and can work and also shutdown without disruptions caused by the loss of power or glitches in the power. And this is what the circuit now does.

When everything is without power, and the Pi is halted, a turn on of the mains supply VCC triggers the 555 through Q2, which is also connected to VDD. (there are actually 4 different 5V supplies)
  • - 1. VCC the main supply with the adjusted 5.40V
    - 2. The battery generated 5.00V at the Anode side of D1
    - 3. VDD the "mixed"supply of 5.02V
    - 4. the 5.00V to the Pi
With the pulse created by Q2 and the R's and C's, the 555 fires, and makes sure that for the whole 45 seconds, no matter what happens, the Pi can boot cleanly and uninterrupted. As soon as the application program is started during the boot process, it takes over. (we'll discuss that below). When the application is running, and there is a loss of power, that get's sent to the Pi through R10/R11. When the power falls away, the battery supply takes over through the combination of D1 and D2. C12 makes sure there is no dip, although you can calibrate the voltages such that there is only a drop of 10 mV or less, and the Pi is happy with that.
The use of the Schottky's have really proven themselves; neat, simple and effective (great idea Bud!)

Because I selected two 2700mAh Ni-MH cells, even with 80% capacity, they can power the Pi under normal operation (at 500mA) for more than 4 Hrs (2700mAH / 500mA * 80% = 4.3 Hrs), so we can elect to play UPS for a while. Now, in my case, when the power goes away, it means that the HVAC system is broken or has no power, so there is little gained by keeping the Pi running. It needs to stop issuing commands to the system anyway, so we might as well close shop.
The software decides that point in time, and starts the shutdown sequence. It first triggers the 555 timer, so the shutdown process cannot be interrupted by power glitches. Then it switches control of the PowerGate (Q1) from the GPIO channel through R9, to the 555 timer. When the 555 output changes state after 45 seconds, long enough for the shutdown sequence, the Pi is made powerless by turning off the PowerGate Q1. The Pi consumes only 100mA and the Hi-MH cells can keep that up for almost 20 Hrs (2700mAh / 110mA * 80% = 19.6 Hrs)

Here is the Python program that controls it all:

Code: Select all

#!/usr/bin/env python2.7

from time import time, sleep
import subprocess
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

PWR_GATE  = 23 # GPIO-23 : P1-16
PWR_TIMER = 24 # GPIO-24 : P1-18
PWR_SENSE = 22 # GPIO-22 : P1-15

UPS_MODE = 60.0 # seconds

GPIO.setup(PWR_GATE, GPIO.OUT) # Turn power on regardless of timer
GPIO.setup(PWR_TIMER, GPIO.OUT) # Trigger for the shutdown timer
GPIO.setup(PWR_SENSE, GPIO.IN) # Senses the loss of the supply from the HVAC

# Init
GPIO.output(PWR_GATE, GPIO.HIGH) # Gate is on, after init, Pi still gets power
GPIO.output(PWR_TIMER, GPIO.HIGH) # Shutdown timer.

def system_action(PWR_SENSE):
    print ('Loss of power detected on GPIO channel %s'%PWR_SENSE)
    sleep(0.5) # Let the voltage drop to ground level to avoid a false trigger
    # we can play UPS for a while before we perform the shutdown.
    # if there was a power glitch, the Pi continues
    # if the mains is out or the HVAC lost power, need to shutdown Pi too.
    t0 = time()
    while ((time() - t0) < UPS_MODE) and (GPIO.input(PWR_SENSE) == 0):
        print GPIO.input(PWR_SENSE), t0 - time()
        sleep(1) # check every second
    if GPIO.input(PWR_SENSE) == 1 :
        print ("Power came back on")
        return
    print ("Power still off -> shutdown sequence started")
    print ("Start timer")
    GPIO.output(PWR_TIMER, GPIO.LOW) # Toggle timer
    sleep(0.1) # 100 mS pulse
    GPIO.output(PWR_TIMER, GPIO.HIGH)
    # When the timer starts, it toggles the output of the 555.
    # Wait a moment, then release the PowerGate to let the 555 timer
    # control the power to the Pi.
    sleep (0.1) # Timer needs to have started, before we release the PowerGate
    print ("Release power gate")
    GPIO.output(PWR_GATE, GPIO.LOW)
    # Start the shutdown process
    print ("Shutdown sequence started")
    subprocess.call(['shutdown -h now "System shutdown due to power failure" &'], shell=True)


GPIO.add_event_detect(PWR_SENSE, GPIO.FALLING, callback=system_action, bouncetime=5000)
# setup the thread, detect a falling edge on a GPIO channel and debounce it with 5 Sec

# assume this is the main code...
try:
    while True:
        # do whatever
        # while "waiting" for power failure
        sleep (2)

except KeyboardInterrupt:
    GPIO.cleanup()       # clean up GPIO on CTRL+C exit
GPIO.cleanup()           # clean up GPIO on normal exit

The comments are such that it is easy to figure out what I did, and what needs to be done to change it to your particular needs.

So, here we have it... Well, I'm sorry to say, not really... :? .

There is still one small instance where the system will not work yet. If (make that a BIG IF), the power returns when the Pi has started the shutdown sequence, during those 45 seconds, Q2 cannot fire the 555 timer to start the booting process. The chances of this happening at this short interval are close to remote, but still. It can cause a locked-up system, not so nice when you're on another continent. This is something that initially caught me off guard, but I hoped that the use of the BCM Watchdog timer and the afterthought of adding D6 would save my day. After half a day spending time on Google and trying things out, I have to admit defeat for now. I cannot teach this Dog that trick. The darn dog needs to kiss the Pi awake while it's halted, and I don't know if and how that can be done. It works great for a hung program, but that's it I fear. So, I will be looking at a circuit, possibly around another 555 that will be triggered when the right conditions are met, such that the Pi can be rebooted again. Kind of a special watchdog for the Pi. :lol:

If any of you know the, or a answer, of have a better idea, please let us know. I'll be very grateful and willing to try that out.

Stay tuned though, ...we're almost there.

paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Controlled Shutdown at Power Failure

Sat Aug 17, 2013 5:27 am

After going through a few possibilities, I managed to find a solution for the last nagging problem. When power would return during the 45 second shutdown process, the Pi would Halt, lose power and there would be no trigger generated to wake it up again.
Here is the final schematic:
ShutdownPower V7 Schematic.png
ShutdownPower V7 Schematic.png (55.09 KiB) Viewed 13004 times
The circuit around IC2, a second 555 timer, solves the last remaining issue.
The 555 has been configured to produce a pulse of 500mS every 60 seconds. A kind of a hardware watchdog, since we can't use the Pi's own watchdog. It seems to be halted too...

The 555 sends this pulse to Q3 and that connects to P6, pin-1 on the Pi board. On the Pi PCB, this pin is pulled high by a 10K resistor to 3V3, and clamped by two diodes to the rail and ground, while going to the Run pin of the BMC2835. (Pin 1 is the bottom hole of P6 on the Pi just to the left of the HDMI connector) I soldered a jumper in it's place, and on the bottom of boards that sit on the P2 connector, there is a 2 pin socket, that connects the two. It also adds some more stability to my boards. Anyway, momentarily shortening pin 1 to pin 2, which is ground, sends a Halt signal to the Pi, and when it's halted, wakes it up.
Here is some more information about using P6: http://www.raspberrypi.org/phpBB3/viewt ... 37&t=48455)

The tricky bit is to only send out the wake-up call to the Pi when we want it, otherwise we'll send it to a quick halt.

I decided to use the reset pin of the 555 to control my new puppy dog, and that pin is held low by the combination of D8 and D9, another OR function, and Q5.

The combination of D8 and D9 will release the reset pin of the 555 through Q5 only at the very end of the shutdown window created by the other 555 timer. When there is no main power to the Pi at the end of the shutdown period, the PowerGate switches off and the Pi rests powerless until triggered by the normal start-up process. If power did return to the Pi during the shutdown window of 45 seconds, D6 will keep the PowerGate open, the dog is released and the Pi can respond to the barks of our puppy. During the normal boot process and the running of the Pi, D8, D9 and Q5 put a muzzle on the dog.

I have selected a 60 second period, because the Pi needs to reboot and the application program needs to turn the watchdog off, otherwise it will send the Pi into the Halt mode again. (no changes were required in the software) A period of 1 minute is safe. Should the Pi not respond the first time, it will continue to be woken by the barks of our new dog.

I will use a dual 555 timer in the final layout, but for now this will more easily show the two separate functions in relation to the previously shown diagrams. I did notice that the usual formula to calculate the timing pulses did not produce the right results for me, so even with the tolerances of R18, R17 and C15 in mind, I experimented with the values of R18 and R17 to get the pulse periods I wanted.

As far as I'm concerned, I will add the parts of the new dog to my experimental PCB and in a few weeks, when I'm back in the US, start to run the system with my new power supply. If everything is OK, I may move to a PCB layout, but I have to learn how to do that first. Should I make changes, or find something interesting to report I will update this post.

For now however, I'm done with this topic! Thanks for watching and even more for contributing, especially Tage and BudBennet ! I hope it's been useful. It certainly was for me, and I learned a lot in the process.

If you have comments or inputs, feel free...

Mjolinor
Posts: 2
Joined: Mon Sep 09, 2013 7:36 am

Re: Controlled Shutdown at Power Failure

Mon Sep 09, 2013 7:49 am

Lot of reading in this post and I think it's all a bit complicated. I made this to do the same thing:

Image

I keep making changes to it and currently I use just under 6 volt for the supply, there is no 7805 and I use a 4.8 volt nicad.

The Pi monitors P1 pin 12 with a bash script and if it goes low a shutdown is started.
The PIC is running a programme that monitors pin 2 and if it is high then it sends a low going pulse every 90 seconds out of pin 7. As there is a level problem between the Pi and the PIC this pulse is generated by changing the pin from input to output and back while it is set to 0, in this way no damage can be caused to the GPIO on the Pi because of the 5 volt PIC

What I need to do now is to stick a Mosfet where the 7805 is that is driven from the PIC so that power is removed form the Pi once it is shutdown, that way the nicad will last for years before it goes flat.

The problem I have right now is that I can find no way to know when a shutdown is complete, I had hoped that I could get a signal from the videocore as that is the last thing to shutdown but no luck so far.

dauhee
Posts: 59
Joined: Fri Sep 07, 2012 1:50 pm

Re: Controlled Shutdown at Power Failure

Wed Sep 11, 2013 7:30 pm

I would buy one of these boards!!!!!!!!!!!!!!!!!!!!!!!!!!!

I am using a lipo rider pro board to provide ups capability. I did a bit of soldering and can detect when battery is activated - I can then gracefully shutdown. Only problem is the RPi will trickle away the battery even when shutdown as you know. It also can't detect power again.

This is a graceful solution and I would gladly pay for it!

There is a UPiS product supposedly being released to market the last 5 months but nothing is materializing and have been watching this area with great interest.

Mjolinor
Posts: 2
Joined: Mon Sep 09, 2013 7:36 am

Re: Controlled Shutdown at Power Failure

Wed Sep 11, 2013 9:25 pm

I found a way to detect full shutdown but it isn't graceful.

The composite video out signal is there all the time until shutdown is complete so passing that through a low pass filter gives a constant DC offset of about 0.5 volts.

This can be detected by the PIC I am using because it has 2 analogue comparator inputs and that means that the PIC can control a Mosfet in series with the supply so it's possible to turn off the Raspi power completely.

I intend to implement that when I get a round tuit.

paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Controlled Shutdown at Power Failure

Wed Sep 11, 2013 10:54 pm

Hi dauhee,

I'm glad you like it. In my case, it has been running for several weeks now, and works perfectly.

I don't have a board developed, because I have not learned how to do that. It's been too many decades ago since I did that, so I have to learn it all over again with the new parts and the new tools.

In my case, I made a prototype board, and that will have to do for the time being. In a week or so, I'll have the thermostat finished and tested with all the new components and security features, and I will post some photographs of the system. By that time, when all the bugs are out, I will also publish the final Eagle schematics and a parts list, so the experienced among us can have a field day producing a board for those who are interested.

User avatar
PiModules
Posts: 96
Joined: Sun Mar 03, 2013 9:20 pm
Location: Athens -Greece
Contact: Website

Re: Controlled Shutdown at Power Failure

Thu Sep 12, 2013 6:15 pm

Dear Friend,

We sent our boards to distributors, already. Next week, they should list them on the webshop. Start from the https://www.modmypi.com/.
We released this board late due to extensively test we have done, in various powering conditions, temperatures, loads changing, extra boards, etc. In other words we tested it professionally. We do not release boards if we are not sure for 110 % that everything is working perfectly. We are serious company and only if everything is as specified product is released to the market. As you have done your own designs you can imagine how many problems it can generate. We solve all of them and everything is working perfectly. In addition we support all other features described below. Very soon we will release also version UPiS Professional with many add-on features. But, first of all buy one of the 2 available the UPiS Basic and UPiS Advanced and comment it on the net. We are open for any comments. We are an EU company, our manufacturer are in EU, therefore quality is the first goal. The implemented functionality are here below, manual is about 70 pages !!!!.

System Overview
Introduction
The UPiS is an Advanced RaspberryPi® Powering add-on Module that incorporates except of the powering functionality a plenty of additional features. It is equipped with LIPO battery 1200/2600 mAh as also with buck/boost switching power converter. There is no need for any additional cabling, as a smart current measurement system continuously checks powering voltage and current consumption, and based on it, when the cable power is absent automatically switches to the battery source. During battery powering process it keeps checking power consumption and when cable power is available again, it is switching to it automatically, and then the battery source off.
Applications
The UPiS as an add-on Module is addressed to all users that need a power back-up for the applications build based on the Raspberry Pi. There are plenty of applications that can be supported but the UPiS and starts from a simple power backup for the RPI based fan less server; going through embedded applications requiring extended powering inputs like car computers, robotic; and ending on a solar powered applications. The list of possibly applications where UPiS can be used is same wide as the Raspberry Pi itself. Due to additional features listed and described below UPiS is solving most of the common requirements that users met during embedded applications build up.
Features
Features of the UPiS Module are listed below and contain powering functionalities, I/O functionalities, RTC functionalities, etc. There are:
• Supervised and Protected Powering from a various cable sources
o RaspberryPi ® micro USB (5 VDC)
o Additional micro USB (5VDC)
o Extended External Powering Input (7 VDC – 18 VDC)

• Battery Power Backup on each cable powering source (including original Raspberry PI micro USB) – the UPS feature
• Onboard Rechargeable LiPO Battery (1150 mAh or 2600 mAh)
• Intelligent Automatic LiPO Battery Charger
• Additional Protected 5 VDC 140 mA output for user applications
• RaspberryPi ® Hardware ON/OFF Switch
• Embedded on Board Analog Temperature Sensor accessible via RS232 interface
• Onboard Protected 1-wire interface
• Onboard Protected I/O pin
• Onboard True 12 V RS232 interface to the external world
• Onboard True USB interface (RS232 – USB Bridge)
• Onboard Normally Open Relay
• Programmable time RaspberryPi ® File Safe Shutdown button
• Embedded Emulated RTC (Real Time Clock) accessible via I2C
• Full monitoring over all UPiS Parameters via RS232 port:
o Current Consumption
o Voltage on each Power source
o System Temperature
o Battery Level
o Powering source

• Programmable Triggers on various events i.e. powering change, low battery, high temperature, digital input pin change etc
• Time programmable RaspberryPi power ON/OFF based on RTC
• XTEA cryptographic Customer Software Protection
• Scripting Language

System Basics
UPiS Versions
The UPiS Module is 100% Plug and Play; there is no need to setup anything. There is no need even to change the original micro USB power connection plugged to your Raspberry Pi if you need to keep the old cabling as it was. You will plug-in the UPiS Module to the P1 connector on the top of your RaspberryPi® and just use it. UPiS Module solves all common powering problems and in parallel offering battery backup and plenty of additional features. There are two versions available UPiS Basic and UPiS Advanced, each one could be configured on order with top-end or stackable P1 connector.

Cable Powering Inputs
The UPiS is designed to offer automatic battery back-up to the Raspberry Pi supplied from the following cable powering inputs:
o RaspberryPi ® micro USB (5 VDC)
o Additional micro USB (5VDC)
o Extended External Powering Input (7 VDC – 18 VDC)
However, decision when battery backup should be activated is made according of the powering status of the 5V Pin on the P1 connector.
Absence of power or more exact falling edge of power within 300 uS automatically activates the battery back-up powering and prevents the Raspberry Pi from unexpected power shutdown. The activation time of battery back-up power is extremely fast and is executed within 100 uS. In addition a large tantalum capacitor is supplying the Raspberry Pi system during this time, in order to avoid unexpected power losses spikes. Activation of the battery backup is executed when 5V on the P1 connector goes down more than 150mV from the mean values. The mean value is continuously monitoring and calculated value represents the voltage of the last 2 seconds. Due to various powering conditions of the Raspberry Pi the approach of dynamic power monitoring has been analyzed and decided as the best possible. In addition a static threshold is active and when powering is smaller than it is activated.

Yes, I know, we are late, but better late and perfect working that faster but with a bugs. You need device to in order to use it. So, Your satisfaction is our profits. It is simple.
So, wait until next week.

My warmest Regards
Pi Modules
http://www.pimodules.com


dauhee wrote:I would buy one of these boards!!!!!!!!!!!!!!!!!!!!!!!!!!!

I am using a lipo rider pro board to provide ups capability. I did a bit of soldering and can detect when battery is activated - I can then gracefully shutdown. Only problem is the RPi will trickle away the battery even when shutdown as you know. It also can't detect power again.

This is a graceful solution and I would gladly pay for it!

There is a UPiS product supposedly being released to market the last 5 months but nothing is materializing and have been watching this area with great interest.

paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Controlled Shutdown at Power Failure

Fri Oct 04, 2013 6:46 pm

After all the work that contributors put in, I though it was only fair to give you all an update on where we are at this moment.

We arrived at our second home about a month ago, and I've been working to finalize the hardware and software to replace my version 1 hardware and software with version 2 hardware and software, and this included the Power Supply.

While implementing and integrating the system, I had, or wanted, to make some adjustments to both the circuit and the code so below are the results.
UPS Power Board.png
UPS Power Board.png (51.71 KiB) Viewed 12352 times
On this separate board, that plugs on top of the Pi, you see the connections as they go to the Pi.
(there is another board in-between, but you'll get the idea)
Pi Logic Board.png
Pi Logic Board.png (19.26 KiB) Viewed 12352 times
The code is made-up in a few parts. Here is a part of the import section with the definitions:

Code: Select all

import os
import subprocess
import RPi.GPIO as GPIO
from threading import Thread
import datetime
from time import time, sleep, gmtime, strftime, localtime
Here is a GLOBAL variable:

Code: Select all

UPS_MODE = 10.0         # UPS provides power for a minimum of x seconds
The GPIO channel definition section:

Code: Select all

# GPIO Channels
HVAC_Is_Alive_P = 27    # input
PWR_Sense_P = 17        # input
PWR_Timer_P = 25        # output
PWR_Gate_P = 7          # output
FAN_Is_Alive_P = 11     # input
FAN_P = 8               # output
Fail_Safe_P = 22        # output
Reset_P = 9             # input
System_Status_P = 18    # output
HVAC_P = 23             # output
Heat_Cool_P = 24        # output
# W-1 interface = 4     # input
Here is a part of the "init" function, where I setup all the interface stuff.

Code: Select all

    if DEBUG: GPIO.setwarnings(True)
    else: GPIO.setwarnings(False)

    # Use the Raspberry the BCM pins
    GPIO.setmode(GPIO.BCM)

    # Power Supply setup, the input action is defined below
    GPIO.setup(PWR_Sense_P, GPIO.IN)
    #
    # The following 2 ports must be set within the Shutdown_Timer period of 45 seconds
    # otherwise the HW Watch_Dog on the UPS board will put the PI to sleep.
    GPIO.setup(PWR_Timer_P, GPIO.OUT, initial=GPIO.HIGH)
    GPIO.setup(PWR_Gate_P, GPIO.OUT, initial=GPIO.HIGH)

     # system status LED setup
    GPIO.setup(System_Status_P, GPIO.OUT, pull_up_down=GPIO.PUD_UP)   # White LED
    sys_stat = GPIO.PWM(System_Status_P, 0.5) # PMW frequency of 0.5 Hz
    sys_stat.start(0) # start the PWM, but with a duty cycle of 0, the LED is on during the boot process

    # --- this needs to be at the end of all the port definitions, otherwise the edge detections don't work!
    # setup the event to detect a falling edge on the main power sense input
    GPIO.add_event_detect(PWR_Sense_P, GPIO.FALLING)
    # setup the event detection thread for the reset button
    GPIO.add_event_detect(Reset_P, GPIO.FALLING, callback=reset_action, bouncetime=1000)

And finally the actual function:

Code: Select all

def power_action():
    '''
    This function controls the Power Supply.
    If a loss of main power is detected, the supply acts as a UPS to see if it
    only was a glitch, if not, the Pi is shutdown.
    The power supply will automatically switch on the Pi if main power returns, or
    if the Pi has been put to sleep, it re-awakens the Pi again.
    '''
    write_log("warning", "Loss of main power detected")
    mail_alarm("Loss of main power detected")
    sleep(3) # Let the voltage drop completely
    # we can play UPS for a while before we perform the shutdown.
    # if there was a power glitch, we'll let the Pi continue
    # if the mains is really out or the HVAC lost power, we need to shutdown the Pi too.
    t0 = time()
    while ((time() - t0) < UPS_MODE) and (GPIO.input(PWR_Sense_P) == 0): # play UPS
#        print GPIO.input(PWR_Sense_P), t0 - time()
        write_log("test", "timer : "+ str(t0-time()))
        sleep(1) # check every second

    if GPIO.input(PWR_Sense_P) == 1 :
        write_log("warning", "Power came back on during UPS period")
        sleep(2) # let the system settle a bit before we restart BangBang
        return
    write_log("warning", "Power still off -> shutdown starting")
    # show the user
    System_Status(ON, 10) # start flashing of status LED with 10 Hz
    # start the shutdown process
    stop_HVAC() # turn off the HVAC system (heating or cooling or the fan)
    #
    write_log("warning", "Start UPS timer")
    GPIO.output(PWR_Timer_P, GPIO.LOW) # Toggle UPS timer with a negative edge
    sleep(0.1) # 100 mSec pulse
    GPIO.output(PWR_Timer_P, GPIO.HIGH)
    # Wait a moment, then release the power gate of the UPS to let the 555 timer
    # control the power to the Pi.
    write_log("warning", "Release power gate")
    GPIO.output(PWR_Gate_P, GPIO.LOW)
    # Start the shutdown process
    write_log("warning", "Pi Shutdown sequence started")
    mail_alarm("Pi Shutdown sequence started due to power failure")
    subprocess.call(['shutdown -hP now "System shutdown due to power failure" &'], shell=True)
    # when the Pi shutdown period has started, it cannot be stopped. If the power comes back on
    # in this period, the Pi will still be halted, but the hardware watchdog will re-wake the Pi
    sleep(20) # wait for the shutdown to happen

If you followed the earlier version, you will have noticed that I'm no longer using a thread. The reason is that after a Debian update, I was getting double hits, irregardless of the hardware and/or software de-bouncing efforts. This actually works better because I have more control over the sequential execution of the code.

Here is a picture of the Power Supply board:
011.jpg
011.jpg (59.36 KiB) Viewed 12352 times
If you are interested in the actual thermostat project, look here: http://www.raspberrypi.org/phpBB3/viewt ... 37&t=46889
Last edited by paulv on Sat Oct 05, 2013 3:10 am, edited 2 times in total.

paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Controlled Shutdown at Power Failure

Fri Oct 04, 2013 6:51 pm

Here is a picture of the Power Supply in the closet behind the thermostat.
IMG_0103.jpg
IMG_0103.jpg (34.72 KiB) Viewed 12351 times
The batteries are mounted in the cover, and so are the switch and the LED.

And here is the new version of the thermostat, next to the "old" one that still can be made functional.
IMG_0107.jpg
IMG_0107.jpg (35.99 KiB) Viewed 12351 times
Thank you all for following this thread and also for your comments and contributions.

synnoack
Posts: 1
Joined: Tue Oct 08, 2013 12:01 pm

Re: Controlled Shutdown at Power Failure

Tue Oct 08, 2013 12:09 pm

Any possibility of getting a parts list for this build. This looks great!

paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Controlled Shutdown at Power Failure

Tue Oct 08, 2013 1:58 pm

Hmm, I could do that although I did not select most of the parts in Eagle to make a layout, just wanted to create a schematic so it will take some work.

I also want to add a first stage convertor for the AC power conversion for safety. The 5V regulator board that I use has a maximum input voltage of 40V. The 24VAC could, when there is no load, go above that level, so I am going to add an LM317P to keep the maximum input voltage at 36V. When that has been build and tested, I'll start on the parts list.

paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Controlled Shutdown at Power Failure

Wed Oct 09, 2013 3:42 pm

After measuring the 24VAC coming from the HVAC system, loaded and unloaded, I decided that I don't need the extra stage to protect the convertor board. The DC input voltage stays below 37.4V. According to the specs, the convertor board has a max input of 45V, so no reason for concern.

Here is the parts list:

Code: Select all

Part		Value		
				
C1		100uF	6V3	
C2		220uF	6V3 low ESR (Yageo)	
C3		10nF		
C4		100nF		
C5		100nF		
C6		10nF		
C7		100uF	6V3	
C8		470nF		
C9		10nF		
C10		100uF	6V3	
C11		470nF		
C12		1500uF	10V	
C13		470nF		
C14		100nF		
C15		100uF	6V3	
D1		1N5819	Schottkey	
D2		1N5819	Schottkey	
D3		1N4004		
D4		1N4148		
D5		1N4148		
D6		1N4148		
D7		1N4148		
D8		1N4148		
D9		1N4148		
G1		NI-MH	SANYO 2700mAHr	
G2		NI-MH	SANYO 2700mAHr	
IC1		NE555	st-microelectronics	
IC2		NE555	st-microelectronics	
J1		1X2-3.5MM	Adafruit	
J2		1X2-3.5MM	Adafruit	
J4		1X2-5MM	Adafruit	
J5		1X2-5MM	Adafruit	
L1		10uH	Coilcraft DO3316-103	
LED1		RED		
Q1		Si3443DV	FET	
Q2		BS170	FET TO-92	
Q3		BS170	FET TO-92	
Q4		BS170	FET TO-92	
Q5		BS170	FET TO-92	
R1		22K	1/8 Watt	
R2		10K	1/8 Watt	
R3		56 Ohm	1/8 Watt	
R4		10K	1/8 Watt	
R5		1K	1/8 Watt	
R6		10K	1/8 Watt	
R7		1K	1/8 Watt	
R8		100K	1/8 Watt	
R9		1K	1/8 Watt	
R10		10K	1/8 Watt	
R11		15K	1/8 Watt	
R12		10K	1/8 Watt	
R13		390K	1/8 Watt	
R14		180K	1/8 Watt	
R15		470K	1/8 Watt	
R16		47K	1/8 Watt	
R17		820K	1/8 Watt	
R18		4K7	1/8 Watt	
R19		10K	1/8 Watt	
R20		10K	1/8 Watt	
R21		10K	1/8 Watt	
R22		2K2	1/8 Watt	
S1		Slide Switch		
U$1		LT1302-5	Linear Technology (DIL)	
Battery holder 2x AA				
Bridge		DF005M	DIL package	
Fuse		125V/1,25A	Littlefuse	Mouser 39511250440
The DC-DC convertor board I got from eBay, here is the schematic:
5V4 Supply Board.png
5V4 Supply Board.png (30.95 KiB) Viewed 12236 times
On another board, I have the bridge rectifier and the fuse. I also use a slide switch to remove the 24VAC from the circuit, to let the Pi power down (= power off) when I want it. You'll probably want to implement that as well. (for details, go to the link to the thermostat project. It's listed above somewhere)

The fuse, the 555's and the LT1302-5 are in sockets. Way up in the post you can see a picture of how I mounted the Si3443DV FET.

If someone is willing to create a board layout, they can contact me and I can send the Eagle (6.4.0) schematics by email.

Enjoy!

konavan
Posts: 4
Joined: Thu Dec 19, 2013 10:24 pm

Re: Controlled Shutdown at Power Failure

Thu Dec 19, 2013 10:29 pm

BudBennett, that design of the Plan B looks very nice. have you anything to report since this post? are you still using it? any failures?

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Controlled Shutdown at Power Failure

Fri Dec 20, 2013 3:58 pm

Plan B is working well. It has gone through several short power failures and kept the system up and running as designed. The only problem I have with it is that it doesn't protect against hot plugging something into the USB port - the Pi resets and I have to remove power and restart after the supercaps discharge.

I revisited Plan A and have it working now. It is more robust in that it will charge the supercaps from zero volts in a reasonably short period of time (20 minutes) and I don't have to worry much about overheating while it is doing that. I added a RTC since I have seen issues with the system riding through a power fault but the wifi router doesn't - the system time gets screwed up somehow. The RTC gets backup power from a 3.3V regulator that draws only 1uA. Here's the schematic:
HoldUp+RTC.png
Plan A final circuit with RTC.
HoldUp+RTC.png (53.11 KiB) Viewed 11623 times
The biggest detriment with this circuit is that it waits 10 seconds before applying power to the Pi. A small inconvenience.

I also found a 5VDC adapter that provides the necessary 5.2V at the input. I have purchased two of these and they both output 5.17-5.2VDC. You can get the adapter at Amazon: http://www.amazon.com/gp/product/B002FA ... UTF8&psc=1

Bud.

konavan
Posts: 4
Joined: Thu Dec 19, 2013 10:24 pm

Re: Controlled Shutdown at Power Failure

Fri Dec 20, 2013 4:29 pm

Thanks for posting Bud, that looks excellent. can you tell me about the supercaps you are now/still using? what is the performance? also, tell me about the powerfail signal. I assume you have this connected to a GPIO pin configured with pull-up? thanks in advance for my questions.

-Van

BudBennett
Posts: 89
Joined: Fri May 17, 2013 2:45 pm
Location: Westcliffe, Colorado, USA

Re: Controlled Shutdown at Power Failure

Fri Dec 20, 2013 5:49 pm

I don't know what you mean by performance, but I'll give a short summary. I bought two sets of D-cell sized supercaps from Digikey. The first set (of 2) was Maxwell 350F, 2.7V max rating, 3.2mOhm series resistance: http://www.digikey.com/product-detail/e ... ND/3079280 They match to better than 5%. They are used in the Plan B circuit.

The second set was Cooper 400F, 2.7V, 3.2mOhm resistance: http://www.digikey.com/product-search/e ... maction=on They are used in the Plan A circuit. I switched from the Maxwells because they were easier to solder and mount. The match is poorer: ~10%. Since this circuit has an RTC I was concerned about the self discharge. The literature paints a pretty bleak picture for supercap self-discharge, but I have measured the rate of voltage loss over time (days) and it is consistent with the bias current of the entire circuit (21uA). I see no significant self-discharge current for this particular pair of supercaps.

Yes, the GPIO is configured as a pull-up:

Code: Select all

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_UP)
I should add this disclaimer. These circuit are mostly for "fun". There are most probably better/cheaper implementations out there (Paulv ended up with a pretty good one). It also doesn't use the supercaps very efficiently since only 250mV of voltage is taken off the stack before it reaches the cutoff point. Their primary advantage is that they should last more than 10 years at room temperature without any maintenance at all.

Bud.

konavan
Posts: 4
Joined: Thu Dec 19, 2013 10:24 pm

Re: Controlled Shutdown at Power Failure

Fri Dec 20, 2013 6:05 pm

Bud, sorry my question was not clear. by performance I was curious as to the run time you are experiencing after power fail event. I am interested in cost savings of the supercaps if I need only say twice the shutdown time (1.5 minutes?) and you are getting many more minutes.

Return to “Automation, sensing and robotics”