Author Topic: Latching push button circuit, need help with some things...  (Read 19122 times)

0 Members and 1 Guest are viewing this topic.

Offline davekraTopic starter

  • Contributor
  • Posts: 33
Re: Latching push button circuit, need help with some things...
« Reply #25 on: September 18, 2015, 05:30:03 pm »
No worries, all ideas are welcome.  I'm very open to scrapping what's been done and head off in another direction but not to diminish the help already provided.

I hadn't been thinking of a PIC because I assumed the route I was going would consume less power.
Having a quick search for nanowatt microcontrollers shows many options that are measured in nA instead of uA.

I'm even more of a beginner when it comes to microcontrollers.  My first use of one was to control the backlight of my carpc.  I used a PICaxe.
Then I got a few Arduino Nano's to build transmitter modules for the ProtoX quadcopter.
All this was with copious direction from helpful people like you.

If we were to do this with a micro would you guys be able to help with selection?

In simple terms, we'd have the micro, hall sensor and a FET?  We'd want an N-channel FET?  Because it's on when held high and in the on state I'm not too concerned about the circuits power consumption (It's going to be low enough by default I'm guessing).
The voltage requirements of the device will exceed the maximums of the components so that again is a concern as you mention.
I hate to come right out and ask but could someone spoon feed me on this new direction?

Many many thanks,
davidk
« Last Edit: September 18, 2015, 06:29:31 pm by davekra »
 

Offline KL27x

  • Super Contributor
  • ***
  • Posts: 4099
  • Country: us
Re: Latching push button circuit, need help with some things...
« Reply #26 on: September 18, 2015, 07:56:05 pm »
Quote
We'd want an N-channel FET?  Because it's on when held high and in the on state I'm not too concerned about the circuits power consumption
AFAIK, this doesn't necessarily matter. Hi rail, low rail, doesn't matter where the gate of the FET is sitting.

For switching a voltage greater than Vdd of the control circuit, things slightly more messy, though. There are some minor pros and cons to switching hi or lo side on the final switch, regarding drive and pcb layout. But because this is a simple manual toggle, not high frequency, and you generally can't stick a magnet on a plane while it's flying, you shouldn't need anything fancy to drive the FET.

I would suggest two stages, anyhow. A PFET for the final switch and an NFET or NPN tranny for the drive, because this conveniently solves the issue of where the rail to be switched is greater in voltage than the control circuitry Vdd while keeping a single ground plane. A simple pullup on the PFET gate would be used to turn it off, drawing no current while off. When switched on, that bit of current would be tacked on to your energy bill.

As for the micro, well... hmm. Even though this is maybe 30 lines of assembly code, it's quite a long journey by spoon feeding. This is lots of RTFM for the specific micro and probably some trial and error, even for someone with experience, and most definitely a good chuck of time optimizing with test equipment. That's after sourcing the parts and reading those datasheets.

PICAXE or ARDUINO probably can't pull off the "full monty" with the pulsing/reading of the hall effect while asleep. PICAXE for sure, no. ARDUINO might be able to do a simple external wakeup, if you're ok with leaving the hall effect sensor on all the time. You mentioned quite a low draw on this part.

For spoon feeding
1. Use a micro, at all... PICAXE or ARDUINO perhaps.
2. Use a bare micro, figuring out use the compiler/IDE, learning how to configure all the peripherals and whatnot. This is 90% of the uphill battle.
3. Play with the WDT and/or for simpler version just sleep and I/O wakeup.

Or hire someone like me to make this for you. :)

edit: Actually, if you're in it for the learning process, for the long haul, and if you happen to be interested in PIC micros, I can recommend you go to Microchip website and download their "low pin count tutorial" and play with this starter example code and work through the lessons. You can view the schematic for the dev board and make your own pcb or just breadboard it. Or you can buy that, too.

