Emergency light switch position sensor

Before everyone who designs an autonomous emergency lighting system, sooner or later, the problem arises of turning on and off the emergency lights. How to do this in the most convenient and transparent way, so as not to spoil the design of the rooms with additional switches?


One of the solutions under the cut.


Background


In the modern world, a lot of things have become tied to uninterrupted power supply. Most types of intellectual activity are already inconceivable without a computer and communications operating 24/7. This is neither good nor bad, it is, and you need to live with it. Especially if your workplace is not in a modern office, stuffed with UPS and backup diesel generators, but in an apartment of an ordinary residential high-rise building. And it so happened that the reliability of energy supply of housing in most cities of the former USSR leaves much to be desired. As a result, the thread connecting the home outlet and the nearest power station has a bad habit of breaking periodically. When once every six months, and when and three times a day.

That is why, when starting repairs in a new apartment, I initially laid parallel wiring in the project for uninterrupted power supply and lighting.

I would very much like to have at my disposal a powerful generator with ICE, capable of providing normal power to the whole apartment, but I had to abandon this idea. In a private house, the question would not have been raised at all, but an apartment is quite another.

The first problem is the removal of exhaust gases, which are absolutely nowhere to put in the apartment of a house with central heating. Well, you won’t throw away the hose just outside the window, where smoke instantly is sucked into the nearest open neighbor's window.

The second problem is noise. Yes, modern inverter four-stroke generators, when you hear them on the street, can seem very quiet. And if you hang an additional silencer, then completely silent. But believe me, in a deenergized, which means completely quiet apartment building, even such a quiet rumble will be perfectly audible to all neighbors.

In short, the idea with the generator died, so plainly and not born. Of the remaining real options, only batteries remained.

Further, I allow myself a simple narrative of my emotional ordeals and the decisions made in the first person without any claim to universal truth. And I immediately warn that my arguments to someone may seem unconvincing, and the decisions made are controversial. But, nevertheless, everything described here is currently implemented in hardware and successfully performs the tasks.

And if anyone is interested in the purely practical side of the issue and it doesn’t matter how I came to such a life, he can skip many letters and go straight to the description of the ready-made solution.

Briefly about choosing the type of battery


And although this issue has nothing to do with the topic of the article, I would like to insert my five cents here too. Moreover, that inevitably arise under such statements discussions often carries a lot of lulz useful information.

Today, in the age of rapid development of alternative energy, relatively affordable industrially manufactured uninterruptible power supply systems for the home, combined with solar or wind mini-power plants, have begun to appear. The most advanced of them use lithium-ion batteries with a whole heap of electronic "enhancers" of the effectiveness of the entire system.

In my case, there can’t be any talk about any mini-power plant for objective reasons, and only the backup source, renewable from an ordinary outlet during “enlightenment”, was interesting. Therefore, it was decided to collective farm all the electronic stuffing of the apartment UPS on their own. And since my hands were completely untied, the first thing that needed to be decided was what type of batteries to use.

At first, I thought like this: “Why not lithium? Stylish trendy youth. Sealed, energy efficient, durable. " But when I looked at the prices, my lithium fervor noticeably subsided. A quick search in combination with school arithmetic showed that even very “dumb” Chinese 26650 banks with (of course) the most honest 5000 mAH will cost five times more than an acid battery of the same energy consumption. And if you choose something not from the bottom of the price sorted by price, the difference easily reaches 8-10 times.

And how can you make up for such a big difference in value?

Yes, lithium stores energy more efficiently for every kilogram and cubic meter, and a battery the size of a cigarette block easily devotes a ten-kilogram lead-acid battery. But is this fact so important for stationary use?

Of course, a good "lithium", but with the right approach will last longer. But ten times?

At the same time, on the other side of the scale, the potential explosiveness of batteries of unknown origin, a more complex charging algorithm, problems with disposal (every homeless person knows where to use a lead battery for profit, while lithium is much more complicated).

In short, by the sum of the factors, I decided to postpone the idea of ​​lithium until the next iteration. Maybe in a few years something will change, but for now, lead is our everything.

, , . , , , .

As for lead batteries, there are also several options. The “right” option is specialized backup batteries, which are used in UPS, at cellular base stations, and other similar places where they are required to be able to take and deliver large currents, occasionally experience a strong discharge, and indeed work without distracting people for service.

Another “right” option is traction batteries for electric auto-loaders or, what the hell, a diesel submarine. These batteries have high durability and good tolerance to deep discharge, while not taking away from the owner the opportunity to "top up some water."

