NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Basic Electronics » unexpected MCU rebooting

February 14, 2011
by sask55
sask55's Avatar

Hello I have bean trying to build a refrigerator control to replace the mechanical control that is not working on an old frig. The project works well on my bench. I wanted to experiment with what I could be done. I have incorporated a number of timers and provisions to record information (highest temp lowest temp, duty cycle ext.) as well as a simple four button control panel to allow a user set various factor. The control buttons, programming and information reporting seams to be working well when it is sitting on my bench. The control circuit will reliably open and close the relay that is intended to control the frig compressor. The issue that I cannot seam to solve is that it seams that my project is very sensitive to any electrical interference. I am suspecting that I am getting some kind of voltage spikes or RF pulse from the frig. I have tried a number of different relays the results are always the same. I have verified that there is no unwanted electrical connection within the relays, i.e. between the activation coil and the switching contacts. The nerd kit micro reboots almost ever time the compressor on the frig start or stops. That is to say that the lcd screen goes blank for a fraction of a second, all timers and data variables are reset. The strange thing is that this will occasionally occur even when the relay is not connected to anything at all, if the project is near the frig and the compressor starts up. It has happened even when I am running the project on a battery or an ac adapter plug in a completely different circuit. I have tried temporarily disabling the temperature sensor in the code just prior to the relay changing states that does not help. I have noticed that it will sometimes restart when some other electrical appliance in the same area starts up. i.e. when the deep freeze or the spin cycle on the washing machine start in the same room as my project is running. These appliances are not connected to the project in any way so it must be some kind of week EMP that the project cannot deal with. I have tried shielding the circuit board by wrapping it in aluminium foil connected to ground, that does not seam to help. I have also determined that the project will restart just about every time I turn on the heavy duty 12V power supply on my bench, even if there is nothing connected to that supply. I am suspicious that the problem is related to the fact that I have a number of longer cables connecting various components of the project. There is a six for long shieled cable between the LM34 and the circuit board. I did incorporate an R-C damper at the temperature sensor end of this cable as per the data sheet. The frig control relay is also separated from the circuit board by a six for cable with three conductors a 12v, a ground and a control wire to the gate of a 2n7000 at the relay. Just to clarify things the relay does work to control the frig compressor if I manually make the gate voltage go high on the relay control, and the control pin on the MCU works well on the bench to open and close the relay circuit , it will control a VOM meter connected across the relay output terminals just fine. The problem is once the MCU closes the relay when the frig is connected, the compressor begins to start up and 80% of the time the MCU restarts. I assume (now) that all this wiring is acting like antennas and delivering pulses to the circuit board or maybe I am missing something else. So, to some things up I do not have a clue why this project is behaving the way it is. If anyone has any suggestions or ideas that I could try, or could point out some error that I am making, I would greatly appreciate any help I can get. I would really like to get this project to work with the frig compressor as well as it seams to work sitting on my bench with no larger electrical loads switching near it.

February 14, 2011
by Ralphxyz
Ralphxyz's Avatar

Just to get started you have to isolate the Nerdkit.

Can you run the initialload program with the breadboard sitting on the refrigerator while turning the refrigerator on and off.

You could try battery powered and then wall wart power from a different circuit and then powered from the same circuit.

Will the mcu get rebooted now?

Ralph

February 14, 2011
by sask55
sask55's Avatar

Thanks Ralph unfortunately things are going from bad to worse, for some reason I can’t get the computer to reprogram the MCU chips. I have never had that happen before; I have 6 MCU chips, and have made dozens of writes operations. This is new.

Microsoft Windows [Version 6.0.6002] Copyright (c) 2006 Microsoft Corporation. All rights reserved.

C:Impt filesproject XNerd kitCode 328frig working>make avrdude -c avr109 -p m328p -b 115200 -P com4 -U flash:w:frig.hex:a

Connecting to programmer: . Found programmer: Id = "ó '"; type = ² Software Version = . ; Hardware Version = . avrdude: error: buffered memory access not supported. Maybe it isn't a butterfly/AVR109 but a AVR910 device? make: *** [frig-upload] Error 1

C:Impt filesproject XNerd kitCode 328frig working> I tried both my 328 chips I get the same message. The programming on the chips does not change during this process. It does not matter what I try to write nothing changed on the chip.

I will not be able to look at this much for the remainder of this month. I will be back in March and try to figure out what is going on then.

Thanks Darryl

February 14, 2011
by mrobbins
(NerdKits Staff)

mrobbins's Avatar

Hi Darryl,

When you're operating in a noisy electrical environment, using adequate power supply bypassing capacitors becomes especially important.

Can you tell us what capacitors you're using around the power supply parts of your circuit? That includes from +5V - GND, as well as something at the input of the voltage regulator.

As a quick way to estimate orders of magnitude of capacitance you might need, consider that a 60Hz AC power line has a half-cycle every 8 milliseconds. If your circuit consumes 10mA and you want it to be able to "survive" with only a 0.5V voltage drop over a power line cycle (if, for example, an enormous motor was just starting up), then you need a capacitor of size C = I * t / V, or plugging in these numbers, (0.010) * (0.008) / (0.5) = 160 microfarads (160uF). Depending on your actual values for I (how much current your circuit consumes), t (how long you want your circuit to survive without input power), and V (allowable voltage fluctuation before your circuit stops functioning properly), you can get an even better estimate.

Motors and compressors are especially "noisy" and can certainly affect nearby electronics that aren't even connected to them in any way, or even battery powered electronics.

Mike

February 15, 2011
by sask55
sask55's Avatar