In addition to the free stuff you can find on the web, I can also recommend Googlium PIC tutorials if you are interested in using any PIC assembly. I have purchased more than a few of them, and they are well written and easy to follow. I learned a few very useful tricks about using the MPLAB IDE through these tutorials. The writer is very experienced. If I had known what I know now, I would have probably started here and saved a lot of headaches I ran into down the road by using less practical fee tutorials and even physical ($$) books (I think Mike Predco probably forgot more than I know, but unfortunately, he forgot a lot of important things for a beginner). By the time I found these, I had already learned most of the content the PAINFUL way. These Googlium tutorials are hands down the best, most practical, most comprehensive I have seen for learning bare PIC assembly. You can probably find a free torrent somewhere, but don't do that. These tutorials are a bargain, already, and the writer obviously spent years thinking them through and laying them out.
 

 
« Last Edit: September 18, 2015, 09:00:47 pm by KL27x »
 

Offline C

  • Super Contributor
  • ***
  • Posts: 1346
  • Country: us
Re: Latching push button circuit, need help with some things...
« Reply #27 on: September 18, 2015, 08:17:55 pm »
With my dmm I'm measuring a max of .4mA through the switch.
How do you measure a short time current with a DMM?
Switches bounce when closing, to see this you need a scope. The current spike is in the transition of what is seen on a scope.

A magnet reed switch has all kind of properties. Being sensitive to very low magnetic fields is not normally one of the properties.

Some hall sensors are used as a compass. Could be a problem or not.

If you look at the properties of the last P channel fet you were using as a power switch you will see that the gate has limits, X to start turning on but do not exceed Y voltage to gate. So for higher battery voltages, your circuit needs to prevent this from happening or you have to lower the max battery voltage. The source to drain also has limits.

When you use a N channel fet to control your positive rail, the gate how needs to go higher then the positive rail. A gate source of 8 to 12 volts is common.

If you look at Dave's video
He has a working circuit, what are the limits?
2N3904 Vceo Collector-Emitter Voltage  of 40Volts is one
The P channel max gate voltage is lower here so it would set max battery voltage.
What is the off state current?
Two off 2n3904's and a cap.

The other circuits have the same limits of max gate voltage setting the input voltage limits.

Your circuit adds a lot of parts compared to Hero999, What did you gain, what problems added? How does it work different from what you have?
What is the off state current?

I would suggest that you build both Dave's and Herro999's circuits and getting them the function properly with your reed switch. Add a Series resistor 40 ohms or more is series with the reed.

Then take each change you are thinking of and block out the needed changes to make each of the two circuits function.

Unless you can find a hull switch that can work with higher then max battery voltage, you have to add a voltage regulator. A voltage regulator needs some current to operate so this change would increase off current. You have to do this properly or destroy parts.

Quote
I'm even more of a beginner when it comes to microcontrollers.
This suggests to me that this would be a better change for a later revision.
This has some advantages but most come from being great at programming.
You could use a hull sensor in place of a hull switch but this requires better programming.
You could sleep at low power most of time, again more good programming.

In place of a hull switch, you could use a light sensor.

Build something and use it while you are working on a better version.

C



 

Offline davekraTopic starter

  • Contributor
  • Posts: 33
Re: Latching push button circuit, need help with some things...
« Reply #28 on: September 19, 2015, 03:24:48 am »
I'm sorry, spoon feeding is more with component selection and tweaking the circuit.  Didn't mean to sound so desperate.

With renewed enthusiasm I ripped up everything and started with a spare PICaxe 14m2.  Using the examples in the docs to connect the hall sensor, then took the dual FET from the old circuit and connected it to one of the outputs with a pull up resistor on the P-channel FET.
I put a few LED's on the controllers output and both FET's drains.
I'll try to put together a circuit diagram on what I have so far.  A week of vacation is going to interrupt things next week.

The code was pretty simple but it took a while to get the for:next and do stuff in the right order.
https://youtu.be/QoPCXNjV6Gg

It's working as planned:
Apply power and its ON.
With it on, a quick swipe across the sensor does nothing.
Hold the magnet over the sensor for .5 seconds and it turns off.  Continue to hold the magnet over the sensor does not change the off state.
Remove the magnet and swipe it over the sensor and it turns on.  If the magnet is held over the sensor the on state doesn't change