Well, the “wrong” option is the starter battery from the nearest car shop. Such a battery can briefly give up to a kilowatt of power to the mountain, but any discharge is stressful for it, like work for a lazy person. And the glory of disposable batteries is generally entrenched in modern calcium batteries: "discharged - change."

Well, then, I hope no one doubts which option I ultimately selected for implementation? Right, third. And the reasons here lie not only in the well-known warty amphibian, but also in a simple pragmatic calculation. Starter batteries are several times cheaper than all other options, sometimes approaching lithium in value. And instead of shaking over an expensive battery, you feel much freer in a situation of healthy indifference, when the replacement results in losses in the amount of going for food for a couple of weeks. Moreover, if you do not let these batteries run out before losing a pulse, then their service life in the role of backups is calculated for many years. You can always put a battery with a larger capacity, set the discharge limit softer, and still get a better price / capacity ratio than the “right” battery,suffering a deep discharge.

The main thing in this matter is to provide ventilation at least at the “hole in the wall” level at the place of installation of the batteries. Well, to organize a banal short circuit protection, because the low voltage of the current source dulls vigilance and everything can end very badly.

Current war in a single apartment


After some moral reassurance caused by the final decision on the type of battery, a new reason immediately appeared to think carefully.

Let me remind you that initially I wanted to get an alternating current generator of 230 V. However, after reconciling with objective reality and mentally switching to batteries, the inertia of thinking already carried me to the well-known Chinese online market in order to choose a suitable DC to AC converter. And in the process of studying the characteristics, the term “modified sine wave”, which was forgotten, first surfaced, and then common sense began to throw up uncomfortable questions.

The essence of the questions was as follows. To cover all the energy needs of the apartment with a small battery will still not work. Boilers, a microwave, a washing machine, a powerful desktop computer will still be unbearable in power. And the refrigerator, the hood, and even the banal fan will not be able to work properly because of this very modified sine wave. Of course, there are inverters with a true sine wave, but they are not only more expensive, but also less efficient. And the issue of powerful consumers is still not resolved.

What consumers remain within the budget? There are not so many of them: consumer electronics such as laptops and phones / tablets, a router, an ARM server, the mood is a TV, and, of course, lighting. Moreover, the initial message of the article (and my personal motivation) is precisely to ensure the functioning of the backup workstation in the form of a laptop and minimal household comfort, such as light in the toilet.

Almost all of these devices require a constant voltage from 5 to 21 V for their operation and there is no objective need to first increase the battery voltage to 230 V AC, then to lower and straighten it again to plus or minus the initial level. On these transformations, it is easy to lose up to 50% of energy, which I did not smile at all.

In short, that’s how smoothly the idea came to use a low-voltage direct current network as an alternative. And after an approximate calculation of losses in the wires, the initial 12 (13.8) V turned into a more practical 24 (27.6) V.

At first I wanted to take even 36 (41.4) B, but after studying the characteristics of some electronic components that I planned to use to work with all this economy, I had to moderate my appetite.

Thus, in an alternative wiring with a cross-section of 3.5 mm 2 of pure copper, voltage was ultimately applied from two car batteries connected in series.

, . ( ) . , .

To enable consumers in the rooms, one more outlet was added to each “large” block of outlets. And so that no one would confuse an ordinary outlet with a backup one, the “American” type products with flat contacts of different widths were installed as the latter. This, firstly, will not allow the vacuum cleaner to be connected to the DC network, and secondly, such an outlet, unlike the European one, always uses the same polarity when using the “correct” plug.


For these outlets laptop adapters were made, lowering the voltage to the desired 18-20 V and equipped with the corresponding connectors. It is clear that heels were made of the usual five-volt USB-charges for every little thing. Well, just in case, a pair of small 24/230 V converters was purchased, with a power of 50 and 200 watts.

Cases for charging with an American plug, the same power cords, and ready-made boards of pulse down converters were ordered from China. A soldering iron was needed only to connect the wires.

I will not talk about the power plant in this article, especially since there is nothing interesting in it, so I will go right to one of the "bottom" problems, namely the issue of utilizing the energy accumulated by the battery for lighting purposes.

Lighting


So, when wiring the apartment in parallel with the main wiring, wires of an alternative DC network with a voltage of 24 (27.6) V were drawn. Among other things, a loop consisting of a pair of such wires was wound into each switch box and then together with the 230 V network wires led to the ceiling lights (if there were several in the room, then the alternative wire led to only one).