Thanks mike Unfortunately I don’t have the time right now to look into things deeper. As I said in my last post I have lost the ability to change the programming on the chip. I have noticed a couple of things. Because I was having trouble loading programs on my 328 chip I swapped it with another 328 that I was using earlier in an effort to resolve the program loading issue. After I swapped the chip I was still not able to load any new programs to it but I have noticed that the version of my project on the second chip (a much earlier and less involved version) is much more stable. I cannot seam to make the project reboot at all by turning off and on equipment near the running project. That would seam to me that at least part of the unwanted reboot issue can be attributed to something in the additional code on the first chip. As far as caps in the power supply circuits go, this is a little involved as well. I was attempting to included in this project a power supply that would handle short to medium power interruptions, therefore I have both a 12 V wart (2 amp max) and a 9 v battery isolated by diodes. I do not know what capacitors are built into the ac adapter. I savaged it from and old external hard drive. I have incorporated a battery saving mode on the project, if the voltage on the wart side of the diode isolating the 12 V supply drops a input pin on the MCU goes low and the chip will shut down the relay,lcd indicators, and back light,as well as disabling the timer interrupts, ADC and buttons in an effort to extend the battery life and hold the variables on the chip. I found that the relay and the backlight do draw a substantial amount of power. and so I use a larger cap as a short term power source that holds the MCU voltage high (even with a larger draw from the relay and /or backlight) long enough for the system to go into power saving mode after the wart voltage drops. I have a 2200 uf cap in the 12V power supply on the voltage regulator side of the isolating diode. This all works great on my bench, if I unplug the wart the system goes into power saving mode and the battery hold the variables until power is restored. Other then that large cap I have the 0.1Uf cap between pin 7 and 8 ant the MCU as per the guide(on the 5 V side of the reg. When I get a chance to work on determining why the chips will not program I will investigate further.

Darryl

March 10, 2011
by sask55
sask55's Avatar

I am completely out of ideas as to how to improve my projects ability to deal with interferences. Completing the project to work on my bench was quick and simple when compared to resolving the rebooting issue. After trial and error with dozens of modifications in both hardware and programming The MCU will reboot about 20% of the time when the frig compressor either starts or stops. The only thing that know of that I have not addressed is the LC network connecting AVcc pin and the Vcc pin (page 257, 21.6.2 b in the ATMega328 data sheet). I do not have a 10uH inductor on hand. I could certainly get some but I am very sceptical that this will resolve the problem. I have decided to list a few point to describe the circumstance in point form. If anyone could to suggest anything that could be done to resolve this very frustrating problem I would be very grateful. .

MCU will occasionally reboot (about 20% of the time) if the frig compress ether is started up or stopped, when the project is on or near the refrigerator. o even when AC adaptor is not plug in. i.e. running on battery power only o When the compressor control relay is not connected to the frig in any way. o when running in a very short loop, timer interrupts and ADC are disabled o The Nerd kit circuit board is totally enclosed in a metal box. o The temp sensor LM24 is connected with R-C Damper as per figure 4 page 7 of the data sheet. o The temp sensor cable is now less then 2 feet long coaxial cable is used for the temperature output voltage line. o I tried to shield the actual temp sensor and the related R-C damper components with a second wire shield that what stripped from coaxial cable. I.e. the entire temp sensor its connection cable (power, ground and single lines) are enclosed in a second layer of wire shielding. o It does not matter if the metal box and or coaxial cables are earth grounded or not .i.e. eclectically connected to the frig body.

to help explain thecode below. Pin B is connected to the output side of a 4N35 optocoupler to insure that no high voltage get thru to the MCU. The input side for the 4N35 is connected to the 12 volt power supply from the adapter that is isolated by a diode.
This is the code that is intended to more or less put the project in a stand by mode if the voltage from the wall adapter drops off. It appears to work as expected. The MCU will reboot when adapter is unplugged i.e. The display is showing the Power failure warning and the circuit is running on the battery, if I manually start and stop the compressor a few times. Unless I am missing something the MCU is in a do nothing loop at that time everything should be stopped.

void chk_powr() {

 while(PINB & (1<<PB1)) {// chk for power from adapter
    if(cmode != 10){  // no power first pass
            while(ADCSRA & (1<<ADSC)) {
    // do nothing... just hold your breath.
  }
        PORTC &=~(1<<PC5);// insure back light is off
        PORTC &=~(1<<PC4);// insure compressor relay is off
        PORTC &=~(1<<PC3);// insure warn lcd is off
        ADCSRA &=~(1<<ADEN); //turn off ADC while power failure
        PORTC &=~(1<<PC2); //turn off "start up pending " lcd
        cli();//disable timer interupt
        //write power fail message to lcd
        lcd_clear_and_home();
        cmode =10; // set cmode to indicate power fail
        lcd_goto_position(1, 3);
        lcd_write_string(PSTR("POWER FAILURE"));
        lcd_goto_position(2, -1);
        lcd_write_string(PSTR(" Battery saving Mode"));
        } //if cmode != 10
    } // while power is off

    if (cmode ==10) { // reset after a power return
    cmode =1; //set screen mode to home
    lcd_clear_and_home();
    ADCSRA |=(1<<ADEN); //turn on ADC
     ADCSRA |= (1<<ADSC);  // set ADSC bit to get the *next*conversion started
    sei();//enable timer interupt
    }

}

I don't have a clue what else to do. This will be a issue for a number of other projects that I had in mind.

March 10, 2011
by Noter
Noter's Avatar

Can you post a schematic drawing of your project?

March 10, 2011
by Ralphxyz
Ralphxyz's Avatar

This makes it easier to see your points.

"I have decided to list a few point to describe the circumstance in point form."

    o even when AC adaptor is not plug in. i.e. running on battery power only 
    o When the compressor control relay is not connected to the frig in any way. 
    o when running in a very short loop, timer interrupts and ADC are disabled 
    o The Nerd kit circuit board is totally enclosed in a metal box. 
    o The temp sensor LM24 is connected with R-C Damper as per figure 4 page 7 of the data sheet. 
    o The temp sensor cable is now less then 2 feet long coaxial cable is used for the temperature 
       output voltage line. 
    o I tried to shield the actual temp sensor and the related R-C damper components with a second 
       wire shield that what stripped from coaxial cable. I.e. the entire temp sensor its connection cable 
       (power, ground and single lines) 
       are enclosed in a second layer of wire shielding. 
    o It does not matter if the metal box and or coaxial cables are earth grounded or not .i.e. 
       eclectically connected to the frig body.

Again can you run the initialload program next to the running refrigerator?

Possible there is something in your code inducing this situation so it would help to know if a simple program like the initialload will run.

If the initialload program runs then load your code but pull all of the tempsensor wires does your program run?

Is the mcu rebooted or effected?

Ralph

March 10, 2011
by sask55
sask55's Avatar

I have never drawn a schematic for anyone else to look at before. For now I just drew up a rough hand drawn schematic as I did not really have a complete and suitable version to post. A couple of things I could mention to clear things up a little. Pins 2,3,14 and 24 on the MCU are not connected to anything. The four push buttons are all connected to ground as well as one MCU pin. I see now that I did not drawn a 330 u resistor in series with the green LED there is one on my board. The relays that I purchased came two on each PC board. I was originally using only one relay and latter started using both in parelel this change did not seem to have any effect on the rebooting issue. The relay circuit was laid out on the board when I got it. I am not sure if this attempt at a schematic will be clear enough to be of any help. I have four input buttons (pins16-19) and the power failure pin (15) as digital inputs. I have pin 23 as an analog temp input. I have pins (25-28) as output pins controlling LED indicators and the LCD backlight. I used 2n7000 to control most off the LEDs because I found that the temperature readings seemed to drift upward when an LED was on. I though that the added current that the MCU was supplying may be the issue. When I controlled the LED thru the mosfets I had more consistent temperature readings. Again this project seams to work as I planned when it is not near the refrigerator. It has 11 different screen that allow the user to set values on start up temp, shut down temp, select Celsius of Fahrenheit, set a high temp warning point, set the average amperage used when compressor is on, set the cost of electricity, and reset the counters to start a new. The system tracks and displays the highest and lowest temperatures the longest and shortest period that the compressor was on and the longest and shortest period the compressor was off, the total time that the compressor was on, the duty cycle in % of the total time, the total power consumed and the cost of the power since the last reset. All of the user settable variables are set by using the value up or value down buttons , that will increment by one base unit for each push or will auto increment if they are held down. The auto increment increases exponentially with time so that very large changes in value can be achieved in a few seconds. for example the amperage setting can easily be changes by one amp up or down and only takes about 30 seconds to change from a value of 0 to a value 0f 4500. Anyways; all this is fine and seams to work well except that the fact that the system resets every few hours at best, all the stored information is lost, and it is back to the default values. This is very disappointing. http://img863.imageshack.us/img863/6157/curcuitsymetic.jpg Thanks Darryl

March 10, 2011
by sask55
sask55's Avatar

sorry I got the link wrong. I willtry again. syematic

I will relaod the initialload program and see how that goes. thanks Darryl

March 10, 2011
by Ralphxyz
Ralphxyz's Avatar

And so the answer to my question is??

March 10, 2011
by Noter
Noter's Avatar

Thanks for posting the drawing. That really helps me understand exactly what you're up to. I'm curious to see if your initial load test crashes the chip or not as per Ralph's plan. After looking at your circuit I kind of suspect the initial load test will run without problems which will indicate an unwanted bug somewhere in the software. Either way it will be progress.

March 11, 2011
by sask55
sask55's Avatar

I am not stalling on purpose but I do have a number of other things on the go right now. I still have not reloaded the initialload. For some strange reason the project has be running the refrigerator for about 20 hrs now with no sign of a problem, that is a record. I will reload initialload and monitor the results. When I start up my project I change the set temp from the default setting that way I can immediately tell if my project has reset with just a glance at the screen. With the initialled I will have to actually be looking at the screen to notice the reset. The problem is the frig compressor itself does not like to start up and stop then start up again. I will have to let the pressure equalize in the cooling system between start ups or an internal overload cut off in the compressor will shut down the compressor. It will take some time to test the initialload near the frig. I should be able to get to it this after noon.

Thanks for your thoughts so far.

Darryl

March 11, 2011
by sask55
sask55's Avatar

I have done the simple test that was suggested by Ralph. With the initialload running it is more difficult to positively recognize what is going on because the event is so short in duration. It does arrear to me that the problem is still there. When staring and stopping the frig occasionally the nerd kit screen does go blank for a fraction of a second. Even stranger the screen went completely blank when the initialload was running. The project was just sitting on top of the unplugged refrigerator and suddenly there was nothing on the LCD screen. I had to unplug and wall adapter wait a few seconds and plug it in again to get the intialload message to reappear. It seams to me that there is some problem in the hardware. For now, I am carefully checking the connections on my board. I also have a very similar project almost completed that I had intended to use on a 4000 watt 208 volt heater. I have made a few simple changes to the code to handle heating as apposed to cooling. I will make the changes so that I can try the other circuit on the frig.

Darryl

March 11, 2011
by BobaMosfet
BobaMosfet's Avatar

saask55

What diodes are you using, please? I'm redrawing the schematic so I can think about it. I see some problems and I want to make sure they are real or just how I'm viewing what you've done. I may have some more questions. Once it's done, I'll post it for you.

Thank you

BM

March 11, 2011
by sask55
sask55's Avatar

BM I do not know what diodes are used on the relay board they came with the board, they are small glass diodes. To be honest I am not 100% sure what I have around the power supply either. I used diodes that I had used before on some other projects and have lost track of the part number. I can’t see any identification on the actual diodes. I think they are most likely 1N4001 at least that is what they look like. I only have three types of unused diodes on hand right now I could certainly get something else. I have new 1N4001, 1N4003, and 1N4148. should I replace the diodes? would it be a good idea to get a different type?

Thanks for the help Darryl

March 11, 2011
by sask55
sask55's Avatar

BM I do not know what diodes are used on the relay board they came with the board, they are small glass diodes. To be honest I am not 100% sure what I have around the power supply either. I used diodes that I had used before on some other projects and have lost track of the part number. I can’t see any identification on the actual diodes. I think they are most likely 1N4001 at least that is what they look like. I only have three types of unused diodes on hand right now I could certainly get something else. I have new 1N4001, 1N4003, and 1N4148. should I replace the diodes? would it be a good idea to get a different type?

Thanks for the help Darryl

March 12, 2011
by Noter
Noter's Avatar

Could this be causing your reset problem?

Custom Butterfly Application Suffers from "Spurious Resets" When starting a custom application for the AVR Butterfly via the bootloader, the butterfly application and/or the bootloader leaves the pin change interrupts enabled. If the application doesn't implement an interrupt handler for that, it will perform the default action for unassigned interrupts which is a restart from address 0 for avr-libc.

Solution: if you don't need the pin-change interrupt, set EIMSK to 0. An application that has been started from the butterfly bootloader cannot rely on the hardware state being pristine as an application started by a normal hardware reset could do.

From: http://www.avrfreaks.net/wiki/index.php/Documentation:Things_That_Are_Broken

March 12, 2011
by BobaMosfet
BobaMosfet's Avatar

saask55-

I'm uncertain as to why you're using those diodes? The 1N400x will only allow 1V at 1Amp, and the 1N4148 will only allow 1V at ~300mA.

If you use a magnifying glass, you should see some sort of marking on the diode. If not, but it's clear glass with copper inside and a black band on one end, it might be a zener....

Each diode also causes a .7 drop/loss (approx) through it, and the LM7805 can have a drop.loss of 1.5 to 2.5 volts through it.

I think it's important to step back and make sure you understand what you're engineering, and make sure you have the proper parts where they need to be, to deliver the amount of current you need at the proper voltage, to each unique part of your circuit.

Can you explain why you have diodes where you have them, and why exactly you have your power-supplies wired the way you do?

BM

March 12, 2011
by sask55
sask55's Avatar

Ok I have no technical training in electronics at all. I can try to explain my thoughts for the placement of the diodes, and why I though theses diodes would work. I was under the impression that a diode was an electrical component that would allow a current to flow in one direction (with a voltage drop) but would not allow current to flow in the opposite direction as long as the reverse voltage and maximum forward current where within the limits of the diode. I do not know what you mean by “The 1N400x will only allow 1V at 1Amp”. . I though that the forward voltage Vfm is the voltage drop across the diode when the current is passing thru it.

What I am trying to do is let current flow from ether the 9 v battery or the 12 volt adapter to the 7805 voltage regulator, but I do not want any current to flow from the 12V supply to the battery or from the battery to the 12 volt supply when it is not powered up. I have tested the project current draw with an ammeter, with the relays active and the backlight on, it draws about 210MA. I know that the reverse voltage that I am dealing is under about 14 volts max in the case of the adapter current flowing to the battery and under 10 volts in the case of the battery current flowing to the adapter. So; my thoughts on using a 1N4001 are, the 50 volt working peak reverse voltage is well above anything that I expected from ether the battery or the AC adapter and therefore these diodes should be suitable to block any significant reverse current. Secondly: the 1 amp max output current is well above the expected draw of the project so the diodes should handle the current with no difficulty. Third; the 1 volt drop across the diode would result in a voltage of about 11 volts from the adapter or about 8 volts from the battery (in the absence of the adapter voltage). I have measured these voltages with a voltage meter and they are as I expected. Either of these voltages should be adequate to maintain a 5 volt output on the out pin of the regulator. The idea is to allow the project to maintain memory thru short power interruptions on the AC power line and then return to normal functions where power is restored. I still do not understand where this is incorrect.
Sorry I don’t understand what is wrong with these diodes.

Darryl

March 12, 2011
by sask55
sask55's Avatar

Notor

I think that you may be unto something. I found your last post very interesting. I will be testing the project with the pin change interrupts disabled. I will let you know how that goes. The biggest question I have about that is why would the initialload test have problems.

thanks Darryl

March 12, 2011
by sask55
sask55's Avatar

BM As you suspected when I got out a powerful magnifying glass I can see part numbers on the diodes. The diodes on the relay boards are indeed zener diodes 1N4746, from the data sheet they have 18 V nominal zener voltage. Otherwise the other diodes are 1N4001. I don’t know what implications this has on my problems.

thanks

Darryl

March 12, 2011
by Noter
Noter's Avatar

Well, I think the initial load program does not disable the pin change interrupts either and likely is in the same condition if a transient interrupt occurs. It could be that the wierd power fluctuation that happens when the compressor is powered up is causing an interrupt on one of the pins and thus resetting the atmega. I guess we'll know for sure once you have the interrupts disabled and test again.

March 12, 2011
by BobaMosfet
BobaMosfet's Avatar

saask55-

Okay, I see where you're headed. You are correct with the voltage drop. Since you're only drawing a nominal load, a resistor to protect the diode is probably not necessary.

However, I notice you've got inputs (pin #6) on the 4N35s that are not (in your drawing) tied to ground-- they should be. This might be part of the problem because these inputs are susceptible to EMI and capacitance issues.

I'm still drawing...

BM

March 13, 2011
by sask55
sask55's Avatar

BM

I have experimented a little with connecting the base (pin 6) of the 4N35 optocoupers to ground. With the base short to ground current flow from the collector to the emitter stops, (i.e. the chip stops working) or at least it will to sink enough current to pull down the MCU pin to a low state. I did a little trial and error test on the chip handling the power failure voltage signal and found that anything smaller then a 15K resistor would immediately cause the MCU to report a power loss. I could tie the pin 6 to ground thru a high value resistor say 100k. If that would stabilize the circuit somewhat. If you are interested you could take a look at this site I found as I was attempting to figure out what could be going on with my project.

http://www.technogumbo.com/projects/Learning-to-Use-an-Optocoupler-or-OptoIsolator/index.php

Thanks Darryl

March 13, 2011
by BobaMosfet
BobaMosfet's Avatar

Darryl,

Remember, the 4N35 is a transistor (BJT). As such, current flow from pins 4 to 5 is controlled by pin 6. The emitter LED at pins 1 to 2) only INFLUENCES the base. In a BJT, you want to use a voltage-divider to control the base. In this case, the voltage-divider is composed of the emitter LED (pins 1 & 2), and a resistor on pin 6. The size of the resistor depends on whether you tie pin 6 to positive or ground (based on how you want to 'bias' the transistor).