The code may not be the most efficient and there aren't any power saving things but it gets me started.
Code: [Select]
high b.1
let b3=1
main:
if b3=1 and pinb.2=1 then goto main
if b3=0 and pinb.2=0 then goto onn
if b3=1 and pinb.2=0 then goto waitn
goto main
waitn:
for w1=1 to 400
if b3=1 and pinb.2!=0 then goto main
next
offf:
low b.1:let b3=0
if pinb.2=0 then goto offf
goto main
onn:
high b.1:let b3=1
        if pinb.2=0 then goto onn
goto main

As it is right now the current draw fluctuates around .6 and 1mA in the off state. 
With the hall sensor  needing power to work it will need to be powered all the time.  The spec sheet says 1.8uA in sleep mode.
I've yet to test the voltage regulator and how much current it draws.  The voltage limits for the hall are 2.2v - 5v. 
Your right, of course, about measuring spikes with a DMM with the old circuit.

I'm in this for the long haul.  I really enjoy doing this stuff.  If I wanted I could buy one of these ready made for about $30. For what I've spent so far I could have bought three of them.  I've been playing with using the toner transfer process too.
It gets overwhelming looking through Digikey with the thousands of parts.  Getting advice on what to look for really helps narrow things down.

Thanks guys,
davidk

« Last Edit: September 19, 2015, 03:29:56 am by davekra »
 

Offline davekraTopic starter

  • Contributor
  • Posts: 33
Re: Latching push button circuit, need help with some things...
« Reply #29 on: September 19, 2015, 05:10:32 am »
Searching Digikey I found this microcontroller
PIC10F202T-I/OT
http://ww1.microchip.com/downloads/en/DeviceDoc/40001239F.pdf
It's got 3 I/O pins which is enough and currents are measured in uA.  If I'm reading the datasheet correct the WDT current is about 1uA. 
This looks promising. 

Now I've got to look over those Googlium tutorials and figure out how to program this.
The PICaxe are easy to program.  If I'm correct, they already have a bootloader on them and can be programmed via a simple serial port.
I've bricked a couple Arduino by using an ISP (I think).  Reading on the problem if I could figure out the fuses or the the right clock speed I could make them work.
I've not successfully programmed a bare chip except for the PICaxe.

Fun stuff!
davidk
 

Offline C

  • Super Contributor
  • ***
  • Posts: 1346
  • Country: us
Re: Latching push button circuit, need help with some things...
« Reply #30 on: September 19, 2015, 06:20:42 am »
Ok got a micro running.

Think about off and off sleep
Do you really need to be fast?
If you have to hold magnet for 5 sec then
waking up once a second could cause holding for 5-6 sec.
The less you wake  up the more power saved.

Also if the hull sensor uses a lot of power you could use one of the micro's I/O pins to turn off power to hull. May need to wait a time for hull to be operational doing this.

Note that even with a scope you can have trouble seeing things. I have found that if think of extremes  while looking at a part you think of something you first missed. If that cap was 100,000 mf you would think of time and high current and worry. Still happens with small cap, just less and smaller.
A 1000 feet of wire gets you thinking of resistance, time, signal loss, signal echo and other things. A motor drive could be ok with a few inches of wire connecting motor, if it's 25 feet it's a different game.
With your micro, every thing takes time.

C
 

Offline KL27x

  • Super Contributor
  • ***
  • Posts: 4099
  • Country: us
Re: Latching push button circuit, need help with some things...
« Reply #31 on: September 19, 2015, 08:22:10 am »
Congrats on the circuit. And good luck with the next step.

I quickly tired of PICAXE, but I spent an embarrassingly long time figuring out my first PIC. In addition to the AWESOME Googlium tutorials, I suggest you get, say, a 12F508, because you can use this with the Microchip Low Pin Count Demo/Lessons and the Googlium tutorials for the BASELINE pic family, which is the easiest place to start. Scratch that... maybe use a 12F629 and start with the Midrange tutorials, because the 508 has a stupid osccal issue and no EEPROM to play with. You're not skipping ahead too much to start with Midrange.