What to do with the output of the DC network in the field of the lamp is a matter of an individual approach. As a light source, a regular 24-volt LED strip was chosen. Its segments of different lengths (in proportion to the area of ​​the room), depending on the design of the fixtures, were either mounted directly in their housings or glued to those surfaces from which it would shine well, and from where it would not be very striking.

In any case, this is a more aesthetic than a technical problem, and now it’s something else.

So, in the box of each switch, I have a loop of a phase wire of a 230 V network for switching on "ordinary" light, and a loop of both wires of a DC network for emergency lighting. From this and dance.

In the end, the challenge before me was to create a certain device that could separate three states from each other:

  • AC mains OK → turn off emergency lights.
  • The AC network is de-energized, the switch contacts are closed → turn on the emergency light.
  • The AC network is de-energized, the switch contacts are open → turn off the emergency light.

We consider the actions to be one-sided, that is, for example, turning off the already turned off lighting just does not change anything. These states can be distinguished from each other if the tasks of determining the operation of the AC network and the position of the contacts of the switch are solved. At the same time, I had the following initial conditions:

  1. Management of both the main and emergency lighting should be completely transparent from one governing body, no “collective farm” of the additional buttons.
  2. , , , .
  3. , .
  4. – , .
  5. - .
  6. ( ), .
  7. .

Of course, the absence of AC mains in the zero boxes turned out to be a very complicated design miscalculation. Without it, the determination of the presence of voltage at the input of the switch becomes impossible. Technically, it would be possible to use the negative wire of a direct current network as zero, but this contradicts the completely indestructible paragraph 5 of my terms of reference.

Sensor


Nevertheless, an alternative to measuring the mains voltage exists. It is not necessary for me to determine the presence of voltage, it is enough to determine the presence of current in the phase wire with the contacts of the switch closed. After all, if there is current, then there is voltage. Moreover, the “reading” of precisely the current allows emergency lighting to be activated not only in the event of a power failure, but also in the event of a banal bulb burnout. This method does not allow to determine the state of the AC network when the switch is off, but this state does not bother me, because once the switch is off, the emergency lighting should not work either.

To determine the presence of current in the wire is quite simple, especially if this current is alternating. Here you can apply, for example, a Hall sensor that detects the magnetic field around the wire. But you can get by with a commonplace current transformer , consisting of a ring magnetic circuit with a winding. An alternating current wire is passed through the ring, which creates a magnetic field in the magnetic circuit. This field in turn induces a secondary current in the winding, proportional to the primary current in the wire. Thus, this simple device allows you to measure the strength of alternating current in any wire, without breaking it and generally without any galvanic connection with the primary circuit.

The work of current clamps, a very useful tool for any electrician, is based on the same principle.

If there is such a transformer near the switch, it is enough to measure the voltage on its secondary winding to find out if any current is flowing in the lamp circuit. The presence of current, as I said, in a first approximation indicates two facts: there is a voltage in the network 230 V, and the switch is closed. The first of these facts is essential for the operation of the emergency lighting activation device.

The second "input parameter" of my future device should be the position of the switch contacts.

The brainstorming initiated by hobby colleagues brought various options for determining the position of the circuit breaker, which basically came down to modifying the design in order to add another pair of contacts to it. Here the scope for imagination is quite large.

It was possible to take a double one instead of a single switch and mechanically “parallelize” its halves so that they became a single whole. This option did not differ in external aesthetics and did not solve the problem in those rooms where the lighting was double-circuit and the switch was double initially.

Other options involved the introduction of a micro switch or a reed switch with a magnet in the switch mechanism. But after studying the designs of the applied circuit breakers, these options also disappeared. The monolithic ceramic base of a good switch simply leaves no chance even for a compact microswitch, and the magnet and reed switch did not work due to too little key travel and hysteresis in the operation / release curve of the reed switch.

«» , . , , , . , , , .

In short, it was necessary to come up with a method that would not require modification of the switch. And this method was found.

Above, I described a current transformer, which allows you to determine the presence of alternating current in a wire without rupture and galvanic contact. But any transformer is a bi-directional device (in contrast to the same Hall sensor), its primary and secondary windings are interchangeable.

If we apply alternating current to the secondary winding of such a transformer, it induces voltage at the ends of the wire threaded into the ring. And, most importantly, the energy consumed by the winding from the source will depend on whether the secondary current in the wire finds its way for circular motion.