A resistor on pin 6 is required.

Without connecting pin 6, your opt-couplers are subject to significant instability associated with EMI.

You might want to brush up on voltage-dividers, and biasing bjt transistors- this will help you understand this, and how to calculate what size resistor to use on pin 6. Pay particular attention to the voltage and current limits (see the datasheet) for the emitter diode, and the transistor (detector) on the 4N35.

BM

March 13, 2011
by sask55
sask55's Avatar

I was really thinking that the solution that Noter found was going to be the answer, but no. The project was working well controlling the frig for about 15hrs, but in the last few hrs. It has reset or rebooted at least four times.

I have been looking over some basic information on biasing bjt transistors and voltage dividers. To be honest I really prefer writing code or the more or less on or off environment of TTL and other digital logic, working with analog circuitry is not my favourite. So far it seams to me that since I am not doing any form of amplification I really only require that the transistor is ether saturated or is off.

Anyway I thought that I would just post that the pin-change interrupt disable test has failed

Darryl

March 13, 2011
by sask55
sask55's Avatar

After looking over the Atmel document in this link http://www.atmel.com/dyn/resources/prod_documents/doc1619.pdf I don’t think is likely I will ever get this project or several others that I have in mind to work as I hoped. I intend to read the relevant sections more closely perhaps I can try to implement a few simple steps to try and mitigate the EMC somewhat, but a lot of the board design issues are far beyond my design or construction capability.

Darryl

March 13, 2011
by BobaMosfet
BobaMosfet's Avatar

Darryl--

Understood. Electronics is not for the faint-hearted. You're either in for the whole enchilada, or you're not.

The 4N35 is doing amplfication, in order to proportionally control the difference in current between B and CE. Opto-couplers are current devices.

Why don't you try the blunt-force method and stick a 100K Ohm pot (one came with the NerdKit) on pin6, turn it one way while the thing is running and then slowly turn it the other way, to see if the thing smooths out for you? Then use a meter to determine the voltage drop across it, and voila- you will be able to know the current and the resistance it's set at.

Darryl, you're smart. You've come a long way, and done an impressive job thus far. You also read the data sheets well. You're just a little bit over your head, that's all. There is a delicate transition period from NerdKit basics, to application of more advanced, on-your-own-thunk-it projects. And I believe that's where you're at right now-- the deep end of the pool. We were all there once.

My advice is simple-- method, method, method. Don't guess, don't stab around- if the transistor seems scary, then go after it. learn it; own it. Take that sucker down... HARD. You'll be glad you did.

I'm interested in seeing how the trimpot idea works, if you decide to try it.

BM

March 13, 2011
by Noter
Noter's Avatar

Hi Darryl,

Too bad on disabling the pin interrupts but it was worth a try. I looked over that ATmel document you found and right at the end was something that might work. I didn't think about it before but if you somehow get 12v on the reset pin even for just an intstant the chip could be going into parallel programming mode long enough to cause a reset. Take a look at the protection given the reset pin in Fig 4-7 on page 15 of the ATmel document. Only a few components and I think worth a try.

Hang in there, I'm sure you'll get it going. Just going to be harder than you thought. Seems that happens to me all the time. ;-)

Paul

March 13, 2011
by sask55
sask55's Avatar

thanks guys

This is a great forum with some realy outstanding members. Anyway I am not quiting. I have a number of unrelated meetings in the next few days. I will be trying to get some more reading done and perhapes get a chance to get back to the bench and try making some changes to the curcuit.

Darryl

March 17, 2011
by sask55
sask55's Avatar

BM

I would attempt to try the blunt-force method to set the bias on the optocouplers if I had any idea what I should be monitoring. I don’t know what you mean by “see if the thing smooths out for you” in your last post. How would I have any indication “when things smooth out”. This project work as expected, with no issues, for long periods of time. It will function fine often for hours at a time even when running the refrigerator. The problem is very brief and likely would not even be noticed if it did not cause all of the variables in the MCU memory to be reset to there default (start up) values. It only occurs when the frig compressor is starting or stopping which can only happen at most every few minutes, as the compressor will not restart when the pressure differential in the cooling system is to high. It does not occur every time the compressor is switched; as I have said sometime it take hrs to determine if the problem has been resolved or not after I make a change.

In any event I completely removed both optocoupelers from the circuit to check if that would resolve the problem. It did not make any difference, the project will occasionally reset when sitting near the frig even when the relay control circuit and the power failure circuits are not connected at all.

Darryl

March 17, 2011
by sask55
sask55's Avatar

I have completed a number of steps to try to resolve the reset issue. I think at this point I am going to have to say this is not likely to work and I don’t know why not. Since I have no more ideas and I have not bean successful in finding the cause of the problem I have tried to eliminate various components by trial and error with no success.

The steps I have tried in the last couple of days

   •Rebuilt the entire circuit board with a different layout, trying to separate the input and output lines from the power conductors as much as I can.
   •Protected the reset pin with the diode ,capacitor, and resistor as indicated in the Atmel document on dealing with EMC  
   •Removed the two diodes and the battery on the power supply 
   •Used a different power supply 
   •Used a different MCU chip
   •Used a different LCD screen
   •Tried again both inside and outside the totally enclosed (except for the screen) metal box.
   • Used a different lm34 temp sensor that was connected with a different cable.
   •Removed the optocouplers and related components from the circuit.

Most of this was intended to be used on my heater adaptation of the frig project. I was going to try and make use of three of these, at this point it looks like one is way too many.

Darryl

March 17, 2011
by sask55
sask55's Avatar

I never really considered the distinction between a reboot and a reset. I now suspect that the chip is resting not rebooting. A quick search for reset in the ATMega328.pdf gives some interesting reading. I suspect that the solution is related to adequately controlling voltage fluctuations on the reset pin. Although I have implemented some circuit changes to try an address this issue I now feel that this is the most promising area for me to consider. I am not certain that anyone is still interested but I hate to give up on something that seams so close.

Darryl

March 17, 2011
by BobaMosfet
BobaMosfet's Avatar

Darryl

Yes, we are DEFINITELY still interested in this-- I apologize I've been overrun- bad day at work, just won't end-- I am trying to find time to rebuild the essential pieces of your circuit to play with and test on my own bench. I hate 'arms length' :P

BM

March 17, 2011
by BobaMosfet
BobaMosfet's Avatar

Something you might try- flow chart your code. Don't draw it as you want it to work-- draw it as it is written. Important distinction. But it may, in a few minutes, identify any logic error that could be causing this.

BM

March 17, 2011
by Noter
Noter's Avatar

Bm has a point, the problem could be in your code. If for some reason you jumped to address 0 you would reset because address 0 is the reset vector. But it does seem unlikely since it works over and over on the bench and doesn't fail every time the compressor switches. Then again, the hard to find bugs don't follow rules.

If you don't find anything flowcharting like BM suggests, post your code and I will look it over to see if I spot any problems. Others probably will look it over too and maybe someone will find something.

March 17, 2011
by sask55
sask55's Avatar

Yes

I will be doing a detailed flowchart this weekend. The thing is it appeared that the project was resetting when running the inialload program, it is a little hard to be sure because the screen goes black for a very shot period of time. I do know that it was resetting while running on the backup battery in what should be a very short do nothing loop. If I unplugged the AC adapter the power failure screen will appear as expected, if I then manually start and stop the compressor a number of time until see the LDC screen flicker and then restore the ac power all of the variables will have reset. If I do not cycle the compressor and restore the power the variables are retained as they where before the power loss. It seams to me that this will be a hardware fix but then again I have thought totally wrong a number of time on this thing.

I don't have a problem posting my code. I will take a crack at the flow chart first.

thanks

Darryl

March 18, 2011
by Ralphxyz
Ralphxyz's Avatar

Darryl, you need to do the initialload test with just the basic Nerdkit breadboard setup without any of your wiring addition.

The screen going dark sounds like a lose wire (vibrations).

Ralph

March 18, 2011
by sask55
sask55's Avatar

ok

I will try the initial load on a basic board next time I get back to the house. I have had three completely different circuit boards built with my project on them. Two of the boards are on Nerdkit style proto boards and one is on predrilled perf board with 100% soldered connections. Also I often did not place the project on the refrigerator for all of the tests. I have tried placing it as far away as the cables will allow, on a concrete floor more than six feet from the refigorator (before I cut the temp sensor cable down to about two feet). I don’t think is possible that the same loose connection would occur at the same instant that the compressor is cycled through all of these vary different test conditions. The longer the cables are the more often the problem occurs the closer to the frig the more often it is likely to occur, When I first moved the project from my bench to the basement frig I had long cables on the relay, tempsensor, and lcd display/control panel. At that time it reset almost every time if the frig either started or stop. Currently with a short double shielded temp cable a shorter relay cable and very short lcd connections it resets much less often, maybe once in every 5 to 10 starts sometimes longer. My suspicions are that with absolutely no cables of any length connected to the board (i.e. the basic nerdkit) it will not reset, or it may take a lot of starts and stops while viewing the lcd to observe a short interuption in the screen.

Darryl

March 22, 2011
by sask55
sask55's Avatar

I have tried running the initialload on a basic nerdkit board. So far I have not noted any resets on that setup. As I have mentioned before it is not possible to do a lot of restarts in quick succession. So I have added a bit of code to the initialload so that I can leave the basic board running next to the frig control project for extended periods of time and then be able to recognize if it has reset. I did not include an interrupts of any kind. Accurate timing is not required at all. I am just using a delay in a loop to display a rough indication of how long it has been since the last reset. I have monitored it over a day or so and there was no indication of a reset, in that same period of time my project had rest a number of times. I then swapped the two MCU chips on the two boards, ie I had the chip programmed with my project code running on the basic board (with pin 15 connected to ground to simulate normal “AC power on” conditions). The modified initialload code is running on my project board. The original mechanical temp control is controlling the refrigerator compressor for this test. Neither of these two circuits have reset but I will continue with this setup for a day or two. When I have my project controlling the frig compressor, it actually does a good job of maintaining a set temperature within the refrigerator. The malfunctioning mechanical control on the refrigerator will no longer bring the temperature below 5 or 6 deg. Celsius. My project will maintain the temperature down as close to freezing as I wish as long as I set that temp as a default value in the code. I could say I do have a working frig temperature control, and I do have a working “on frig” control panel. The project is recording parameters as it runs. I am happy with the way the buttons and the information screens work, however these added futures are of no use because the project resets so often.