So you will also need a programmer to use bare PICs. I suggest a PICKit2, because it is simple software and very reliable. And to use the free assembler, I suggest you use MPLAP IDE 8.xxx. Not MPLAB X IDE, which did not exist when the Googlium tutorials were written.

You will spend a long time just finding and installing all the software and figuring out how to begin to use it. Pretty painful road. Enjoy. :)
« Last Edit: September 19, 2015, 08:26:51 am by KL27x »
 

Offline Cliff Matthews

  • Supporter
  • ****
  • Posts: 1910
  • Country: ca
    • General Repair and Support
Re: Latching push button circuit, need help with some things...
« Reply #32 on: September 19, 2015, 02:04:59 pm »
This is catchy.. I got a damaged Pickit3 and fixed it a while ago, but still kept playing with AVR's. On persistence of forum posters hailing the virtues of PIC and Googlium, I bought-in.
And it didn't break the bank (PIC and mini dev board below were $6, and $20 CDN for the whole tutor pack). My journey begins - Thanks guys!
 

Offline davekraTopic starter

  • Contributor
  • Posts: 33
Re: Latching push button circuit, need help with some things...
« Reply #33 on: September 28, 2015, 12:30:54 pm »
I've started reading the Gooligum tutorials and find them quite good.  It will give a good understanding on how these little buggers operate.

I've also been searching for low power ideas.  One I came across has the hall sensor powered by an output of the microcontroller.
The controller is asleep most of the time but wakes up every so often, powers up the hall sensor, reads it then goes back to sleep.
Powering the sensor from the controller was a lightbulb moment.  The only thing drawing power when off will be the microcontroller and that should be in the nano-amps.

The only thing I'm missing now is regulated power.  All the examples I'm finding talking about low power are using a battery with voltages within the controllers limits.
I need something to regulate 3 - 12 volts but draw next to nothing.  The 2.5v regulator I have draws 100uA with nothing connected.
It does have an enable pin the controller could use to shut it down but that would be its last action as there would be no power to wake up with.

In sleep mode the controller would be waking up every 1/2 second just long enough to read the sensor. 
My simple thinking wonders if a capacitor could be used on the output of the regulator to sustain the controller in sleep and provide enough to turn the regulator on when it wakes up? 

Are there other ways I'm missing to provide a lower voltage than the battery and not consume more than 1 or 2 uA?

Thanks guys,
davidk
 

Offline KL27x

  • Super Contributor
  • ***
  • Posts: 4099
  • Country: us
Re: Latching push button circuit, need help with some things...
« Reply #34 on: September 28, 2015, 07:17:27 pm »
Quote
I've also been searching for low power ideas.  One I came across has the hall sensor powered by an output of the microcontroller.
The controller is asleep most of the time but wakes up every so often, powers up the hall sensor, reads it then goes back to sleep.
That's a great idea. I hope you didn't have to search too hard.   :phew:

Quote
The only thing I'm missing now is regulated power.  All the examples I'm finding talking about low power are using a battery with voltages within the controllers limits.
I need something to regulate 3 - 12 volts but draw next to nothing.  The 2.5v regulator I have draws 100uA with nothing connected.
It does have an enable pin the controller could use to shut it down but that would be its last action as there would be no power to wake up with.
I picture a very small shunt regulator. E.g. Vbat>>series resistor >>Vdd>> 5.1V Zener >> ground. And a good size filter cap that would reach 90% charge by the time the micro wakes up for the next cycle, maybe on the order of 10-100uF. Enough power for the hall effect and to switch a digital output pin and charge a FET gate without dropping VDD too much. Maybe even have the PIC go back to sleep for a cycle before switching the FET, so it doesn't power the hall effect and switch the small signal FET in the same cycle. Most 8 bit PICs will run from 5 V all the way down to 2.5V, so you have some leeway, there. With a very high impedance power source as this, I would even be curious to try pushing the peak up to 5.5V. Get the firmware working as intended and optimized, then start choking off the regulator with series resistance to see what you end up with at the point of brown-out under all operating conditions.  Then take your minimums and double or triple the current and the caps. If you can smooth out the power requirements enough and be able to handle some dips on the line, the shunt could theoretically be just a fail safe, with zero shunt current flowing under normal circumstances (at least for a specific Vbat). The simple series resistor and filter cap would act as an unregulated buck converter, with the power consumption carefully matched. The zener would be there to handle varying Vbat.