And here it becomes more interesting. A wire passes through the ring, which is immediately, in a few centimeters, connected to one of the contacts of the switch. It remains only to provide this current with a return path from the other side of the switch in order to obtain a device for “sensing” the position of the contacts. And for the reason that this current is alternating, a conventional capacitor can become a bridge for it.


In principle, to close this circuit under certain conditions, a capacitor is not needed. If a current of a sufficiently high frequency is “pumped” into the transformer, then the stray capacitance between the wires will be enough for passage.


So, what is needed to organize such a detector:

  1. Current transformer.
  2. Transformer output voltage meter.
  3. Source of high-frequency alternating current.
  4. Current meter flowing through the winding of a reversed transformer.

The most difficult in terms of selecting the optimal parameters is a transformer, which in the current transformer mode should give an acceptable voltage with a frequency of 50 Hz, and in the active “sensing” mode of the circuit breaker state, have an acceptable transmission coefficient at a frequency of hundreds of KHz. This element is not possible to simulate in a program for modeling electronic circuits, and even with mathematical calculation everything turned out to be very difficult. I had to take a soldering iron in my hands and spend hours driving various options in search of the best.

The number of turns and the optimal load resistance were selected empirically and not the fact that I did not miss the best ratio. As a result of the experiments, the following construction appeared:

  • Ferrite core with a permeability of 10,000, size 10x6x4 mm.
  • Winding 30 turns with 0.25 mm enameled wire.
  • The active load of the winding is 1 kOhm.

The magnetic permeability is quite large, probably, it would make sense to use a ring for 5000 or even 2000 units, but in sufficient quantities I had these rings. In general, permeability in this case is a compromise value. Too low makes the transformer unsuitable for operation at a frequency of 50 Hz, and too high spoils everything at frequencies above hundreds of kilohertz.

Multiple experiments confirmed the reality of the idea and the following results were obtained:

  • In current transformer mode, the transmission coefficient turned out to be about one millivolt per watt of flowing power (voltage 220-230 V).
  • In probe mode, depending on the frequency and capacitance of the leak, the current difference with closed and open contacts of the switch reached two to three times.

That's all. Both values ​​are more than sufficient for reliable fixation of both the flowing current, and for determining the position of the switch contacts. It is only up to the specific implementation.


In iron


Unlike most of its other designs, here already in the early stages of deliberation, it was decided to immediately use the microcontroller. Based on the needs and experience, the choice fell on the ATtiny13A. This chip has an ADC, and with the ability to use an internal reference source of 1.1 V instead of the supply voltage. There is a PWM that is great for generating a sounding signal. And, which later turned out to be important, there is an EEPROM that allows you to store calibration data.

, « , , - «» , ».

. . . , , , .

Here you need to combine at least a generator, a voltage meter, and some kind of trigger to store the current state between measurements. In general, any speculative sketch required at least three cases only on the "core", and the controller turned out to be much more practical.

The voltage from the current transformer with a load of 10-20 W is 10-20 mV and it is too small to supply it to the DAC input with a limit of even 1.1 V. Therefore, in addition to the controller, you also need an amplifier with a transfer coefficient of about 100 to increase the signal voltage at least up to hundreds of millivolts.

In general, the voltage of the output signal of a current transformer depends not only on the load power, but also on its nature. A purely active load such as Ilyich’s bulb, for example, gives a millivolt level sine wave. A LED bulb of the same power with simple pulse power gives short bursts to volts and above. We could play on this, but, firstly, I wanted to make a universal device, and secondly, in the apartment there was one lamp with an external power supply unit equipped with a PFC circuit (that is, having a consumption characteristic close to active).

I will not torment the reader with intermediate options and immediately give the final diagram of the device.


Here the DC voltage through the economical linear regulator LM2931-5.0 feeds the controller. In terms of housing, functionality, and pinout, this stabilizer is similar to the popular 78L05, but differs from it in lower intrinsic consumption (about 500 ÎĽA at a load of 10 mA) and greater tolerance to short bursts of input voltage. If you plan to work with a voltage of no more than 20 V, you can use an even more economical analogue of LP2950-5.0.

LP2950-5.0 30 . 24 . - , , , , . 50%, 100%.

The transformer is not shown in the diagram, but its winding is connected to the pins TR1 and TR2.

As a key element for switching the load, a low-current P-channel MOS transistor 2SJ196 is used (a current of up to 1 A should be sufficient for any LED lamp), but any other one suitable for the pinout, maximum current and maximum drain voltage can be used.