I am posting my code such as it is. I had never written any C before I got the Nerdkit. I am sure there is a lot that could be improved. Perhaps someone can point out an issue that could be contributing to this problem. The code works the way that I intended except for the resets. The resets that I have actually seen always occur when the frig compressor is starting or stopping, with no regard to what screen is showing, or what the chip is doing at the time. Resets have occurred when the compressor is started by the project relay, by the original frig control, and by just plugging in the warm frig when the relay is not even connected to the frig.

// frig.c
// for NerdKits with ATmega 328p

#define F_CPU 14745600

#include <stdio.h>
#include <math.h>

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <inttypes.h>

#include "../libnerdkits/delay.h"
#include "../libnerdkits/lcd.h"
#include "../libnerdkits/io_328p.h"

// PIN DEFINITIONS:

// PC2 -- compressor startup pending indicator lcd (allow pressure to equilize before restarting comp)
// PC3 -- Over temp warning lcd
// PC4 -- compressor relay control output 
// PC5 -- back light control output
// PC0 -- temperature sensor analog input
// PB1 --  power adapter voltage drop ind.(power failure ind)
// PB2 -- light Button
// PB3 -- mode button
// PB4 -- adjust down button
// PB5 -- adjust up button

volatile uint16_t Light_time; //duration of light timer 
volatile uint16_t the_time;  //  total time since reset < 1 min
volatile uint32_t time_min;  // total time since reset in min
volatile uint32_t elap_time; //dutation of current comp state
volatile uint32_t on_min;    //shortest duration comp on
volatile uint32_t on_max;    //longest duration comp on
volatile uint32_t off_min;   // shortest duration comp off
volatile uint32_t off_max;   // longest duration comp off 
volatile uint32_t on_time;   //total time comp on since reset < 1 min
volatile uint8_t comp_was;   //state of comp
volatile uint16_t button_time;  // duration time for auto increment button down
volatile uint32_t on_time_min;  //total time comp on since reset in min
float primary_increment;      //set increment value for mode
float max_value;              //set max  value for mode
float min_value;              // set min  value for mode
uint16_t light_timer;         //light time out value
uint8_t cmode ;               //display mode
uint8_t Lchange;              // last button change
uint8_t Lstate;               // last button state
char tscale;                  // C or F tempature scale 
float temp_avg;               // the frig temp in F no calabration
float set_temp;               // comp off temp
float frig_temp;              // frig temp for display
float temp_offset;            // offset above set_temp for comp on
float warn_temp;              // high temp warning temp
float watts;                  // average watts power use
float price;                  // cost of power   
float rec_high_temp;          // highest temp since reset
float rec_low_temp;           // lowest temp since reset
float temp_calab;             // adjustment cor for temp
uint8_t warn_timer;           // light flash warning timer
int auto_inc_ct;              // auto increment control count

void adc_init() {
  // set analog to digital converter
  // for external reference (5v), single ended input ADC0
  ADMUX = 0;

  // set analog to digital converter
  // to be enabled, with a clock prescale of 1/128
  // so that the ADC clock runs at 115.2kHz.
  ADCSRA = (1<<ADEN) | (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0);

  // fire a conversion just to get the ADC warmed up
  ADCSRA |= (1<<ADSC);
}

uint16_t adc_read() {
  // read from ADC, waiting for conversion to finish
  // (assumes someone else asked for a conversion.)
  // wait for it to be cleared
  while(ADCSRA & (1<<ADSC)) {
    // do nothing... just hold your breath.
  }
  // bit is cleared, so we have a result.

  // read from the ADCL/ADCH registers, and combine the result
  // Note: ADCL must be read first (datasheet pp. 259)
  uint16_t result = ADCL;
  uint16_t temp = ADCH;
  result = result + (temp<<8);

  // set ADSC bit to get the *next* conversion started
  ADCSRA |= (1<<ADSC);

  return result;
}

double sampleToFahrenheit(uint16_t sample) {
  // conversion ratio in DEGREES/STEP:
  // (5000 mV / 1024 steps) * (1 degree / 10mV)
  //     from ADC         from LM34
  return sample * (5000.0 / 1024.0 / 10.0);  
}

void chk_powr() {

     while(PINB & (1<<PB1)) {// chk for power from adapter
        if(cmode != 10){  // no power first pass
                while(ADCSRA & (1<<ADSC)) {//ATMega328 datasheet 26.6.2 d - no C pin changes while ADC running
    // do nothing... just hold your breath.
  }
            PORTC &=~(1<<PC5);// insure back light is off
            PORTC &=~(1<<PC4);// insure compressor relay is off
            PORTC &=~(1<<PC3);// insure warn lcd is off
            ADCSRA &=~(1<<ADEN); //turn off ADC while power failure
            PORTC &=~(1<<PC2); //turn off "start up pending " lcd
            cli();//disable timer interupt
            //write power fail message to lcd
            lcd_clear_and_home();
            cmode =10; // set cmode to indicate power fail
            lcd_goto_position(1, 3);
            lcd_write_string(PSTR("POWER FAILURE"));
            lcd_goto_position(2, -1);
            lcd_write_string(PSTR(" Battery saving Mode"));
            } //if cmode != 10
        } // while power is off

        if (cmode ==10) { // reset after a power return
        cmode =1; //set screen mode to home
        lcd_clear_and_home();
        ADCSRA |=(1<<ADEN); //turn on ADC
         ADCSRA |= (1<<ADSC);  // set ADSC bit to get the *next* conversion started
        sei();//enable timer interupt
        }
}

void chk_buttons() 
{
    uint8_t cnt = 0;  // button no change count
    uint8_t iz = 0;   // button reads for change count
    uint8_t Nstate = (PINB & 0x3c);// read the state of all buttons

    if((Lstate & 0x3c) == Nstate)// check for pin change on any button
        {

        return;// no button changes 
        }

    while(iz++ < 20)// reread up to 20 times to debounce
    {

        delay_ms(4);// short delay

        if((PINB & 0x3c) == Nstate) 
        { // reread to check for consistant value
            // pin reading is the same
            cnt++;

            if(cnt >= 6)// looking for 6 consecutive values
            { // accept new Button state as debonced

                if((Lstate & (1<<2)) != (Nstate & (1<<2)))
                {  //check Button #1 -"light/home botton"

                    if((Nstate & (1<<2)) == 0)
                    { // check state of button? button #1 is down
                        Lchange = 1;// store button state #1 down  
                        if (cmode == 1) 
                        { //at home page?
                            if(PORTC & (1<<5))
                            { //light is on?
                                PORTC &=~(1<<PC5);// turn backlight off
                                Light_time = light_timer; // deactivate light timer
                            }else
                            { //backlight is on else
                                PORTC |=(1<<PC5);//turn on backlight
                                Light_time = 0; // activate light timer
                            }

                        }else
                        { //  at home page else
                            cmode = 1;  // reset to homepage
                            Light_time = 0;//  activate light timer
                        } 
                    }else
                    { //button #1 is up
                        Lchange = 5;  // store button change to #1 up
                    } 
                }else if((Lstate & (1<<3)) != (Nstate & (1<<3)))
                {  //check Button #2 "mode botton"
                    Light_time = 0;
                    PORTC |=(1<<PC5); //turn on backlight
                    if((Nstate & (1<<3)) == 0)
                    {
                        Lchange = 2;   // button 2 down
                        if(cmode == 8)
                        {
                            cmode = 1;// reset to cmode #1
                        }else
                        {
                            cmode++;//  increment cmode by 1
                        }
                    }else
                    {
                        Lchange = 6;  //button 2 up
                        lcd_clear_and_home(); //cleer the lcd for new mode
                    }
                }else if((Lstate & (1<<4)) != (Nstate & (1<<4)))
                {  //check Button 3 "down/reset button"
                    Light_time = 0;
                    PORTC |=(1<<PC5);
                    if((Nstate & (1<<4)) == 0)
                    {
                        Lchange = 3;   // store bOtton #3 is down
                        switch(cmode)
                            {
                                case 2:
                                    tscale= 70;// set scale to f "
                                    Lstate = Nstate; 
                                    break;

                                case 6:
                                    cmode = 9;
                                    lcd_clear_and_home();// set cmode to conformation screen
                                    Lstate = Nstate;
                                    break;

                                case 9: // reset all the data  variables to defaul values
                                    rec_high_temp = 0;
                                    rec_low_temp = 100; 
                                    on_time_min =0;
                                    on_time =0;
                                    the_time =0;
                                    time_min =0 ;
                                    elap_time =0 ;
                                    on_min = 599400;
                                    on_max =0;
                                    off_min =599400;
                                    off_max=0;
                                    lcd_clear_and_home();
                                    cmode=6;
                                    Lstate = Nstate;
                                    break;

                                default:
                                    auto_inc_ct=1;  //set for auto inc
                                    button_time =50; // restart auto inc timer
                            }

                    }else
                    {
                        Lchange = 7;  //button 3 up
                        auto_inc_ct=0;
                        button_time =0;

                    }

                }else if((Lstate & (1<<5)) != (Nstate & (1<<5)))
                {  //check Button 4 up
                    Light_time = 0;
                    PORTC |=(1<<PC5);
                    if((Nstate & (1<<5)) == 0)
                    {
                        Lchange = 4;   // store button #4 is down
                        switch(cmode)
                            {
                                case 2:
                                    tscale= 67;  // set scale to C
                                    Lstate = Nstate;
                                    break;

                                case 6:
                                    cmode = 1;
                                    Lstate = Nstate;
                                    break;

                                case 9:
                                    cmode = 1;
                                    Lstate = Nstate;
                                    break;

                                default:
                                        auto_inc_ct=1;  //set for auto inc
                                        button_time =50;  // restart auto inc timer

                            }
                    }else
                    {
                        Lchange = 8;  //button 4 up
                        auto_inc_ct=0;
                        button_time =0;

                    }

                }
                Lstate = Nstate;
                return;

            }

        }
        else
        { // pin reading is the same else
            cnt = 0;  // pin reading is different reset match counter
        } //check for consistant pin reading
    } //while iz < 20
    // no Button push accepted just return
}

void realtimeclock_setup() {
  // setup Timer0:
  // CTC (Clear Timer on Compare Match mode)
  // TOP set by OCR0A register
  TCCR2A |= (1<<WGM21);
  // clocked from CLK/1024
  // which is 14745600/1024, or 14400 increments per second
  TCCR2B |= (1<<CS22) | (1<<CS20) | (1<<CS21);
  // set TOP to 143
  // because it counts 0, 1, 2, ... 142, 143, 0, 1, 2 ...
  // so 0 through 143 equals 144 events
  OCR2A = 143;
  // enable interrupt on compare event
  // (14400 / 144 = 100 per second)
  TIMSK2 |= (1<<OCIE2A);
}