The game would be to see how tiny a straw your little micro can breathe through, after slowing down its metabolism as low as possible and spreading out surge requirements to avoid too fast/deep of a ripple on the line.

*Edit Hmm. The problem with a shunt is where Vsupply approaches Vdd. To account for this, you have to "open the flood gates" a bit, which will toast the efficiency at higher Vsupply. So to cover the entire range you're looking at, you might be best off with a buck converter, afterall. Maybe an active buck converter for a one-size-fits-all solution. Maybe a passive shunt regulator where you select the series resistor according to Vbat, for highest efficiency.
« Last Edit: September 28, 2015, 09:30:20 pm by KL27x »
 

Offline Cliff Matthews

  • Supporter
  • ****
  • Posts: 1910
  • Country: ca
    • General Repair and Support
Re: Latching push button circuit, need help with some things...
« Reply #35 on: September 29, 2015, 01:23:01 am »
...  Still can't help wondering why some pacemakers and ICD's (implantable cardioverter-defibrillator) use reed switches. According to abstract*, they have been tested in MRI fields at 3 Tesla. http://onlinelibrary.wiley.com/doi/10.1046/j.1460-9592.2002.01419.x/abstract

Polling with the MCU is certainly interesting, but it's still not the primary switch. Granted, I know squat about materials physics, but I hall sensors can be damaged by strong fields as well. Since your zero power option was not justly explored, can I suggest a second thread in projects specifically on reed lead-forming, handling, and magnetic stress/shunting?
 

Offline davekraTopic starter

  • Contributor
  • Posts: 33
Re: Latching push button circuit, need help with some things...
« Reply #36 on: September 29, 2015, 01:56:12 am »
A mechanical switch would be easier of course.  And reed switches have a long life...if treated with respect.
The little bit of testing I did with magnets on hand showed they could be damaged.
And I would agree, the circuit I was using had a capacitor shorting across the switch albeit a small one.  This could damage the contacts as well, but I experienced failure almost immediately.

I'm not sure I agree with a strong magnetic field damaging a hall sensor.
A snip from the Allegro website-
": Can a very strong magnetic field damage a Hall-effect device?
A: No. A very strong field will not damage an Allegro Hall-effect device nor will such a field add additional switchpoint hysteresis (other than the designed hysteresis)."

Honeywell also corroborates that a strong field will only drive the sensor into saturation.

So, a hall sensor is more robust.  As I won't be able to control the end environment having it be more reliable is more important than a few uA of current when off.
As I said before, someone already has a product that works with the voltage range I've mentioned and has a current draw of about 5uA.
I'm heading to Kansas next week where I'll be meeting with someone who has one of these switches.  I plan on taking some tools to map out the circuit and try to figure out how they are doing this.
As frustrating as this seems to be I still find it rewarding to try to figure this out. 

Thanks for the input.
davidk
 

Offline Cliff Matthews

  • Supporter
  • ****
  • Posts: 1910
  • Country: ca
    • General Repair and Support
Re: Latching push button circuit, need help with some things...
« Reply #37 on: September 29, 2015, 02:43:02 am »
Since few people carry around magnets, have you given thought to field energy from a close proximity key FOB? It could be like 2 or 3 button presses (one to wake, and another within another 3 seconds to analyze an RF envelope shape to toggle power state). Add one more internal pcb button to get the MCU into program in new key FOB mode. I don't know if there's enough compute in a PIC for precision (say between one Ford key FOB and another), but perhaps it's enough to count >8 packet bursts from a close-up key FOB from background RF pulses at 315Mhz? This also comes closer to your zero power ideal, since only a few antenna/filter components would connect to the ADC pin. Cheers!