In addition to the controller and the key from the active elements, two transistors are used. One is needed to control the shutter of the key, operating under the voltage of the emergency source. The second acts as an amplifier signal from the output of the current transformer.

At this point, you could use op-amps, but in terms of details the gain was minimal, and you would have to forget about working at frequencies above several hundred kilohertz.

It is not the amplified signal from the transformer itself that is fed to the ADC, but its envelope, which can be measured by a single sample, and not by "streaming" digitization for some time. To isolate the envelope, two Schottky diodes are used, connected according to the voltage doubling circuit. Such an inclusion forms a classical amplitude detector, in which the voltage drop across the diodes themselves is largely compensated.

The principle of operation of the sensor is simple. First, consider the algorithm of actions necessary to measure the current in the wire.

In current measurement mode, pin PB0 is put into output mode and is grounded by a logic zero. This prevents any signals from the controller from being sent to point TR1. In parallel, the same actions are performed on pin PB3, as a result of which the top output of the capacitor C2 is grounded. This capacitor together with the resistor R1 creates a low-pass filter with a cutoff frequency of about 1500 Hz. Thanks to this filter, the role of various high-frequency noise in the formation of the measured signal is greatly reduced.

Then a high level is applied to PB4 to power the signal amplifier. After the completion of transients, a current of 50 Hz from the transformer output is amplified and gets to the rectifier, where it charges the capacitor C8.

The charge of the capacitor C8 is measured using ADC1 and from the obtained voltage value a conclusion is drawn about the “primary” current flowing through the transformer.

Active sensing is performed differently. First, pin PB0 is translated into a PWM solver, and a signal is fed to it with a frequency from hundreds of kilohertz to units of megahertz. This signal is somewhat attenuated by a resistive divider and fed to the current transformer winding at point TR1. Capacitor C1, together with one upper arm of the divider R4, creates a low-pass filter with a cutoff frequency of about 1.5 MHz, which reduces the level of high-frequency harmonics from rectangular pulses.

After passing through the transformer winding, the probing signal from point TR2 gets to the same amplifier and detector, likewise in the end charging the capacitor C8 to a voltage proportional to the load in the "external" transformer circuit. In the same way, the capacitor charge is measured using the ADC of the microcontroller.

Now explanations for some "loose".

Resistor R5 is designed to limit the voltage at the gate of the power switch, which for low-voltage MOSFETs should usually not exceed 20 V. In my case, the DC network has a voltage of up to 30 V, which dictated the need for a 1: 3 divider, which is obtained in conjunction with R3. When powered from a source of less than 20 V, resistor R5 is not needed (replaced by a jumper).

Capacitors C4 and C5 are connected in parallel to achieve a capacitance of 2 ÎĽF. This pair of capacitors is noteworthy in that it must transmit signals of both low and high frequencies equally well. Here it would be possible to use a parallel connection of an electrolytic capacitor of several microfarads and a ceramic of a hundred or two nanofarads, but an "electrolyte" of such a small capacity does not give a gain in size when compared with microfarad "ceramics". True, it was not possible to buy a ceramic capacitor at 2 microfarads, so I put two of them the same.

, 50 2 , . , . . 100 , , . .

Resistors R4 and R1 form a voltage divide, which more or less equalizes the five-volt alternating voltage at the PWM output with the output voltage of the current transformer.

Capacitor C8, as mentioned earlier, accumulates the voltage to be measured. It is better if it is a high-quality capacitor with a minimum leakage current.

Special mention deserves the two-pin “comb” TP1 / TP2 connected to the microcontroller reset leg. These contacts are used not just to reboot, but to enter the calibration mode, which is described below. Simply, after the implementation of all the Wishlist, the controller no longer had free pins, and the need to add one simple control appeared during the debugging of the firmware. So I had to use the controller reset foot for this purpose.

«» AVR RESET GPIO. , . , . , , , , RESET.

In general, the circuit turned out to be quite simple, and all the “magic” is implemented in the firmware of the microcontroller. However, after the manufacture of the prototype, it turned out that the wiring capacitance for reliable operation of the "probe" is often not enough. The difference in current through the transformer simply turns out to be comparable with the level of interference and the operation of the circuit becomes unreliable.

Therefore, I had to abandon the ferrite ring freely hanging on the wires, and add a high-voltage circuit directly to the board in a new revision of the device to facilitate the probing task.

The point here is to add a dedicated capacitor, turned on so that the shortest way to close the path to the RF current through the contacts of the switch.