ISR(TIMER2_COMPA_vect) {

  // when Timer0 gets to its Output Compare value,
  //one one-hundredth of a second has elapsed (0.01 seconds).
     //chk for backlight timeing active?
     if(frig_temp< warn_temp){
     if (Light_time < light_timer) {
    Light_time++; // increment timer -light timer active
        }else{  //light timer active else
            if(cmode == 1) {  // AT HOME PAGE
            PORTC &=~(1<<PC5);// Turn backlight off
            }else{ // if at home page else not at home page
            cmode = 1;  // Reset to home page
            Light_time = 0;// reset light timer
                } // if not at home page
        } // if light timer not active
        }

        if(button_time >0){ //increment button time
        button_time++;
        }
        if(button_time >= 300){ // reset button time 
        button_time = 0;
        }

        elap_time++;  // comp state duration timer
 if((PORTC & (1<<PC4)) == comp_was) { //check for comp state change

    if((PORTC & (1<<PC4))>0) {// compress on?
    on_time++;  //add to on time
            if(on_time >= 6000) {
            on_time_min++;
                on_time = 0;
                }

    }
    }else{  //compressor state has changed
        comp_was= PORTC & (1<<PC4); //reset to new state
    if(comp_was == 0) {  //compressor was on

        if(elap_time < on_min) {  //check for new shortest
        on_min = elap_time;
        }
        if(elap_time > on_max) {  //check for new longest
        on_max = elap_time;
            }
            }else{   //compressor was off

            if(elap_time < off_min) {  //check for new shortest
        off_min = elap_time;
        }
        if(elap_time > off_max) {  //check for new longest
        off_max = elap_time;
        }
        }
         elap_time = 0;
        }

  the_time++; // inc total time
 if(the_time >= 6000) {
 time_min++;
 the_time =0;
 }
}
float incr_value(float ch_value){
    float modifier =1; // temp scale adj factor
    float temp;
    int temp2;
    if (auto_inc_ct ==0){// check if value is to be incremented
    return ch_value;
    }
    if((tscale==67) && (cmode<6)){ //check for temp scale adjustment
    modifier = (1.8); // use deg C
    }
        if ((Lchange == 3) && (button_time>=40)){ // button 3 down timed out so increment value down
        Light_time = 0; // activate light timer
        temp=(float)(auto_inc_ct/6); //set up loop for exponential inc
        temp2 = (((int)(temp))+1)*(((int)(temp))+1);
    ch_value=ch_value - (temp2*modifier*primary_increment);

            if(ch_value< min_value){
            ch_value=min_value;
            }
    auto_inc_ct++;
    button_time=1;
    //return ch_value;
    }else{
    if ((Lchange== 4) && (button_time>=40)){// button 4 down incremnt value up
    Light_time = 0; // activate light timer
    temp=(float)(auto_inc_ct/6);
        temp2 = (((int)(temp))+1)*(((int)(temp))+1);
    ch_value=ch_value + ((temp2)*modifier*primary_increment);

            if(ch_value> max_value){
            ch_value=max_value;
            }
    auto_inc_ct++;
    button_time=1;
    //return ch_value;

    }

    }
    return ch_value;

}// return no bOttons down no change to value

void L1() {

lcd_line_one();
    lcd_write_string(PSTR("Home        Increase"));
    }
void L2() {

lcd_line_four();
    lcd_write_string(PSTR("Mode         Decease"));
    }
void mode1(){
    float dis_set_temp;
        float dis_frig_temp;
                primary_increment =.1;
    max_value= 100;
    min_value = 0;

    set_temp =incr_value(set_temp);

 FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE);

        if(tscale == 67) {
        dis_set_temp = ((set_temp + temp_calab-32)*5/9);
        dis_frig_temp = ((frig_temp + temp_calab-32)*5/9);
        }else{
        dis_set_temp= (set_temp + temp_calab);
        dis_frig_temp = (frig_temp + temp_calab);
        }

    lcd_line_one();
    lcd_write_string(PSTR("Light       Increase"));     
    lcd_line_two();
    fprintf_P(&lcd_stream, PSTR("   Set Temp %4.1f"), dis_set_temp);
    lcd_write_data(0xdf);
    fprintf_P(&lcd_stream, PSTR("%c  "),tscale);
    lcd_line_three();
    fprintf_P(&lcd_stream, PSTR("  Frig Temp %4.1f"), dis_frig_temp);
    lcd_write_data(0xdf);
    fprintf_P(&lcd_stream, PSTR("%c  "),tscale);
    L2();

    }

    void mode2(){
        float dis_rec_high_temp;
        float dis_rec_low_temp;

    FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE);
    if(tscale == 67) {
        dis_rec_low_temp= ((rec_low_temp + temp_calab-32)*5/9);
        dis_rec_high_temp = ((rec_high_temp + temp_calab-32)*5/9);;
        }else{
        dis_rec_low_temp= (rec_low_temp + temp_calab);
        dis_rec_high_temp = (rec_high_temp + temp_calab);
        }

    lcd_line_one();
    lcd_write_string(PSTR("Home  choose-Celsius"));
    lcd_line_two();
    lcd_write_string(PSTR("  Select Temp Scale "));
    lcd_line_three();
    fprintf_P(&lcd_stream, PSTR("High%4.1f  low%4.1f"),dis_rec_high_temp,dis_rec_low_temp);
    lcd_write_data(0xdf);
    fprintf_P(&lcd_stream, PSTR("%c  "),tscale);
    lcd_line_four();
    lcd_write_string(PSTR("Mode   Or-Fahrenheit"));
    }

    void mode3(){
    primary_increment =.1;
    max_value= 25;
    min_value = .5 ;
    float dis_set_temp;
    float dis_temp_offset;
    temp_offset=incr_value(temp_offset);
    FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE);
    if(tscale == 67) {
         dis_set_temp = ((set_temp + temp_calab-32)*5/9);
         dis_temp_offset = ((temp_offset+set_temp + temp_calab-32)*5/9);
        }else{
         dis_set_temp = (set_temp + temp_calab);
         dis_temp_offset = (temp_offset + set_temp+ temp_calab);
        }

    L1();
    lcd_line_two();
    fprintf_P(&lcd_stream, PSTR("Comp ON Temp %4.1f"), dis_temp_offset);
    lcd_write_data(0xdf);
    fprintf_P(&lcd_stream, PSTR("%c"),tscale);
    lcd_line_three();
    fprintf_P(&lcd_stream, PSTR("Set OFF Temp %4.1f"), dis_set_temp);
    lcd_write_data(0xdf);
    fprintf_P(&lcd_stream, PSTR("%c"),tscale);
    L2();
    }
        void mode4(){
        primary_increment =.1;
    max_value= 100;
    min_value = 0 ;
        float dis_warn_temp;
        warn_temp=incr_value(warn_temp);
 FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE);
    if(tscale == 67) {
         dis_warn_temp= ((warn_temp + temp_calab-32)*5/9);
        }else{
        dis_warn_temp= (warn_temp + temp_calab);
        }

    L1();
    lcd_line_two();
    lcd_write_string(PSTR("  High temp warning"));
    lcd_line_three();
    fprintf_P(&lcd_stream, PSTR("   Set Temp %4.1f"), dis_warn_temp);
    lcd_write_data(0xdf);
    fprintf_P(&lcd_stream, PSTR("%c"),tscale);

    L2();
    }

        void mode5(){
        primary_increment =.1;
    max_value= 15;
    min_value = -15;
    float dis_frig_temp;
    temp_calab=incr_value(temp_calab);
 FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE);
    if(tscale == 67) {
        dis_frig_temp = ((frig_temp + temp_calab-32)*5/9);
        }else{
        dis_frig_temp = (frig_temp + temp_calab);
        }

    lcd_line_one();
    lcd_write_string(PSTR("Home  calibrate  inc"));
    lcd_line_two();
    lcd_write_string(PSTR("Set actual Temp now"));
    lcd_line_three();
    fprintf_P(&lcd_stream, PSTR("   Set Temp %4.1f"),dis_frig_temp);
    lcd_write_data(0xdf);
    fprintf_P(&lcd_stream, PSTR("%c"),tscale);

    L2();
    }
    void mode6(){

  FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE);

    float on_perc = ((((float)on_time_min +((float)on_time/6000))/((float)time_min +(((float)the_time)/6000))) * 100);
    lcd_home();
    lcd_line_one();
    lcd_write_string(PSTR("Home Min  Max   % "));
    lcd_line_two();
    fprintf_P(&lcd_stream, PSTR("ON  %3.1f %4.1f %3.1f"),(float)((float)on_min/6000),(float)((float)on_max/6000),(on_perc));
    lcd_line_three();
    fprintf_P(&lcd_stream, PSTR("OFF %3.1f %4.1f %3.1f"),(float)((float)off_min/6000),(float)((float)off_max/6000),(100 - on_perc));

    lcd_line_four();
    lcd_write_string(PSTR("Mode DutyCycle Reset"));
    }

    void mode7(){
    primary_increment =1;
    max_value= 6000;
    min_value = 0 ;
    watts=incr_value(watts);
  FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE);
 lcd_home();
    float on_hrs = (((float)on_time_min  + ((float)on_time /6000))/60); 
    lcd_home();
    lcd_line_one();
    lcd_write_string(PSTR("Home  Power Use  Inc"));
    lcd_line_two();
    lcd_write_string(PSTR("Hrs    Wates   KWh"));
    lcd_line_three();
    fprintf_P(&lcd_stream, PSTR("%5.1f  %4.0f    %3.1f"),on_hrs,watts,(on_hrs*watts/1000));
    lcd_line_four();
    lcd_write_string(PSTR("Mode  Set Wates  Dec"));
    }

    void mode8(){
    primary_increment =.0001;
    max_value= 1;
    min_value = 0 ;
    price=incr_value(price);
  FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE);
    float on_hrs = (((float)on_time_min  + ((float)on_time /6000))/60); 
    lcd_home();
    lcd_line_one();
    lcd_write_string(PSTR("Home  Power Cost Inc"));
    lcd_line_two();
    lcd_write_string(PSTR("KWh   price   cost"));
    lcd_line_three();
    fprintf_P(&lcd_stream, PSTR("%3.1f   %4.4f   %5.2f"),(on_hrs*(float)watts/1000),price,((on_hrs*(float)watts/1000)*price));
    lcd_line_four();
    lcd_write_string(PSTR("Mode  Set price  Dec"));
    }

        void mode9(){
    lcd_line_one();
    lcd_write_string(PSTR("Home         Cancel"));
    lcd_line_two();
    lcd_write_string(PSTR("   Confirm reset "));
    lcd_line_four();
    lcd_write_string(PSTR("              Reset"));

    }
    void L3(){
        lcd_clear_and_home();
        lcd_line_two();
    lcd_write_string(PSTR("     Compressor"));
    lcd_line_three();
    }