http://www.greenhybrid.com/forums/f10/some-key-fob-experiments-19844/
« Last Edit: September 29, 2015, 04:42:26 pm by Cliff Matthews »
 

Offline davekraTopic starter

  • Contributor
  • Posts: 33
Re: Latching push button circuit, need help with some things...
« Reply #38 on: October 05, 2015, 01:53:53 am »
I got to look at the switch you can buy and I'm happy to say the hall sensor they used is the same one I bought.  It draws 2.5uA.
The circuit is pretty simple.  It goes regulator, sensor, something then the FET.
The total current draw when off is 4.2uA so whatever regulator they are using it's drawing much less on its own than the one I bought.

The regulator, FET and mystery component are labeled but the first search didn't come up with anything.

The regulator is marked with "HGRA"  .  It's a SOT-23 and is 3volt.

The FET is an SO08 and is marked:
4136
BAA (triangle)
w25B

What I think is a microcontroller is an SOT-23-5 marked  "H80R"

The regulator is the one I'd really like to identify.  The microcontroller is somewhat less importan but it would be cool to find that one as well just to see what they are using.
So, again, I'm hoping you can help with help with identifying the markings on these components.

Thanks guys,
davidk
 

Offline KL27x

  • Super Contributor
  • ***
  • Posts: 4099
  • Country: us
Re: Latching push button circuit, need help with some things...
« Reply #39 on: October 05, 2015, 02:23:14 am »
My guess is the sot23-3 is a 3V voltage reference IC. And the SOT23- 5 is a CMOS flip flop. The numbers on SOT23 parts is useless to anyone outside the manufacturing plant. Even to the manufacturer, it may be useless once taken out of context.
« Last Edit: October 05, 2015, 02:30:26 am by KL27x »
 

Offline davekraTopic starter

  • Contributor
  • Posts: 33
Re: Latching push button circuit, need help with some things...
« Reply #40 on: October 05, 2015, 03:48:39 am »
Bummer.

I think I found a regulator.  Rather than having circuitry to enable/disable the regulator a simple dumb regulator might have a lower draw.
The XC6201 series looks to have a 2uA draw. 
http://www.torexsemi.com/products/detail.php?id=363
With no quiescent current to quote the only current draw is the device.

The switch operates a little different than what I expected.  Rather than having to hold it for a few seconds before it turns off it seems to simply toggle on/off with a wave of the magnet.
That could mean a flip flop is what is being used.  I'll start looking at that but I kinda like the microcontroller idea.
With the controller I can turn everything off and the regulator/microcontroller would be the only things drawing current.   Couple that with it only checking for a magnet every .5 seconds could mean less current draw.

I'm going to continue down the microcontroller path (cause I want to learn assembly language) but a couple days looking at flip flops wont be wasted.

Thanks guys.
 
 

Offline davekraTopic starter

  • Contributor
  • Posts: 33
Re: Latching push button circuit, need help with some things...
« Reply #41 on: November 05, 2015, 02:47:08 pm »
Ok, so I lied.  I don't want to learn assembler.  C is proving to be enough of a challenge.

Using the Microchip PIC10f322 and MPlab xc8 I've got something that's almost working but I'm unsure of a few things in my code.

The SLEEP command on this midrange PIC should wake up and continue where it left off (I think).  When it wakes up I'd like it to restart the main for loop.
Does the 'return();' after the SLEEP restart the main loop as I hope?  It's not leaving the loop hanging where after time it would create a stack overrun?

Do the other returns go back to the main loop?

Do the initializations immediately after 'void main' only run once?  The LATA=0 setting all outputs low should only run once.  Subsequent loops should not set all outputs low.

I'd appreciate any suggestions or opinions on what I've got so far.
Thanks,
davidk