Capacitor C10 must be designed for a voltage of at least kilovolts, and its capacitance should be chosen according to a compromise principle so that the operation reliability is sufficient for practical use, and so that the stray capacitive current through the lamp is not too large. In practice, you can try to "play around" with this denomination, if necessary.

In any case, a switch equipped with such a sensor can no longer be perceived as ideal. Rather, it is similar to a switch with an indicator, therefore, firstly, it can cause stray light or flicker of low-quality LED lamps, and secondly, it can cause an electric shock, though not a strong one. Therefore, you never need to work with lighting wiring, relying only on the switch in the wall, always turn off the “switch” at the entrance.

And, since I still had to add part of the AC network to the board, I added two shut-off chokes there, which will not let the high-frequency probing current pass into the wiring. The practical value of the frequency of the probing voltage can reach several MHz and I, as a radio amateur, are very sick of the idea of ​​increasing the amount of interference in the network with my own hands.

Chokes L1 and L2 must be power, wound with a wire of noticeable thickness on the dumbbell or ring type cores. Signal chokes in the "resistor" axial design cannot be used.

The primary turn of the current transformer is now a piece of wire threaded through the ring and soldered to points TR3 and TR4 on the board. It is better if this wire is shielded, while connecting the screen to TR5 and TR6 on both sides of the ring.

TR6 , . - , . , .


The firmware code and the assembled HEX file are attached at the end of the article along with the circuit and the layout of the printed circuit board.

The algorithm of the tuned detector is simple. Once every three seconds, the controller wakes up from deep sleep, takes measurements, and, if necessary, changes the state of the control key in one direction or another. Thus, the reaction to a change in the position of the switch may have a delay of up to three seconds. Not very convenient, but this is done, firstly, to save energy of the backup source, and secondly, to significantly reduce the polling interval does not allow the duration of transients at different stages of measurement. The minimum interval can be considered equal to one second, but then the circuit will be in active consumption mode almost all the time.

Well, in conclusion, about the configuration. Due to the fact that different sensors have to work in completely different conditions according to the current consumed by the lamp, the length and other wiring features, the level of interference, and the like, it was impossible to put a universal set of adaptive parameters into the firmware. Therefore, each sensor after installation requires a single calibration on site.

The sensor enters calibration mode each time it is turned on, while there is no calibration data, or after closing the contacts TP1 and TP2. Entering the first stage of calibration is indicated by a five-time flashing emergency lamp.

After flashing five times, 7.5 seconds are given to set the switch to the “off” position, if it was turned on before. After this time, the level of interference always present in the AC network is measured. The obtained value is used as a starting point for measurements in the duty cycle. Also at this moment, the circuit breaker is sensed at different frequencies for the subsequent selection of the most "contrast" frequency.

Next, the second calibration stage begins and the emergency lamp flashes twice. 7.5 seconds of time is given to switch the switch to the “on” position and after the timeout the program measures the current consumed by the lamp. If the lamp has several brightness levels, then after switching on, you must immediately switch it to a minimum, so that in the future the sensor will work correctly with any of the available levels.

The beginning of the third and final calibration stage is marked by a three-time flashing of the emergency lamp and requires that the switch remains in the “on” mode and the lighting network is de-energized at a level higher (that is, with the main or secondary circuit breaker on the panel) no later than through the same ones 7.5 seconds In this case, a second sounding of the circuit breaker already turned on at different frequencies is performed and taking into account the values ​​obtained at the first stage, the frequency is selected at which the current difference through the on and off switch is maximum.

Successful completion of the calibration is indicated by a single blinking of the emergency lamp and, if the lighting network after the third stage is still de-energized, by switching on the emergency lighting in the next operating cycle of the survey.

If the measured values ​​of currents and resistances in different conditions are too close and cannot be used for reliable detection, calibration fails. In this case, the emergency lighting lamp blinks twice when the switch position is unsuccessful, or three times when the standard lighting lamp consumption is too low.

In case of persistent unwillingness of the sensor to calibrate with a double blink in the final, you should try to increase the capacity of C10.

Total


The device turned out to be quite simple, compact enough to fit in a switch box, but not to say that it is very easy to configure. Of course, it does not draw on the component of a modern "smart home", because it does not have 5G, cloud control, and even banal WiFi with GPS is not provided. Nevertheless, eight of these devices perform their sole function, and nothing else is required of them in blackout conditions.

Firmware source code (Atmel Studio 7)
#define F_CPU 9600000 //   (  : avrdude.exe -U lfuse:w:0x7a:m -U hfuse:w:0xff:m)

#include <avr/io.h>
#include <avr/wdt.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <avr/eeprom.h>

//#define PROTEUS

typedef unsigned char bool; //   
#define true  (0 == 0)
#define false (0 != 0)

#define MAX_U10BIT 0b0000001111111111 //      

#define INTERVAL         3   //  , 
#define CUR_MINIMAL_DIFF 50  //      , LSB
#define RES_MINIMAL_DIFF 50  //      , LSB
#define FREQ_DIV_OFFSET  2   //     
#define FREQ_MAXIMAL_DIV 6   //     

EEMEM unsigned int  EEPROM_cur_edge;
EEMEM unsigned int  EEPROM_res_edge; 
EEMEM unsigned char EEPROM_frequency_dividor;

unsigned int cur_edge, res_edge; //   ,   EEPROM    
unsigned char frequency_dividor; //   ,   EEPROM    
unsigned char clk = 0; //   watchdog
bool tp_reset = false; //   TP1  TP2

//   
static void init_vars(void) {
  if(MCUSR & (1 << EXTRF)) { // ,       TP1  TP2
    tp_reset = true;
    MCUSR &= ~(1 << EXTRF); //  EXTRF       ,   
  }
}

//  
static void init_pins(void) {
  DDRB |= (1 << PB0) | (1 << PB1) | (1 << PB2) | (1 << PB4); //       
}

//    watchdog
static void init_interrupts(void) {
  sleep_enable(); //   

  WDTCR = (1 << WDCE) | (1 << WDE); //  watchdog
  WDTCR = (1 << WDTIE) | WDTO_1S; // watchdog      ,  1 

  sei(); //  
}

//   
void init_settings(void) {
  cur_edge = eeprom_read_word(&EEPROM_cur_edge); //   
  res_edge = eeprom_read_word(&EEPROM_res_edge); //   
  frequency_dividor = eeprom_read_byte(&EEPROM_frequency_dividor); //   
}

//   
static void toggle_load(bool state) {
  if(state) {
    PORTB |= (1 << PB1);
  } else {
    PORTB &= ~(1 << PB1);
  }
}

//  
static void blink_load(unsigned char count) {
  for(unsigned char i = 0; i < count; ++i) {
    _delay_ms(200);
    toggle_load(true);
    _delay_ms(200);
    toggle_load(false);
  }
}

//   (   )
static void stop(void) {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  while(true) sleep_cpu();
}

//   
static void toggle_amp(bool state) {
  if(state) {
    PORTB |= (1 << PB4); //     PB4
    _delay_ms(250);      //       200 .
  } else {
    PORTB &= ~(1 << PB4);
  }
}

//  
static void toggle_lpf(bool state) {
  if(state) {
    DDRB |= (1 << PB3); //  PB3    (  "0")     C2
  } else {
    DDRB &= ~(1 << PB3); //  PB3    ( )   C2  
  }
}

//    
static void toggle_gen(bool state) {
  if(state) {
    TCCR0A |= (1 << COM0A0) | (1 << WGM01); //    ( )    OC0A      OCR0A
#ifndef PROTEUS
    TCCR0B |= (1 << CS00); //    1
#else
    TCCR0B |= (1 << CS00) | (1 << CS02); //    1024
#endif
    OCR0A = FREQ_DIV_OFFSET + frequency_dividor; //   ,         OC0A
  } else {
    TCCR0A = 0; //  
  }
}

//  
static void toggle_adc(bool state) {
  if(state) {
    DDRB &= ~(1 << PB2); //  PB2    ( )
    ADMUX = 0b01 | (1 << REFS0); // PB2, 1.1v reference
    ADCSRA = (1 << ADPS0) | (1 << ADPS1) | (1 << ADPS2) | //       = 128 (75 )
             (1 << ADIE) |  //    
             (1 << ADEN);   //  
  } else {
    ADCSRA = 0; //  
    DDRB |= (1 << PB2); //  PB2    (  "0")   C8
    _delay_ms(50); //      C8
  }
}

//  
static unsigned int do_adc(void) {
  set_sleep_mode(SLEEP_MODE_ADC); //   "" 
  do {
    sleep_cpu(); //      ,      ,   
  } while(ADCSRA & (1 << ADSC)); //        ,  

  return ADC;
}

/*
//  
static void blink_bin(unsigned int value, unsigned char count) {
  for(unsigned char i = 0; i < count; ++i) {
    _delay_ms(1000);
    toggle_load(true);
    if(value & (1 << (count - i - 1))) {
      _delay_ms(500);
    } else {
      _delay_ms(50);
    }
    toggle_load(false);
  }
}
*/

//   
static unsigned int get_current(void) {
  unsigned int cur;

  toggle_lpf(true); //  
  _delay_ms(150);
  toggle_adc(true); //  
  _delay_ms(50); //    C8
  cur = do_adc(); //  
  toggle_adc(false);
  toggle_lpf(false);

  return cur;
}

//    
static unsigned int get_resistance(void) {
  unsigned int res;

  toggle_gen(true); //  
  _delay_ms(150);
  toggle_adc(true); //  
  _delay_ms(50); //    C8
  toggle_gen(false); //   ,   C8     
  res = do_adc(); //     
  toggle_adc(false);

  return MAX_U10BIT - res; //      ,      
}

//   
static bool is_current(void) {
  return (get_current() >= cur_edge);
}

//   
static bool is_toggled_on(void) {
  return (get_resistance() <= res_edge);
}

//  
static void do_main(void) {
  toggle_amp(true); //  

  if(is_current()) {
    toggle_load(false); //  ,  
  } else {
    if(is_toggled_on()) {
      toggle_load(true); //  ,  
    } else {
      toggle_load(false); //  ,  
    }
  }

  toggle_amp(false); //  
}

//    
static bool first_on(void) {
  return (frequency_dividor == 0xff); //   EEPROM   0xFF,        FREQ_MAXIMAL_DIV
}

//  
static void calibrate(void) {
  unsigned int cur_off, cur_on, res_off, res_on, res_on_tmp, res_off_array[FREQ_MAXIMAL_DIV + 1], diff, max_diff, frequency_dividor_tmp;

  blink_load(5); //    ,    
  _delay_ms(7500); //      

  toggle_amp(true); //  

  cur_off = get_current(); //      ( )

  //      
  for(frequency_dividor = 0; frequency_dividor <= FREQ_MAXIMAL_DIV; ++frequency_dividor) {
    res_off_array[frequency_dividor] = get_resistance();
  }

  blink_load(2); //     
  _delay_ms(7500); //      

  cur_on = get_current(); //     

  blink_load(3); //     
  _delay_ms(7500); //      

  
  res_off = MAX_U10BIT;
  res_on = MAX_U10BIT;
  frequency_dividor_tmp = 0;
  max_diff = 0;
  //      
  for(frequency_dividor = 0; frequency_dividor <= FREQ_MAXIMAL_DIV; ++frequency_dividor) {
    res_on_tmp = get_resistance();

    //   ,      
    if(res_off_array[frequency_dividor] > res_on_tmp) {
      diff = res_off_array[frequency_dividor] - res_on_tmp;
      if(diff > max_diff) {
        res_off = res_off_array[frequency_dividor];
        res_on = res_on_tmp;
        frequency_dividor_tmp = frequency_dividor;
        max_diff = diff;
      }    
    }
  }
  frequency_dividor = frequency_dividor_tmp;

  toggle_amp(false); //  
  
  if(cur_on > cur_off + CUR_MINIMAL_DIFF) { 
    cur_edge = cur_off + (cur_on - cur_off) / 2; //    ,     
 
    if(res_on + RES_MINIMAL_DIFF < res_off) {
      res_edge = res_off - (res_off - res_on) / 2; //    ,      

      //   
      eeprom_write_word(&EEPROM_cur_edge, cur_edge);
      eeprom_write_word(&EEPROM_res_edge, res_edge);
      eeprom_write_byte(&EEPROM_frequency_dividor, frequency_dividor);
      
      blink_load(1); //  
    } else {
      blink_load(2); //    
      if(first_on()) stop();
    }
  } else {
    blink_load(3); //    
    if(first_on()) stop();
  }
}

ISR(WDT_vect) {
  WDTCR |= (1 << WDTIE); //    watchdog   ""    
}

EMPTY_INTERRUPT(ADC_vect); //     ,     

int main(void)
{
  init_vars();
  init_pins();       
  init_interrupts(); 
  init_settings();

  if(tp_reset || first_on()) {
    calibrate(); //          
  }

  //  
  while(true) {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_cpu(); //   watchdog

    if(++clk >= INTERVAL) {
      do_main(); //  
      clk = 0;
    }
  }
}


Archive with diagram, wiring, and the complete Atmel Studio 7 project

All Articles