void set_relay(){

    if(frig_temp < set_temp) { // frig is cooled  turn off relay
            while(ADCSRA & (1<<ADSC)) {
    // do nothing... just hold your breath.
  }

        PORTC &=~(1<<PC2); //turn off "start up pending " lcd
        if (PORTC & (1<<PC4)) {
        ADCSRA &=~(1<<ADEN); //turn off ADC while switching relay
        L3();
        lcd_write_string(PSTR("    Shutdown Mode"));

        PORTC &=~(1<<PC4);// insure compressor relay is off
        delay_ms(2000);
         ADCSRA |=(1<<ADEN); //turn on
         lcd_clear_and_home();

         ADCSRA |= (1<<ADSC);
        }
        }
    if(frig_temp > (set_temp + temp_offset)) { //frig is warm turn  on relay 
        if((PORTC & (1<<PC4))==0) { // is  relay is off? 
            if(elap_time>12000){ //is frig is off for at least two minites, for presure to equilize
                while(ADCSRA & (1<<ADSC)) {
    // do nothing... just hold your breath.
  }

            ADCSRA &=~(1<<ADEN); //turn off ADC while switching relay

            PORTC &=~(1<<PC2); //turn off "start up pending " lcd
            L3();
            lcd_write_string(PSTR("    Startup Mode"));
            delay_ms(50);
            PORTC |=(1<<PC4);// compressor relay on
            delay_ms(5000);
            ADCSRA |=(1<<ADEN); //turn on ADC
            lcd_clear_and_home();

            ADCSRA |= (1<<ADSC);
            }else{
            while(ADCSRA & (1<<ADSC)) {
    // do nothing... just hold your breath.
  }
            if((PORTC & (1<<PC2)) ==0){
            while(ADCSRA & (1<<ADSC)) {
    // do nothing... just hold your breath.
  }

            PORTC |=(1<<PC2);//turn on "start up pending" lcd
            }
            }
            }
            }
    }
void chk_temp_warn(){
    if(frig_temp> warn_temp){
            while(ADCSRA & (1<<ADSC)) {
    // do nothing... just hold your breath.
  }
        PORTC |=(1<<PC3);  //Warn lcd on
        warn_timer++;
        if(PORTC & 1<<PC5){

            if(warn_timer>=50){
                PORTC &=~(1<<PC5);//light off

                warn_timer=1;
                }
            }else{

            if(warn_timer>=30){
            Light_time=0;
            PORTC |=(1<<PC5);  //light on
            warn_timer=1;
                    }
                }

        }else{
            while(ADCSRA & (1<<ADSC)) {
    // do nothing... just hold your breath.
  }
        PORTC &=~(1<<PC3);//warn lcd off
            }
}

int main() {

// start up the Analog to Digital Converter
  adc_init();

   DDRB &= ~(1<<PB1); // set PB1 as input
    DDRB &= ~(1<<PB2); // set PB2 as input
    DDRB &= ~(1<<PB3); // set PB3 as input
    DDRB &= ~(1<<PB4); // set PB4 as input
    DDRB &= ~(1<<PB5); // set PB5 as input

// set up timers    
    realtimeclock_setup();
EIMSK = 0 ;// disable pin change interrupts
// activate pull-ups
  PORTB |= (1<<PB1) | (1<<PB2) | (1<<PB4) | (1<<PB5) | (1<<PB3);
// set  for output
    DDRC |= (1<<PC4) | (1<<PC5) | (1<<PC3) |(1<<PC2) ;
//enable interrupts
sei();

lcd_init();

// set variables defaults

 the_time = 0;
 time_min=0;

    elap_time=0;
    on_time=0;
    on_time_min=0 ;
 auto_inc_ct =0;
    light_timer =1500;
  uint16_t last_sample = 0;
  float this_temp;
     set_temp = 34 ;
     Light_time=light_timer;
    cmode =1;
    Lchange=0;
    button_time =0;
    uint8_t ti = 0;
    Lstate = 0Xff;
    comp_was = 4;
    tscale = 67;
    temp_offset = 3.00;
   warn_temp = 40;
   on_min =599400;
   off_min = 599400;
   off_max = 1;
   warn_timer=0;
   on_max =1;
   temp_calab =0;
   on_time = 0;
  rec_high_temp= -10; 
     rec_low_temp = 100;

   watts = 130;
   price = .10000;

  while(1) {

// Read temp    take 100 samples and average them!
    if((ti< 100) && (ADCSRA & (1<<ADEN))) {     
      last_sample = adc_read();
      this_temp = sampleToFahrenheit(last_sample);
      // add this contribution to the average
      temp_avg = temp_avg + this_temp/100.0;
      ti++;
          }else{
          ti=0;
          frig_temp= temp_avg;
          temp_avg =0;
            if(frig_temp < rec_low_temp) {
            rec_low_temp = frig_temp;
            }
            if(frig_temp > rec_high_temp) {
            rec_high_temp = frig_temp;
            }
          }

    //check for power
   chk_powr(); 
//Chk_Buttons
    chk_buttons();

set_relay();
chk_temp_warn();
//display_mode

  switch(cmode)  {
    case 1:
    mode1();
    break;

    case 2:
    mode2();
    break;

    case 3:
    mode3();    
    break;

    case 4:
    mode4();    
    break ;

    case 5:
    mode5();
    break;

    case 6:
    mode6();
    break;

    case 7:
    mode7();
    break;

    case 8:
    mode8();
    break;

    case 9:
    mode9();

    }

  }

  return 0;
}

thanks Darryl

March 22, 2011
by Noter
Noter's Avatar

I went through your code and I don't see anything that would cause an unexpected reset. Previously you said when the temp sensor wire was longer the reset occured with greater frequency. I think that is an indication that it is an EMI issue. I know you tried the reset pin protection that was in the atmel doc but did you use a Schottky diode? Maybe regular diodes are not fast enough. I would pursue that protection circuit some more. What value of capacitor and resistor did you use?

It's hard to know if the EMI is coming from the motor or the relay's or both. Maybe another approach using triac's instead of relays would reduce EMI enough to keep it running. If you could do a reset test without the relays in the circuit that would certainly show if they are an issue or not but I don't know if you have an alternative to switch the compressor on/off.

Just thinking out loud. If I come up with another idea I'll send it your way.

March 23, 2011
by sask55
sask55's Avatar

Notor

I am now very confident that the issue is hardware related, as you have said. Over the last day my project board running on top of the frig with a simple delay loop (see code below) has rest a number of times. This board is connected to the relay that is connected to the frig but would never activate the relay as there is no software on board to do that. The frig compressor is controlled by the mechanical temp control in the frig.

The project board resets even when the relay is not activated or not even connected. 
My application software running on a basic board does not reset.
simple delay loop running on my project board reset.    
The frig compressor starts up with a high amperage surge, in the order of 12 to 15 amps  as measured with a clamp type AC ammeter. It draws about 1.3 amps when running.

With regards to the reset pin protection I am currently using. 10K pull-up resistor 4.7 nf filter capacitor 1n4148 Diode- this diode is not described as a small single but as a High conductance fast diode. The Data sheet shows a reverse recovery time of 4 ns.

I have considered ordering some small single diodes and giving that a try. However after looking over a few data sheets there are not many diodes that are faster then the 1n4148. I could try a SD101 they have a 1 ns reverse recovery time. Since I am in a rural area I order all my parts. I am making up a list of items for my next order.

code on chip that occasionally resets.

// initialload.c

// for NerdKits with ATmega168
// mrobbins@mit.edu

#define F_CPU 14745600

#include <stdio.h>

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <inttypes.h>

#include "../libnerdkits/delay.h"
#include "../libnerdkits/lcd.h"
#include "../libnerdkits/io_328p.h"
// PIN DEFINITIONS:
//
// PC4 -- LED anode

int main() {

  // fire up the LCD
  lcd_init();
 FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE);
 lcd_home();
 uint8_t sec = 0;
  uint8_t min = 0; 
  uint8_t hr = 0;

  // print message to screen
  //             20 columns wide:
  //                     01234567890123456789
lcd_home();
                  lcd_line_one();
  lcd_write_string(PSTR("  Congratulations!  "));
  lcd_line_two();
  lcd_write_string(PSTR("********************"));
  lcd_line_three();
  lcd_write_string(PSTR("  Your USB NerdKit  "));

  while(1) {
    // set up roughf time indicator no interupts in play
    for(hr=0; hr<100; hr++){
        for(min=0; min<60; min++){
            for(sec=0; sec<60; sec++){
            delay_ms(1000);

  lcd_line_four();

            fprintf_P(&lcd_stream, PSTR("%dHr   %dMin   %dSec"), hr,min,sec);

            }

        }

}   
  }

}

thanks again Darryl

March 23, 2011
by bretm
bretm's Avatar

Could be anything--even an oxidized connector in the breadboard causing intermittent connectivity. Try shifting everything on the breadboard down one row.

March 23, 2011
by Noter
Noter's Avatar

I live out of town in a rual area too so I know what you mean about ordering everything.

Since my last comment I saw an example that used the same components on the reset pin except a 10nf cap instead of the 4.7. If you had a 10nf you could try it in there.

Seems the only source of EMI that you haven't protected against is the temp sensor wire. Maybe a big enough surge on that wire is more than the intermal diodes can handle or more than the chip can dissapate quick enough to prevent problems. I'd put external clamping diodes on that wire (as close to the avr as possible) to keep a transient voltage surge from getting into the chip?

I assume you still have your other protection diodes in place.

March 23, 2011
by sask55
sask55's Avatar

Bertm

I have had the same results on three completely different layouts of the circuit. Two of them on breadboards using different component pieces including the actual breadboard, and one soldered on a perf board layout.

Darryl

March 23, 2011
by sask55
sask55's Avatar

Notor

I do have the protection diodes in place. I have now swapped out the 4.7nf cap for a 10nf that certainly seams worth a try. As you suggested I have put a couple of diodes on the temp sensor input lead. As you know by now it often takes a while to determine if the problem is resolved. I will post the outcome as things develop.

Darryl

March 23, 2011
by sask55
sask55's Avatar

Noter

Sorry to report things have not changed resets are still occuring.

Darryl

March 24, 2011
by Noter
Noter's Avatar

Well, I'm running out of ideas to overcome the reset from a hardward perspective.

What about making a few changes to your application so it can survive the reset? You could write needed data to eeprom or flash before you switch the relay and then on reset read that data back to resume operation. I guess you'd miss a second of real time while all that happened but you should be able to resume without having to set up again or loosing the data you've been collecting.

March 24, 2011
by Ralphxyz
Ralphxyz's Avatar

It seems that the reset has to be caused by EMF effecting your circuit, not the Nerdkit breadboard per. se. as the initialload project runs minus the resets. You have to break your circuit down, what works, can you have a wired mcu with one transistor flashing a led not be reset?

Can you then have that transistor trip a relay to flash a LED, sorry but circumstances force your solution into tedium solutions.

You have to isolate what works (is not effected by resets) from what does not work. There is a piece of wire going to something that is acting as a antenna picking up the EMF what is that something?

I had thought as Noter suggested that you could use EEPROM to save data and settings the mcu has 512 bytes of internal EEPROM that is relatively easy to program or you could use a external EEPROM. This would save your data between resets it we cannot find the solution.

Ralph

March 24, 2011
by Noter
Noter's Avatar

On second thought, I guess a reset turns off the relay so it doesn't matter if the program can more or less resume where it left off.

March 24, 2011
by sask55
sask55's Avatar

Thanks fellows

I see where you are going with the EEPROM idea, which would no doubt work on this project. This project was intended as basically a stepping stone for me. I think I have learned a lot about a few potential issues I have in a much more ambitious project that I am slowly working towards. Most relevant and important, I see now that I should not depend on the MCU itself to maintain any long term data, I have to design with the possibility of occasional resets in mind. My idea of using a battery as a power loss backup is not the answer the project must continue to function as planned after resetting. This should not present any problems as there will be a PC communicating with the MCU or possibly 2 MCUs if I ever get my idea of the ground. I am confident that I can handle the data storage on the pc. I wish I could say the same about possible EMF issues. I have successfully completed a number of projects involving the uart communications, both reading decoding data streams from digital callipers (I posted part of that calliper project to the Nerd kits forum) and controlling multiple stepper motors with a PC. My motivation for continuing with this project, as it is, was to learn as much as I could. When the resets presented as a problem I felt it was an excellent opportunity to get some experience dealing with EMF issues so that I would be better equipped to deal with them if they become a problem. To that end I think I have learned a great deal.

I am going to switch my focus, back to where I was before I decided to resolve the reset issue. Originally I was intending to use pin 23 on my project board for a second analog input. I am hoping to incorporate an AC amperage sensor (ammeter) that would monitor the power consumption of the frig compressor. I want to get some experience using more then one ADC pin on the same chip to measure analog information. I have plenty of time in the winter to work on these ideas , but in the summer months my real job (farming) takes most of my time. Soon I will be getting into a very busy season and may not find much time to do much hands on electronics. What I would eventually like to accomplish is to develop the hardware, software and algorithm for a PC based system to control aeration/drying fans on grain storage bins. This is not a trivial task from any standpoint. As I envision it, at minimum the system would require a temperature and a relative humidity sensor at a bin roof air vent. A second temperature and relative humidity sensor and possibly an air mass flow sensor in the fan plenum, some 20 to 30 feet apart. An ammeter on the fan to track power consumption, which would relate to static head and therefore air volume. Controlling the fan would involve controlling the electric motor contactor relays that are used to close the ac power to the fan motors (typically 3 to 10 hp-240 volt depending on the bin size). The PC software would be required to track and record all of these measurements as well as the grain temperature reading that are available on a separate pre-existing grain temp monitoring system in the bin. The algorithms to determine when to turn on or off the fan would be extremely involved considering a multitude of factors. Truthfully it is not likely I will ever by able to accomplish all that especially when I consider how much trouble I had dealing with the EMF from one little frig compressor, but I do enjoy working on this kind of thing and you never know it might just work.

I am not in a hurry. I do this when I find the time. Sorry for being so long winded I am just trying to give you a perspective.

Thanks again Especially Paul and Ralph; your help is very much appreciated

March 25, 2011
by Noter
Noter's Avatar

Darryl,

That sounds like an neat project. I hope you keep us informed on your progress as you work towards your end goal.

If you don't have a logic analyzer/scope combo or something to view the signals on the wire you may want to consider gettting one. I think you're at the stage where you may need a tool to view what is really happening to overcome the EMF problem and who knows what else in the future. From what I've been able to find and read on solving EMF issues is that there is a lot of lab observation (trial and error) beyond theory and design to arrive at a good solution.

Paul

March 25, 2011
by Ralphxyz
Ralphxyz's Avatar

Darryl, by the time this farming season is over I should have my weather station running that will have most of the components except for the current sensing (I think I do have a hall effect current sensor in my parts drawer though) that you will need. So definitely keep us posted on your progress and stay tuned, search the forum for "Multi Sensors". I did 4 or 6 temperature sensors, If I could do it you know it has to be fairly simple.

We all (well I have) have learned a lot about EMF this has been a very interesting thread. I really wish you had found a definitive answer.

Ralph

March 25, 2011
by sask55
sask55's Avatar

I have seriously considered a logic analyzer/scope a couple of times. I am not sure if this is the place to ask but does anyone have any comments on what to look for or what to avoid. There is a wide range of prices out there It would be best to get something that is likely to be more then adequate for most applications that I might have without going over board with all kinds of features I am not likely to ever make use of. I realize it is not possible to know now what I may want in the future but I don’t have much of a feel for what I am really looking for.

Darryl

March 25, 2011
by sask55
sask55's Avatar

I may have ot ahead of myself , there seams to be a considerable number of posts on this topic in the forum already I will have a closser look at them.

Darryl

March 25, 2011
by BobaMosfet
BobaMosfet's Avatar

Darryl,

Ralphxyz just got a scope, and that same model is perfect for what you are trying to do, and almost anything else. I agree with Paul-- you are really flying blind without some way to capture and analyze voltage "events" over time.

I personally do not believe this is an EMI/EMF issue- the things you've done to fight that issue and yet it persists, tell me this is something else. A relay is a coil. I suspect the relays are drawing too much current, or you are getting back-current and need a flyback diode on each relay.

I believe that you are either experiencing an over-voltage or an under-voltage condition that is causing either the LM7805 to drop to protect itself, or the MCU to protect itself (or simply get underloaded/overloaded and reset).

I think your silo project is well with in your capability- but not without a scope. You must specifically identify your problems and deal with them- guessing is pointless as the forms in which trouble occur are multitudinous.

Please keep us informed on your projects, and good luck!

BM

March 25, 2011
by sask55
sask55's Avatar

BM

The project has reset dozens of times when the relay is not in control of anything and was not activated by the project circuit. It is not the activation of the relay that will cause a reset it is the starting or stopping of the compressor motor. I have run the project (relays and all) for days without any resets. But when I set the project is on or near the frig and run my code or the initialload code I get the occasional reset, even if the 110 volt frig compressor wires are not connected to the relay in any way. The resets that I have been present for always happen when the refrigerator compressor is either starting up or stopping but certainly not every time it starts or stops. There is absolutely no question that the resets are related to the actual compressor cycling not the project activating the relays. I have cycled the relay from the project board dozens of times the only time it resets is when the frig comp. is actually staring or stopping. I am certain I could unplug the AC to the frig and I would never get a reset by cycling the relay.

The relays themselves draw about 33 mA each, there are flyback diodes on the relays at the relay boards. I have used four different lm7805 and three different MCU chips. It is not necessary for the project to be connected to anything to see occasional resets. Again I have seen plenty of resets when the project board is not connected to an ac adapter, (running on a battery) therefore no voltage supply to the relay. With the temp sensor in the frig and the relay connected to the main project board but not the frig, all that is required is to turn on the normal refrigerator control and have some patients eventually the board will reset when the compressor is either started up or stopped by the normal operation of the frig. Sometimes it may take 10 minutes other times it could be many hours’ hens the need for an indicator on the project screen to determine if a reset has occurred when I was not monitoring the screen. How could this not be an EMI/EMF issue? The project resets are totally related to what the compressor is doing and not related at all to what the project is doing and no electrical connection between the frig and the project is required.

Darryl

March 25, 2011
by sask55
sask55's Avatar

One interesting thing that I have determined in the last couple of days, is appears both the temp sensor cable and the relay cable seam to be contributing to the issue. If I let the original frig control run the frig and remove ether the entire temp sensor cable or the entire relay control cable resets are far less frequent. I tried disconnecting just the relay signal wire at the board I still get the occasional reset when I disconnect the 12V power wire and the ground that go the relay board as well I have not seen a reset yet. So it appears that at least part of the problem is arriving at the project board on the relay power conductors. I happened to have a couple of 1N4744 (15 volt zeners) on hand I though that perhaps I could clip at least part of a voltage spike (if that is the issue) if I put one across the 12 volt supply this did not change anything.

Darryl

March 26, 2011
by Ralphxyz
Ralphxyz's Avatar

Darryl, is there anyway to add shielding to the frig contactor (switch)?

Ralph

March 26, 2011
by sask55
sask55's Avatar

Ralph

There is a drawing of the electrical layout and schematic on the back of the frig. I am posting a photo of it hear. There is no separate motor control contactor (magnetic relay) in the frig circuit, although it does have the word “relay” on the schematic. It is not a relay in the sense that a smaller current control signal is closing the high amperage compressor circuit. In any event this “relay” that is shown on the schematic is mounted on the side of the compressor itself, it is enclosed in a metal box. It is more or less an integral part of the compressor.

This refrigerator is a frig only unit with no freezer and therefore very simple. Just the interior light, the door light switch, the compressor, an overload protection circuit breaker, and the mechanical temp control. The mechanical temp control does have an off position. I have the project relay in parallel to the mechanical control between the red (power) and neutral wires near the compressor. The compressor is energized by closing ether the project relay or by the mechanical frig control closing the circuit. The full electrical draw required to run the compressor is switched at the relay or the frig temp control (about 12 amps start up 1.3 amps running). In my current setup these two contact point are physically quite far apart. The project relay is outside and behind the frig near the compressor on the concrete floor behind. The mechanical frig control in inside the frig wall near the top, with the control knob on the inside wall. It does not seam to matter how (where) the contact is made to start or stop the compressor, the relay, the mechanical control, or by plugging and unplugging the frig. I have seen resets from all three contact locations. I guess what I am saying is it does not appear to be the actual switch causing the problem as I can leave the mechanical control closed and get occasional resets by plugging in or unplugging the frig. It seams to me that in problem must be originating from the compressor/relay/overload protection unit, they are one totally enclosed unit.

Darryl

March 26, 2011
by sask55
sask55's Avatar

sorry; I misstated the connections for my project relay. It is in parallel with the frig control as I said but not connected to the neutral wire (that would be a dead short) it is in fact connected to the black hot (power) line and the red (load) line.

Darryl

March 26, 2011
by BobaMosfet
BobaMosfet's Avatar

Darryl,

I'm sorry, I missed some things along the way in this thread. My time is very scattered right now and not much sleep, so thank you for the summary. I've gone back to the beginning and read the entire thread from start to finish.

First of all, EMI/EMF is a capacitance/reactance issue. The length of your wires, acting as antenna, will 'catch' a certain amount of stray current-- like what you are describing. Secondarily, your sensors out at the ends may not be entirely reliable, because (like the LM34), they are not intended to operate out at a significant length of wire, without a capacitor there to lift the sag and provide stable current and voltage to the sensor.

As for the capacitance issue on the wire itself, use an appropriately sized pull-down resistor to ground all such EMI/EFI, and furthermore, TWIST your pair. This is exactly why UTP exists in CAT5 - to eliminate cross-talk and EMI/EMF interference.

Hope that helps.

BM

March 26, 2011
by BobaMosfet
BobaMosfet's Avatar

Wouldn't it be easier to simply cut their thermostat out, and use your ATMEGA328, the LM34, and an SCR to control their former thermostat leads?

BM

March 26, 2011
by sask55
sask55's Avatar

BM

At first I was going to cut the thermostat out, but thought I would just as simple to connect it in parallel and leave it turn off. It would be a kind of a backup system in case my project failed in some way I could always just start using it again. Now I am glad that I left it in as it allows me to very simply switch control away from my project and therefore get plenty of opportunity to monitor the project running on or near the frig without actually controlling the compressor. I was also seriously considering cutting into frig door on this old frig and mounting the screen and buttons flush in the door just to make it look built in. I’m glad I never did that before I determined how this thing is working. It would be very simple to remove the wires from the connectors and eliminate the thermostat from the circuit; electrically I do not think that is any different then turning the thermostat to the off position.

Darryl

March 26, 2011
by Ralphxyz
Ralphxyz's Avatar

Once you have this project running I would leave the thermostat turned on a few degrees cooler than your project setting to act as automatic backup.

Ralph

March 26, 2011
by sask55
sask55's Avatar

Ralph

I could just leave the thermostat seta as cold as it will go. It would nerver activate the relay as long as the project was working. One of the reasons that I am using this old frig for this project is that it works fine but runs very little, an indication that the thermostat is not functioning as it should. 5 or 6 deg C is about as cold as it will maintain the frig, that is to warm. I have tried there is no replacement thermostat available. My project does a much better job at maintaining a nice cold frig then the malfunctioning thermostat does.

Darryl

March 26, 2011
by BobaMosfet
BobaMosfet's Avatar

Darryl,

Make sure you have your bypass capacitor on the power-input lines on the MCU as close to the MCU as possible; This current loop has to be very small, otherwise it's susceptible to voltage spikes due to EMI. When one reads the datasheet, the current on the input pins is actually only the AVERAGE current. It may be significantly higher, depending on how many pins are being used for output.

I'm very concerned about two things--

  1. Your long conductors to the sensors-- these are surely an inductive/capacitive issue. The only truly effective way to deal with this is use an appropriately sized zener to ground. Very high speed. and
  2. How the reset pin is wired. You might try changing the setup on the reset pin slightly. Instead of connecting directly to Vcc, you might put a 10K Ohm pull up resistor in parallel with the Vcc and Reset pin, AS WELL as a small 4.7nF capacitor from Reset to GND. Furthermore, add a small signal diode from Reset to Vcc, in parallel with the resistor, but closer to the MCU. Put the anode toward the Reset pin. This setup provides you with the proper protection while still making it possible to perform in system programming.

Hope this helps!

BM

March 27, 2011
by sask55
sask55's Avatar

BM

Noter had brought the reset pin protection idea to my attention a while ago. I am running the project with the changes you described it still had occasional resets.

With regards to the zener diode goes, I have a 15 volt vener across the 12 volt supply. I have looked around a bit. It is uncommon for the zener datasheets to list a speed. Therefore I don’t know how to order a fast one. Thanks anyways; those both did seamed like very promising ideas when I tried them.

I Think I am getting very close, my project has been ruining the frig for about 20 hours with no resets. I don’t know why I never thought of this before. I did two things that seams to help. In this project there is no good reason why the relay cable needs to be so long. I moved the relay up near the main project board and ran the 120 volt cord up to it. On my first attempt I had the relay very close to the project board, this actually made the reset problem most frequent. I reasoned that the EMF coming off the relay itself may be an issue. I then separated the relay from the project board with a short 2 foot “shielded-twisted pair low voltage computer cable”. So far so good.

I do have the feeling that this project is just barley stable, kind of balancing on the brink of a reset and probably will reset occasionally. I don’t think I will worry about that I can work with the occasional reset if I know to expect them. I am waiting on an order of components and will be switching my focus.

I will be getting a scope/analizer soon. I have not found the time for a detailed look at what I want.

thanks Darryl

March 27, 2011
by BobaMosfet
BobaMosfet's Avatar

Darryl,

The zener I mentioned is not for your power-supply, it's for your leads going to your sensors- if they pick up a large spike, a zener will effectively route the excess to ground, so it never hits the MCU. Something like a 1N5231B.

Any length of wire should be (at the very least) twisted- this helps eliminate crosstalk and EMI-- that is in fact why they twist it.

One other thing I don't think anyone mentioned, is you should ground any rows on your breadboard that are not being used- your breadboard acts as a screen antenna itself (capacitance) and this can throw off the whole thing in a noisy environment.

As for getting a scope, I've provided a lot of solid advice on scopes in the forum, as have other people here, to help people make good decisions about what scope to get and why-- things that either a) aren't obvious up front, or that will help you save money. I use an old TekTronix TDS360 that I got practically new, and has a 200MHz (1GSa/s) upper rate at 400V. I'm fairly certain I won't ever need anything faster.

Thanks for sharing this project-- more power to you!

BM

March 27, 2011
by Ralphxyz
Ralphxyz's Avatar

Darryl, here is the link to my on going oscilloscope thread. So far I am very pleased with my purchase.

Ralph

April 01, 2011
by Noter
Noter's Avatar

Hey Darryl,

I just learned about the MCU Status Register and thought it might help you figure out your reset issue. Look at 10.9.1 MCUSR – MCU Status Register in the ATmega328 datasheet and then change your program to query the value when you start up and maybe knowing the type of reset will help with resolution.

I know you're probably busy and not working on your project these days but maybe save this tidbit for the next time you get to it.

Paul

April 01, 2011
by Ralphxyz
Ralphxyz's Avatar

So Noter is the MCUSR stored in flash so that you can see a code denoting the previous reset?

And yes I will look at the specsheet 10.9.1 I remember seeing it before but had no comprehension of what it was talking about.

Ralph

April 01, 2011
by sask55
sask55's Avatar

Paul I am looking over the reference you made on the ATmaga data sheet. I like Ralph I had also looked at this information before but never real understood what it meant or what I could do with it. Although it does not actually say how it is possible it seams to imply that this register will hold the information about the last reset thru the reset itself. I think you are correct this could be very revealing I will be doing some more tests.

I had to locate a newer version of the datasheet to make sense of your 10.9.1 reference. In have been using a pdf file version of the datasheet that I had downloaded from the NerdKits downloads site, last year. In that version of the data sheet the reference to the same information is 8.9.1 This is another lesson learned for me. That is;in some cases it may be important to have the most current version of the datasheet available, as apperently changes are made to datasheets.

thanks Darryl

April 01, 2011
by Noter
Noter's Avatar

Apparently the MCUSR register holds the type of the most recent reset and to see it all you would need to do is print it out to the LCD display. Or you could get fancy and test the bits to print out the name of the reset. I'll give it a try over the weekend and let you know what I find. Or if either of you get to it first, post your results.

April 02, 2011
by sask55
sask55's Avatar

I have been running the fridge for a couple of hours now with a print out to the LCD reporting the status of the MCUSR register as Paul suggested. I have had three resets, all three were bit 2 (Brown-out flag set) resets. I have placed some code in the project code to set MCUSR to 0 (clear the MCUSR register) by pushing the light button on my fridge panel. This is working well I can clear the register any time, no need to shut down the power or reprogram the chip. As before the resets all occurred when the compressor was starting up, I can completely unplug the AC power adapter from the wall the system will successfully go into the battery backup mode and then return to normal operation when I plug in the adapter. No reset occurs with a complete lack of AC power but a brown out reset occurs when the fridge compressor starts up. I am looking thru the datasheet considering this new information.

Darryl

April 02, 2011
by sask55
sask55's Avatar

I have noticed that the MCUSR register can have more then one bit set. If I unhook the battery and unplug the adapter to shut down the project when I restart it I often get two flags set bit 0 and bit 2 (Power-on reset and brown-out reset). When the project is reset by a compressor start up it has always been just the brown-out flag. I thought that I may be able to smooth out Vcc with a slightly larger Cap at the MCU pins (7 & 8). I replaced the .1uf cap with a .33uf it did not seem to have any effect. Perhaps when I get my oscilloscope I will be able to better understand the nature of this issue. I am still trying to digest the brown out reset info in the data sheet.

Darryl

April 04, 2011
by Noter
Noter's Avatar

I guess it's good to know where that reset is coming from. I've been looking at filter circuits and most have more than one capacitor. Usually 3 that are connected parallel to sized something like .1uf, 1uf, and 10uf. I think it means a single large capacitor won't filter out higher frequency noise. This is a pretty good document on choosing capacitor values - http://focus.ti.com/lit/an/scaa048/scaa048.pdf

April 04, 2011
by Ralphxyz
Ralphxyz's Avatar

I had questioned the best use of capacitors and had come across the reference to using three capacitors such as you have listed.

Apparently you also want to have the smallest capacitor closes to the mcu.

Using the three capacitors seems to make sense.

Parallel Capacitors

"When capacitors are connected in parallel, the total capacitance is the sum of the individual capacitors' capacitances. 
If two or more capacitors are connected in parallel, the overall effect is that of a single equivalent capacitor having the 
sum total of the plate areas of the individual capacitors. As we've just seen, an increase in plate area, with all other 
factors unchanged, results in increased capacitance."

So the 10uf + 1uf +.1uf = a 11.1uf capacitor in total but each of the individual capacitors gets charged (saturated?) at a different time (frequency?) or over a different time period.

This sure has been a interesting thread, sorry Darryl that you are having this problem but I sure am learning a lot from it.

Ralph

April 04, 2011
by sask55
sask55's Avatar

The information on using up to three caps. is interesting. I will likely be trying that if my current experiment fails.

I have always wandered about those cylindrical components are that are offten found on many cables and power cords. I did a little searching and determined that they are ferrites shields. I thought that it may be a good idea to incorporating ferrites shields on the temp and the relay cables. I was lucky enough to find a couple of snap on type Ferrisheilds on a couple of old cables I had. I installed them on the relay and the temperature sensor cables. There is already one in place on the AC power adapter cable. So far there have been no resets with the ferrishields in place. I will keep you posted. This is a link to one of the sites concerning ferrishielding http://www.leadertechinc.com/PDFs/FerriShield_web.pdf

Darryl

April 05, 2011
by sask55
sask55's Avatar

It looks like my project is now running without resetting . This thread has been interesting but very long and at times not very focused. I believe that I have learned a great deal about some of the things to consider when dealing with a possible electromagnetic interferences issue. I do not consider myself an authority of any kind on this topic but feel it may be helpful to summarize a few points that may be helpful to anyone trying to deal with this type of issue. I will list the points in the order that they came to my attention with no regard to how important or how relative they are to the solution for my project. Some of these points may seam obvious to many of you but I think they are worth listing in a more concise manner. This list is not intended to be detailed or complete, but a quick summary of this thread.

 Insure that there is adequate size of capacitors around the power supply. see Mike’s post.
 Try to determine if the problem is hardware or code related by running very basic code on your project hardware setup. If possible run your project code on a very basic hardware setup. Does the problem stay with the software or the hardware?
 Consider disabling the pin-change interrupt if they are not being used as this is has been a known issue.   http://www.avrfreaks.net/wiki/index.php/Documentation:Things_That_Are_Broken 
 Consider protecting the reset pin or perhaps other steps found in this link. http://www.atmel.com/dyn/resources/prod_documents/doc1619.pdf
 Insure that all your connections are good. Consider moving or rebuilding the hardware to reduce the chances that it may be a simple connection problem.
 Insure that all cables connected to the board both, signal and power, are in twisted pair configuration and or shielded. Connect all conductors that are not in use to the ground plain.  Enclose the circuit board in a metal container that is also connected to the project ground. 
 The type of reset can be discovered by polling the MCUSR – MCU Status Register.
 Consider the size type and number of capacitors adjacent to the Vcc and other power pins on the MCU. http://focus.ti.com/lit/an/scaa048/scaa048.pdf
 Consider the use of ferrishields on any cables connected to the project board http://www.leadertechinc.com/PDFs/FerriShield_web.pdf

Thanks Darryl

April 05, 2011
by sask55
sask55's Avatar

In my last post I forgot to mention that I am also using zener diodes (1N5231B) on the temp sensor leads, both signal and power, to try to clip any large voltage spikes that may be present there.

Darryl

Post a Reply

Please log in to post a reply.

Did you know that you can input numbers in binary via a DIP switch, and output them to the LCD? Learn more...