Code: [Select]
/*
 * File:   newmain.c
 * Author: davekra
 *
 * Created on October 21, 2015, 6:30 PM
 */
#include <xc.h>
// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.
// CONFIG
#pragma config FOSC = INTOSC                // Oscillator Selection bits (INTOSC oscillator: CLKIN function disabled)
#pragma config BOREN = OFF                  // Brown-out Reset Enable (Brown-out Reset disabled)
#pragma config WDTE = ON                    // Watchdog Timer Enable (WDT enabled)
#pragma config PWRTE = ON                   // Power-up Timer Enable bit (PWRT enabled)
#pragma config MCLRE = OFF                  // MCLR Pin Function Select bit (MCLR pin function is digital input, MCLR internally tied to VDD)
#pragma config CP = ON                      // Code Protection bit (Program memory code protection is enabled)
#pragma config LVP = OFF                    // Low-Voltage Programming Enable (High-voltage on MCLR/VPP must be used for programming)
#pragma config LPBOR = OFF                  // Brown-out Reset Selection bits (BOR disabled)
#pragma config BORV = HI                    // Brown-out Reset Voltage Selection (Brown-out Reset Voltage (Vbor), high trip point selected.)
#pragma config WRT = ALL                    // Flash Memory Self-Write Protection (000h to 1FFh write protected, no addresses may be modified by PMCON control)
#define _XTAL_FREQ 32000                    //Declare clock speed for __delay_ macro
int dely;                                   //Declare array for counting
void turnon(void);                          //Declare function
void turnoff(void);                         //Declare function

void main()
{
   
    OSCCONbits.LFIOFR=1;                    //Low freq internal oscillator enable
    OSCCONbits.IRCF=0b000;                  //Frequency select bits
    ANSELAbits.ANSA0=0;                     //RA0 - set as digital i/o
    ANSELAbits.ANSA1=0;                     //RA1 - set as digital i/o
    ANSELAbits.ANSA2=0;                     //RA2 - set as digital i/o
    TRISAbits.TRISA0=0;                     //RA0 - output power to Hall
    TRISAbits.TRISA1=0;                     //RA1 - output unused
    TRISAbits.TRISA2=0;                     //RA2 - output to FET
    LATA = 0;                               // start with all output pins low
    WDTCONbits.WDTPS=01001;                 //Watchdog set to 512ms
       
    //*** Main loop
    for (;;)
    {
        LATAbits.LATA0=1;                    //Turn on power to Hall
        __delay_ms(10);                      //Wait for Hall to initialize
            if (PORTAbits.RA3==1)            //Check if magnet present high=no, low=yes
            {
                LATAbits.LATA0=0;            //Magnet not present, turn off power to Hall
                SLEEP();                     //Sleep for 256ms
                return;                      //Return to beginning of loop
            }
        if (PORTAbits.RA2==0)                //if FET is off, go to code to turn it on
            turnon();                        //Call turnon function
        else                                 //FET must be on, go to code to turn it off
            turnoff();                       //call turnoff function
       
    }
}


void turnon(void)                             //turn on function
{
    LATAbits.LATA2=1;                         //Turn FET on
    for (dely=0;dely<=20;dely++)              //Start loop to test for button release
    {
        CLRWDT();                             //Clear watchdog timer
        __delay_ms(20);                       //Wait 20ms then..
        if (PORTAbits.RA3==0)                 //If Hall still low..
            dely=0;                           //Reset count and loop again
    }
    return;                                   //Return to main and start over
}
void turnoff(void)                            //turn off function
{
    for (dely=0;dely<=254;dely++)             //Start loop for 'button hold to turn off'
    {
        CLRWDT();                             //Clear watchdog timer
        __delay_ms(5);                        //Wait 5ms then..
        if (PORTAbits.RA3==1)                 //If button released before end of loop, cancel 'turnoff'
            return;                           //Return to main and start over
    }
    LATAbits.LATA2=0;                         //'Button hold' loop success, turn off FET
    return;                                   //Return to main and start over
}

 
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf