Part Number Hot Search : 
STK2029 2SD1933 STK2029 DE01600 2AXXX 2N5109 KBP155G AD22055N
Product Description
Full Text Search
 

To Download AVR465 Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
  AVR465: single-phase power/energy meter with tamper detection features ? cost-effective and flexible single-phase energy meter ? fulfills iec 61036 accuracy requirements for class 1 meters ? detects, signals and continues to measure accurately under at least 20 different tamper conditions ? design easily downgrades to fit normal single-phase energy metering ? compact design with internal flash memory, sram and eeprom ? includes usart and programmable i/o ? lcd is easily added by migrating to other avr microcontrollers ? secure and reprogrammable flash memory enables flexible firmware updates ? one-time, quick, and accurate digital calibration gives added benefits - calibration can be automated - no need for trimming components - no need for external eeprom , as calibration coefficients are stored internally ? adjustable energy pulse out put goes beyond 10.000 impulses / kwh ? active power, voltage and current measurements are easily accessible over usart interface ? design easily migrates to any other avr microcontroller ? low-power avr microcontroller allows operation down to 1.8v introduction this application note describes a single-phase power/energy meter with tamper logic. the design measures active power, voltage, and current in a single-phase distribution environment. it differs from ordina ry single-phase meters in that it uses two current transducers to measure active power in both live and neutral wires. this enables the meter to detect, signal, and continue to measure reliably even when subject to external attempts of tampering. the heart of the meter is an avr microc ontroller. all measurements are carried out in the digital domain and measurement re sults are available in the form of frequency-modulated pulse outputs and as plai n-text values, accessible over the usart interface. this enables the design to be used in cost-effective applications based on mechanical display counters. alter natively, the design easily fits more computerized applications with features such as remote reading (amr), demand recording, multiple tariffs, and other. a prototype built for 230v and 10a operati on showed better than 1% accuracy over a dynamic range of 500:1. with careful pcb design and following the guidelines given at the end of this document the ac curacy can be further increased. the meter is easily configured to fit any other voltage and current settings. 8-bit microcontrollers application note rev. 2566a-avr-07/04
2 AVR465 2566a-avr-07/04 overview power meters are sometimes referred to as energy meters and vice versa. per definition, (active) power is a measure of what is required (or consumed) in order to perform useful work. for example, a light bulb with a 100w rating consumes 100 watts of active power in order to create li ght (and heat). energy, per definition, is the measure of how much work has been requir ed over a known period of time. in the light bulb example, leaving the bulb on fo r an hour it will co nsume 100w * 3600s = 360000ws (watt-seconds) = 100wh (watt-hour s) = 0.1kwh (kilowatt-hours) of energy. the meter described in this application note can be referred to as a power meter, an energy meter or a kilowatt-hour meter. t he energy pulse output (ep) is a ready indication of active power, as registered by the meter; the frequency of the pulse is directly proportional to active power. integrat ing pulses over time gives active energy. for storage purposes, the meter includes two pulse outputs (dpp and dpn) to directly drive various display counters. all pulse outputs are easy to configure for any reasonable rate. the default is 10.000 impulses per kilowatt-hour for the ep output and 100 impulses per kilowatt-hour for the dpp/dpn pulses. not only pulse rates are readily adjusted; all measurement results can be calibrated in the digital domain, removing the need for any trimming components. this includes adjustments to compensate for phase delays in current transformers. the calibration event can be automated, removing the time -consuming manual trimming required in traditional, electromechanical meters. digital calibration is fast and efficient, reducing the overall production time and cost. calibrati on coefficients are safely stored in the internal eeprom, further reducing the need for external devices. the brain of the meter is the firmware, which is provided open source. although it includes all the functionality required for a tamper-proof, single-phase meter, it can be modified and updated at any time. even in the field. the firmware is entirely written in c, which makes modifications easy to implement. integrity and intellectual property are yet easy to secure using lock bits of the avr microcontroller. meter hardware the energy meter hardware consists of a power supply, an analog front end, a microcontroller section, and an interface section. the meter described in this application note connects to high currents and high voltages. high currents and high voltages ma y be hazardous, even lethal. hence, the meter should be operated by qualified technicians only. at mel takes no responsibility for any consequence that may result from the use of this document or the application described herein. warning: shock hazard
AVR465 3 2566a-avr-07/04 figure 1. electric shock hazard. 465 ln load there is no insulation between line voltage and the meter. hence, sections of the meter contain high voltages and even the low-voltage output of the power supply is connected to the mains. use caution. the meter must be enclosed in a non- conductive casing to avoid accidental voltage shocks. the power supply is a low-efficiency, but cost-effective and compact design. it is intended to provide just the amount of power needed by the meter at a cost as low as possible. if enhancements are made to the meter it may be necessary to derive new values for some of the components. the following table summarizes typical curr ent consumption of the main parts of the meter. table 1. typical current consumption of main meter sections. section includes continuous peak front end operational amplifiers (1) 0.2 ma 0.2 ma microcontroller avr (active mode, 4 mhz) (2) 1.8 ma 3.5 ma led all led?s (each about 1 mcd brightness) none (3) 3.0 ma display display counter (400 ? coil impedance) none (3) 7.5 ma notes: 1. typical consumption, according to lmv358 data sheet 2. according to atmega88 data sheet (2545b?avr?01/04) 3. led?s are mostly off and display counter is updated rarely peak currents are brief, mainly occurring when the display counter is updated. the worst-case scenario is when the display counter is updated and all led?s are lit. typically, the power supply needs to be able to supply less than ten milliwatts (at 3 volts), but it must also be able to deliver t he brief bursts of energy required to turn the coil of the counter. the power supply is illustrated in figure 2. the below schematic is identical to the power supply section of the meter, as illu strated in the schematic at the end of this document, but component numbers are not t he same. please note well the galvanic connection between live wires and meter ground! power supply power budget theory
4 AVR465 2566a-avr-07/04 figure 2. low-cost, transformerless power supply. l n 230v r1 d1 vout u1 +vin gnd vcc d2 c2 c1 the power supply is based on halfway rect ification. during negative half-waves capacitor c1 is charged and during positi ve half-waves the capacitor is drained. zener diode d1 (minus the forward voltage of diode d2) dictates to which voltage c2 is charged. voltage regulator u1 uses the energy stored in c2 to produce a stable output voltage. resistor r1 controls the ch arge and discharge of c1 and also limits the current flow through zener diode d1. please note that the power supply can be a source of noise, if poorly planned and realized. ground connections are very im portant. for example, the current flow through the zener is rather large and if the same ground track is shared by the zener and, say, the operational amplifiers (see cu rrent front end) then measurement results will be greatly degraded. typically, this can be seen as odd harmonics in the measured current signal. it is recommended to use star topology in ground connections. the dropout voltage for the 3.3v regulator u1 is about 5v. when input voltage falls below the dropout level, the device ceases to regulate. the regulator input must be kept above this level, even at the end of the drain cycle and at worst-case current consumption. as a starting point, the zener diode is specified to 15v. this leaves much headroom for capacitor c2 to discharge before reachi ng minimum input voltage of the regulator. next, the size of capacitor c2 is calcul ated. the minimum size is derived based on the general discharge function of the capacitor, as follows: equation 1. equation to calculate size of charge capacitor. () 0 rc t v v 0 ln r t c e v v ? = ? = ? here t is the discharge time, v 0 is the initial voltage, v is the voltage after discharge and r is the load discharging the capacitor. if the worst-case current consumption is 14ma (see previous table), then the equivalent load resistance is r = 3v/14ma = 214 ? . worst-case current consumption takes place when driving the display counter. the length of the drive pulse is 100ms, by de fault. assuming the voltage of the charged capacitor is allowed to drop to regulator minimum during the length of one display pulse, the smallest size of the capacitor is as follows: equation 2. calculating minimum size of capacitor c2. () f 470 f .3 425 ln 214 0.1s c 15v 5v = ? ? = source of noise component values
AVR465 5 2566a-avr-07/04 next, capacitor c1 is calculated. the size of the capacitor should be as small as possible, since it dictates how much powe r is drawn from the mains lines. also, the larger the capacitor, the more expensive it is. the minimum size of the capacitor is derived from the basic functions of stored ch arge (q = cu) and current (i = q/t). for capacitor c1 it is no longer required to use the above worst-case current (14ma), since capacitor c2 will store energy enough to maintain the current briefly. assuming 10ma continuous current, and that the capacitor is drained over one 50hz half cycle, and that voltage is 80% of nominal, then the required minimum size of the capacitor is as follows: equation 3. calculating minimum size of capacitor c1. 680nf f 0.543 230v 0.8 0.01s 0.01a u t i c mains = = = the capacitor needs to be fully charged each half-cycle. the charge time is dictated by resistor r1, the size of which can be derived using the so-called 5rc rule of thumb. the 5rc rule says that for a step change in voltage the capacitor charges to within 1% of its final value in five time constants (rc). specifying that the capacitor should be (almost) fully charged at the peak of the positive half-wave, the maximum size of resistor r1 can be estimated as follows: equation 4. calculating maximum size of charge limit resistor. ? = = = ? = 1470 0nf 68 5 0.005s c 5 t r c r 5 t another limitation on resistor r1 is that it must be small enough for capacitor c2 to charge enough during one half-cycle. the larger r1 is, the less c2 is charged each cycle. on the other hand, it is unreasonable to specify r1 such that c2 charges to, say, 99% during one half-cycle since this would make r1 very small and the power consumption in zener diode d1 very large. instead, a decent charge level is selected and r1 is specified accordingly. for example, setting r1 = 470 ? the meter works nicely (input voltage to regulator typi cally stays above 13v at all times). the analog front end is the part, which interfaces to the high voltage lines. it conditions high voltages and high currents down to a level where the signals cannot harm the more delicate electronics. it conv erts high voltages and high currents to voltages sufficiently small to be measured di rectly by the adc of the microcontroller. the nominal line voltage of the meter is 230v and the maximum rated current is 10a, both of which obviously are way too large signals to be fed directly to any microcontroller. the analog front end c onverts line voltage and line current to voltages with amplitudes of no more than 1v peak-to-peak. the front end is easy to configure for any other line voltage or current, as described in the following. line voltage is first downsized using a resist or ladder, then dc-filt ered and finally dc- biased, as illustrated in figure 3. note t hat component numbers are not the same as in the full schematic at the end of this document. analog front end voltage front end
6 AVR465 2566a-avr-07/04 figure 3. voltage front end. load 230v r2 r1 r4 r3 c1 vcc the resistor ladder r1-r2 by default produ ces a 1.1vpp signal when the line voltage reaches 115% of nominal voltage, as follows: equation 5. downsizing the line voltage. pp nom max 1.099v 0.388v 681k ? 1k ? 1.15 230v r2 r1 r2 1.15 u u = = = + = the nominal voltage is 230v by default and the 265v limit is there to leave 15% headroom for overvoltages. the dc bias ladder r3-r4 positions the ac signal halfway up the adc voltage reference. by default, it has been sized to fit atmega88 (1.1v reference) and 3v supply voltage, as follows: equation 6. dc bias level of downsized signal. 2 u 0.55v 3.68m ? 680k ? 3v r4 r3 r4 u u aref vcc dc = = + = please note that the voltage front end handles voltages of considerable amplitude, which makes it a potential source of nois e. disturbances are readily emitted into current measurement circuitry, where it w ill interfere with the actual signal to be measured. typically, this shows as a non-lin ear error at small signal amplitudes and non-unity power factors. at unity power fa ctor, voltage and current signals are in phase and crosstalk between voltage and cu rrent channels merely appears as a gain error, which can be calibrated. when volt age and current are not in phase crosstalk will have a non-linear effect on the measur ements, which cannot be calibrated. crosstalk is minimized by means of good pc b planning and the proper use of filter components. the current front end is a little bit more complex than the voltage front end. this is because line voltage remains constant at, sa y, 230v but line current varies with the load. line current typically ranges from so me milliamperes to ten amperes, or more. in order to achieve 1% measurement accu racy over such a wide range, the adc would need to have a resolution of around 16 bits. since the target device includes only a 10-bit a/d-converter the front end must amplify small-scale signals. the current front end therefore includes a prog rammable gain stage, which is controlled by the mcu. crosstalk current front end
AVR465 7 2566a-avr-07/04 the design criteria for the programmable gain stage are not very relaxed; the gain stage must amplify ac signals up to ar ound 100x, but provide little or no dc amplification. this is because the input is a dc-biased ac signal and if the gain stage provides even a small dc amplification t he output will saturate. in addition, the gain must be programmable by the mcu and the settling time must be considerably less than a second. finally, the design must be cost-effective. there are many school examples of how to realize the above, but most of them are sooner or later ruled out by at least one of the design criteria. a good starting point, however, is the operational amplifier; they are common, exist in a wide variety and can be very cost-effective. a little experimentation soon shows that the non-inverting amplifier is not a viable topology for this design, mostly because of the requirements for high ac and low dc gains. considering the frequency band of interest, ac-coupled, non-inverting amplifiers require very large (and expensive) capacitors for the dc decoupling. also, a large dc decoupling capacitor leads to very long switching times when gain is altered. since the gain needs to be variable the dc levels cannot be trimmed to zero. a viable solution is found from inverting amp lifier topology, althou gh it still requires a rather (but not very) large capacitor to be used. gain configuration resistors are readily toggled in and out using low-cost sw itches from 74hc-seri es logic, as shown in figure 4. the gain stage shown has a fast switching time and allows high ac gain but a low dc gain. figure 4. inverting amplifier with variable gain uses bilateral switches (74hc4066). the gain of the inverting amplifier is as follows: equation 7. gain of inverting amplifier. r1 r2 a ? = here r1 consists of the series connection of r11, r12 and r13. gain is adjusted by shorting out one of resistors r12 or r13. th is is done using the bilateral switches, which are controlled by two i/o pins of t he mcu, shown as i/o0 and i/o1 in the figure. gain adjustment resistors are dimensioned such that each range has an amplification of about eight times the previous. the num ber of switches may well be increased and the gain difference decreased, however, it is not recommended to have a larger gain difference than eight between two subsequent ranges. this is because gain calculating the gain vcc i/o0 i/o1 rs c1 r11 r12 r13 r2 r4 c2 r3
8 AVR465 2566a-avr-07/04 differences of around ten, and higher, cause the signal to degrade below 1% accuracy before it can be further amplified. the table below illustrates how gain is adjusted from the mcu. table 2. adjusting the gain of the inverting amplifier. r2 = 470 k ? . i/o0 i/o1 range r 1 impedance gain low low low r11+r12+r13 = 6.8k+39k+330k (2) -(470/375.8) = -1.25 low high medium r11 + r12 = 6.8k+39k -(470/45.8) = -10.26 high x (1) high r11 = 6.8k -(470/6.8) = -69.11 notes: 1. no effec t, when i/o0 is high 2. all switches open; all re sistors connected in series shunt resistor rs and the current transforme r are scaled such that a voltage signal of no more than 1v peak-to-peak is present at the amplifier output when maximum current flows through the primary of the current transformer and the amplifier is set to minimum gain. for example, using a 2500:1 current transformer, a 68 ? resistor, and setting amplification to minimum (see above) , the voltage at the output is as follows: equation 8. full-scale voltage at amplifier output. pp rms rms max max 0.96v 0.34v 2500 10a 68 ? 1.25 n i rs a u = = = the input signal of the amplifier must be dc decoupled. this is done using capacitor c1 in the previous figure. it should be noted that r1 + c1 form a high-pass filter (hpf) that may distort signals, especially at high gains. the corner frequency, or the ?3db point, of the hpf is calculated as follows: equation 9. corner frequency of hpf. c1 r1 2 1 f 3db - = the closer the corner frequency of the hpf is to the frequency band of the interest, the higher is the distortion of phase a nd amplitude. it is recommended to keep a distance of at least 100x between the tw o frequencies. at 50hz line frequency and r1 minimum = r11 = 6.8 k ? , c1 should not be less than 47 f. the output signal of the gain stage is bias ed around the dc level present at the non- inverting input of the operational amplifier. hence, this dc level should be exactly half of the reference voltage of the adc in t he mcu. assuming a 1.1v reference, the voltage divider r3-r4 should produce a st able 0.55v. the voltage divider should have a large impedance to keep the current consumption low, since high impedance increases noise. for example, assuming 3v supply voltage, a suitable set of values is 3 m ? + 560 k ? . the dc level is stabilized with one, or many , capacitors. it is re commended to include at least one capacitor in the f-range. to make accurate measurements, the input signal must be as clean as possible, especially at low amplitudes. input signal s with low amplitude are amplified before being sampled and processed, which means any noise in the signal will be enlarged, too. at the low end of the measurement range input signals have amplitudes below calculating full-scale dc decoupling dc bias eliminating noise
AVR465 9 2566a-avr-07/04 10mv, which means noise typically not visible on an oscilloscope (say, below 1mv) may distort the signal by as much as 10%. noise is eliminated using good pcb planning and properly sized and placed filter components. energy meters are prone to operate in har sh environments; meters are often subject to over-voltages and current spikes. if such disturbances are not properly shielded they may traverse all the way to the mcu and drive it outsi de operating limits. there are many techniques available for filtering out unwanted disturbances. rapid voltage spikes are usually suppressed using varistors, which normally have very high impedance. at a given threshold the impeda nce very rapidly decreases, causing a short circuit, which then leads the excess ener gy to ground. varistors must be picked such that they do not break down if the spike is too large or lasts too long (i.e. if the energy of the spike grows too large). much depending on the layout of the circui t board and connectors, some inputs may be prone to pick up radiated noise. in some cases, even the circuit board tracks can perform as antennas and pick up noise from the environment. induced noise can be throttled using well-placed diodes, which clamp signals between ground and supply voltage. emc protection techniques are well covered in application note ?avr040: emc design considerations?. the microcontroller section includes the avr and the clock source to run it. also included are all digital input and output circuitry. in order to keep power consumption low all led?s are of low-current type. low- current led?s typically produce around 2m cd of light power for 2ma current. the led?s have a forward voltage of about 2v and using a series resistor of 1 k ? will therefore limit the current to about 1ma per led. the resulting led brightness is good for most applications. for display purposes, this application us es what is sometimes referred to as a stepper motor counter. these types of coun ters are typically available in a price competitive range and tend to be rather common in designs like this. the counter is driven using a pulse waveform as illustrated in figure 5. figure 5. pulse waveform to drive display counter. by default, pulse length t dpx is 100ms, but this is readily adjusted from the firmware to any other value. naturally, the pulse outputs provided by the design can be used to drive standard impulse counters, as well. protection circuitry microcontroller section signal led?s display counter dpp dpn 2t dpx t dpx t dpx
10 AVR465 2566a-avr-07/04 the programming interface is required for programming the microcontroller and for calibrating the meter. using the serial prog ramming interface (spi) of the avr, it is possible to access both flash and eeprom via the same connector. complete system programming and calibration can be performed at any time. the pin layout of the programming inte rface is shown in the table below. table 3. pin layout of spi connector pin name direction description 1 miso out serial data out 2 vcc n/a supply voltage 3 sck in serial clock 4 mosi in serial data in 5 /rst in device reset 6 gnd n/a ground the application uses the usart (u niversal synchronous/asynchronous receiver/transmitter) interface of the avr to send measurement data. any terminal software can be used for sending commands to the meter and for receiving measurement data. measurement results, once calibrated, are given in units of watts, volts and amperes. the following table shows the pin layout of the asynchronous interface connector. table 4. pin layout of serial interface pin name direction description 1 rxd in asynchronous data in 2 txd out asynchronous data out 3 gnd n/a ground 4 gnd n/a ground please note that the meter does not cont ain a level converter and the signals can therefore not be directly connected to the seri al port of a computer. the rs-232 spare connector on stk500 contains a level converter and can therefore be used as a buffer between the meter and the computer. asynchronous communication may introduce noise in measurement results, especially when power supply is unable to provide the amount of current required and when ground connections have not been properly laid out. by default, the power supply is capable of delivering enough current for the meter to run, but not necessarily enough to drive the usart interf ace, since it is typically not required after calibration. in addition, the serial inte rface cable may deliver disturbances to the meter. programming interface serial interface communication noise
AVR465 11 2566a-avr-07/04 as a summary, some default values for the hardware are shown in the table below. table 5. hardware defaults. parameter value note system clock 4mhz external crystal by default maximum current 10a external amplifier chops above 10a nominal voltage 230v varistor chops signals above 250v current gain ranges 1.25 / 10 / 69 meter firmware the firmware is written in c language and compiles on iar embedded workbench, versions 3.10 and upward. previous compiler versions do not support the atmega88 and cannot be used as such. the language synt ax is standard c, so the firmware should be easy to port to other c compilers of choice. the firmware is interrupt-driven, which means the main program consists of an endless loop that is halted by interrupt request s on a regular basis. it is important that the interrupt requests arrive regularly since they are used as the time base for calculations. variations in interrupt in tervals will show in the accuracy of measurement results. interrupt requests are generated by the adc, which is driven by a prescaled system clock. the analog-to-digital converter (adc) is set to operate in free running mode, which means a new conversion will start immedi ately after the current conversion completes. at the end of a conversion, t he adc raises an interrupt request and the mcu starts executing the interrupt service routine (isr). the isr reads, processes, and accumulates sampled data and then returns execution to the main program. the main program is mostly idle and is activated only when enough data has been accumulated for the end-of-cycle calculations to start. once started, the isr may still continue to interrupt the main program, even when it is busy calculating. adc interrupt requests occur at sampling rate, which is by default: equation 10. default sample rate. 2403.85hz 1664 4000000hz 13 128 f f clk s = = = when the isr is started its first task is to read sampled data from the adc and store it in a location in sram where it cannot be overwritten by new data. the first task to perform on the data is then to remove any dc offset. this is carried out using a digital high-pass filter (hpf) of type infinite impulse response (iir). the transfer function of the filter can be written as follows: equation 11. high-pass filter, infinite impulse response type. [] [ ] [ ] [ ] 1 - n x 0.996 - n x 0.996 1 n y 0.996 n y + ? = summary: defaults sampling & timing dc offset removal
12 AVR465 2566a-avr-07/04 this is a short ? and simple ? digital filter, but it removes dc sufficiently well and has a reasonable settling time. for a step change in input, the filter will settle to within 1% of its final value in some 1200 samples. this means that after power-on the meter should be allowed a few seconds to settle before measurements start. this is not a problem when the meter is running, as there are no large step changes in dc level. it should be noted that the filter is realized wi th a bit length higher than the input or output data. if internal filter data is truncat ed, the filter will rather generate offset than remove it. hence, the filter implementation uses 32-bit data types (signed long) for intermediate and output data. active power is defined as the power used by a device to produce useful work. mathematically it is the definite integral of voltage, u(t), times current, i(t), as follows: equation 12. active power definition. () () ( ) ? cos i u t i t u t 1 p t o dt here u and i are the respective voltage and current root-mean-square (rms) values and phi is the phase lag between current and voltage. the discrete time equivalent is: equation 13. active power definition in discrete time. () () = 1 - n 0 n n i n u n 1 p here u(n) and i(n) are the sampled instances of u(t) and i(t) and n is the number of samples. active power is calculated simp ly as the average of n voltage-current products. it can be shown that this method is valid for both sinusoidal and distorted waveforms. the implementation uses 32-bit data types (signed long) for storing accumulated data. the result is stored as a floatin g-point number. when the meter has been calibrated, the active power results are in units of watts. most energy meters are required to provi de a pulse, which frequency is proportional to the amount of active power measured. th e pulse typically drives an led, which is used for calibration or verification purposes. the frequency of the energy pulse, ep, and the amount of active power measured are related as follows: equation 14. frequency of energy pulse output. 000 600 3 mc p f = here p is active power in watts and mc is the meter constant in pulses/kilowatt-hour. the meter constant is part of the calibrat ion coefficient set, and can be set to any integer value, ranging from one to 65535. taking into account the system clock, f clk , and the timer/counter prescaler, ps, the energy pulse interval is derived as follows: active power measurement energy pulse output
AVR465 13 2566a-avr-07/04 equation 15. interval of energy pulse output. mc p ps 000 600 3 f t clk = it should be noted that after the meter co nstant has been set there is only one variable; active power, p. in order to sa ve instruction cycles, the expression is reduced to t = n/p, where n is a pre-calc ulated, constant numerator. the numerator is calculated during firmware initializat ion, when mc is read from eeprom. the default numerator is as follows: equation 16. constant numerator at default meter constant. 250 406 1 000 10 024 1 000 600 3 000 000 4 mc ps 000 600 3 f n clk = = = after the required pulse interval has bee n calculated the timer/counter (t/c) is programmed to produce a pulse output with an interval as close as possible to the one derived. the 16-bit t/c is clocked by a prescaled system clock. the prescaler is chosen such that even the smallest puls e intervals can be accu rately represented. the problem is to also be able to accurately produce pulses with very long intervals. for this purpose, the t/c is extended with a firmware counter. the regular t/c mechanism is illustrated in figure 6. in this mode of operation the energy pulse is set on each compare match. figure 6. basic timer/counter operation. a compare match with ocr1a sets the oc 1a output and a compare match with ocr1b clears the same. the pulse interval, t ep , is controlled by ocr1a and the pulse width, t eph , by ocr1b. when the calculated energy pulse interval exceeds 16 bits the firmware extended, 16- bit counter (tc1ext) is activated. the firm ware counter value is increased each time the hardware counter reaches 16-bit maxi mum, effectively making the extended counter 32 bits in length. the extended counter mechanism is illustrated in figure 7. regular mode t/c extended mode t/c ocr1a ocr1b tcnt1 oc1a (ep) t eph t ep
14 AVR465 2566a-avr-07/04 figure 7. extended timer/counter operation. tc1extrem ocr1b tcnt1 ocr1a tc1ext max ($ffff) max 0 1 tc1extrem tc1exttop max ($ffff) tc1exttop+1 0 max ($ffff) oc1a (ep) for each energy pulse emitted, an internal pulse counter is increased. when the counter reaches a given threshold a display pulse sequence is initiated, as shown in figure 8. the threshold can be set using calibration coefficients. figure 8. generation of display pulses. oc1a (ep) display counter pd6 (dpp) pd7 (dpn) t dpx t dpx t dpx t dp n 1 0 1 0 n-1 n pulse width and spacing, t dpx , are firmware constants, which are easy to alter. the default setting generates 100ms long pulses. the firmware calculates rms (root-mean-squar e) values of voltage and currents. an rms value is defined as the square root of the mean value of the squares of the instantaneous values of a periodically va rying quantity, averaged over one complete cycle. the discrete time equation for calculating voltage rms is as follows: display pulse outputs voltage and current measurement
AVR465 15 2566a-avr-07/04 equation 17. voltage rms calculation in discrete time domain. () n n u n n ? = = 1 0 2 rms u current rms is calculated using the same equation, only substituting voltage samples, u(n), for cu rrent samples, i(n). accumulated data is stored 32 bits wide (si gned long) and the calculation result is stored as a floating-point number. when pr operly calibrated, the resulting voltage measurement is in units of volts and curr ent measurements in units of amperes. a tamper condition enters when meter wiring is altered in a pilfering manner, typically with the intention to reduce electricit y billing. the firmware detects, signals and continues to measure accurately under mo re than twenty known tamper conditions, including reversal of current and partial or whole earth reroutings. tamper detection is based on monitoring curre nt flow in both live and neutral wires. tamper indicators are set if any inconsis tency is detected between the two currents. actions are then taken to ensure measurement data is recorded correctly, regardless of the type of pilfering attempt. an earth fault means some or all loads have been connected to another ground potential and not the neutral wire. a partial ea rth fault is illustrated in figure 9. full current, i tot , only flows through one of the current transformers, since part of the return current, i 2 , does not go through the meter. as a consequence, the current in the neutral wire, i 1 , is less than that in the live wire, i tot . alternatively, if live and neutral wires have been swapped, the current in the live wire is less than that in the neutral. figure 9. partial earth fault. l n r l1 r l1 i tot i 1 i 2 meter load the firmware constantly monitors current flow in both wires and signals an earth fault if the magnitude difference between the two exceeds a given a threshold. the threshold has been hardwired to 5%, but is easily adjusted in the source code. tamper detection earth fault
16 AVR465 2566a-avr-07/04 the earth fault indicator is set during initia lization and will not be cleared until at least one set of valid readings have been found. this means that if the meter is powered on at a no-load condition the fail i ndicator will remain constantly set. the firmware always uses the larger of the two readings for driving the energy pulse and an earth fault therefore has no effect on the accuracy. a reversed current condition means current in one or both wires is flowing in the wrong direction. as a cons equence, active power reading s will have the wrong sign. the firmware activates the reversed curr ent indicator when any of the two currents has a sign opposite the one expected. figur e 10 illustrates how return current, i 2 , has been reversed while live current, i 1 , flows in the expected direction. figure 10. reversed return current. l n r l i 1 meter load i 2 the reversed current indicator is set during in itialization, but is soon cleared, provided currents in live and neutral wires flow in the correct direction. the firmware always uses the absolute value of active power for driving the energy pulse and the direction of current t herefore has no effect on accuracy. no two meters are alike and individual variations are to be expected. typical tolerance figures for components used in the meter are 5%, which means the assembled meter has an inherent error of the same magnitude. hence, each meter must be calibrated before accurate measurement result can be obtained. rather than populating the meter with trimming resistors and rely on slow, manual calibration the procedure is readily carried out in the digital domain. calibration coefficients are first calculated for each meter individually, then stored in on-chip eeprom and later retrieved during firmware initialization. the coefficients trim the calculations such that measurement results are accurate within limits. digital calibration is accurate and efficient, it is quick to perform, requires little or no manual intervention, and does not degrade over time. in addition, calibration data is safely stored in the internal eeprom. phase displacements between signals are in troduced by current transformers, input filters and by the multiplexing of input ch annels. some dc immune transformers may well introduce phase displacements of more than 5 degrees while the multiplexing introduces a time difference between all channels, inversely proportional to the sampling frequency. at approximately 2400hz sampling frequency, the time delay is 1/2400hz = 0.42ms, which means that at 50hz mains frequency there is a phase difference of 360 x (50hz/2400hz) = 7.5 degrees. reversed current calibration phase
AVR465 17 2566a-avr-07/04 the phase displacements are adjusted using linear interpolation, which is fast, easy and sufficiently accurate. the limitation is that linear interpolation introduces a constant time delay to the signal, which means phase can be correctly adjusted for one frequency, only. signal components above mains frequency, i.e. harmonics, cannot be simultaneously phase-adjusted using this approach. typically, though, this is not a problem since most of the si gnal energy lies in the first harmonic. the algorithm uses two subsequent samples to interpolate an intermediate point. this means that the higher the sampling frequ ency, the lower the phase adjustment margin. at approximately 2400hz sampling rate (800hz per channel) and 50hz mains frequency, the highest phase delay that c an be interpolated is 360 x (50hz/800hz) = 22.5 degrees. the effect of the phase calibration coefficients is shown in the following equation. equation 18. effect of phase calibration coefficient. clk m f 3 13 128 f 360 65536 pcc z = here pcc is the phase calibration coefficient, f m is the mains frequency and f clk the system clock frequency. there is one phase calibration coefficient for each input channel, i.e. three in total. note, that t he 16-bit phase calibration coefficients are treated unsigned. magnitude errors are introduced to all measurement results due to variations in discrete component values, but are easily corrected using a set of gain calibration coefficients. there are separate gain coe fficients for voltage and each amplification range of both current channels, i.e. 1 + 2 x 3 = 7 in total. current samples are filtered, phase adjusted and then accumulated. for active power calculations, the current samples are first multiplied with voltage samples and then accumulated. at the end of each calcul ation cycle all accumulation registers are normalized and the results are then multiplied with corresponding gain coefficients. for each current channel, one of three gain coefficients is used, depending on the amplifier setting, i.e. different coeffi cients are used at low, medium and high amplification. the effect of current gain coefficients is shown in the following equation. equation 19. effect of current gain coefficients. n cal ig i i = here ig is the current gain coefficient and n denotes amplifier setting (n=1,2,3). the same equation holds for both live and neutral current measurements. the 16-bit coefficients are treated unsigned. assume meter is configured for 10a maximu m current. at full-scale, sinusoidal input and lowest amplifier setting the peak-to-pe ak value of sampled data is 1023. after prescaling (x32) and dc removal, the amplitude of the sampled signal is: current gain example
18 AVR465 2566a-avr-07/04 equation 20. amplitude after hpf. 130432 2 1023 255 i ? = = after scaling (1/64) and taking the square of each sample, the amplitude is now +/- 4153444. at 4mhz system clock, 128 adc prescaler and 50hz mains there are 16.026 samples per mains cycle. accumulating over 25 x 16.026 = 401 samples, normalizing and taking the square root, the result before calibration is: equation 21. result before calibration. 755 . 1713 2 401 4143444 401 i = = dividing the result with a calibration coefficient of 1713.755 / 10 = 171.3755 the result is: equation 22. result after calibration. 000 . 10 171.3755 1713.755 i cal = = voltage is calibrated similarly as current, but since gain remains constant only one coefficient is required. the effect of the voltage gain coefficient, ug, is shown in the following equation. equation 23. effect of voltage gain coefficient. 65536 ug u u cal = the 16-bit gain coefficient is treated unsigned. active power measurements do not require a dedicated gain coefficient, but use current and voltage gain coefficients. meas urement results are multiplied with the voltage coefficient and the corresponding current coefficient. the effect is shown in the following equation. equation 24. effect of voltage and current gain coefficients on active power. n cal ig ug p p = the meter constant dictates the relati onship between amount of active power measured and the frequency of the energy pu lse output. the larger the active power, the higher the frequency, f ep , as illustrated in the equation below. equation 25. effect of meter constant. 000 600 3 mc p f ep = voltage gain active power gain meter constant
AVR465 19 2566a-avr-07/04 here p is active power in watts and mc is the meter constant in impulses/kilowatt- hour. note, that the pulse frequency also depends on the system clock. the above equation assumes a system clock of 4mhz. the calibration coefficient is treated as a 16-bit, unsigned integer. the energy pulse output is typically wire d to an led and used for calibration and verification purposes. the pulse must be sufficiently long to light the led for an optical reader to register it, but also suffici ently short to allow a reasonably high output frequency. the default is 50ms active time, which limits the frequency to about 10hz. at 4mhz system clock, 10a max current and 230v nominal voltage, this means the maximum meter constant is about 15000 imp/kwh. to increase the meter constant above this, the maximum current and the pulse length must be decreased. another limitation is the quantiz ation of the pulse interval. at default system clock (4mhz) and default t/c prescaler (1024), the timer is updated once every 1024/4000000 = 0.256ms. assuming highest default pulse rate (10hz) the pulse interval is 100ms and the highest quantiza tion inaccuracy is +/-(0.256/100) = +/- 0.256%. for practical purposes it is recommended to scale system clock, maximum current and meter constant such that the timer/counter interval never goes below, say, 500 timer ticks. by default (4mhz, 10a, 230v, 10000imp/kwh) the pulse interval will not go below 500 ticks. a pulse pair is provided to drive a steppe r-motor counter. typically, the required display pulse rate is much lower than the energy pulse rate. the pulse rate, f dp , can be adjusted using the dpc calibration coefficient, as follows: equation 26. effect of display pulse constant. dpc f f ep dp = here f ep is the energy pulse rate. the 16-bit display constant is treated unsigned. the eeprom layout of calibration coeffici ents is shown in the table below. all coefficients are 16-bit wide and stored with high byte first, then low byte. table 6. calibration coefficient layout in eeprom. addr. + 0x00 + 0x01 + 0x02 + 0x03 + 0x04 + 0x05 + 0x06 + 0x07 0x00 pcc0 pcc1 pcc2 ilg0 0x08 ilg1 ilg2 ing0 ing1 0x10 ing2 ug mc dpc 0x18 crcw crc16 pcc is the phase calibration coeffici ent and ilg and ing are the current gain coefficients for live and neutral wires, respec tivelty. ug is the voltage gain coefficient, mc the meter constant and dpc the disp lay pulse constant. crc16 contains the checksum for the low 32 bytes of the eeprom. if crcw is set to to 0x4357 then the checksum is calculated by the firmware and written to crc16. limitations display constant coefficient layout
20 AVR465 2566a-avr-07/04 program constants are values that can be alte red before the firmware is compiled, but not afterwards. typical constants are various bit and flag definitions, but also included are some fundamental invariables, such as pulse lengths and sample rates. some of the fundamental constant s are discussed below. this constant defines the threshold when to increase amplification of current signal. amplification is increased when the amplit ude of the filtered current signal drops below this level. should be below (255 x 1023) / current gain. these are low and high levels, which define saturation limits for current samples. amplification is decreased when unconditioned current samples go below low limit or above high limit. recommended a few lsb?s below max and above min. this is the number of samples to wait befor e allowing a new gain switch to take place. by default, the amplifier settles in a few hundred sampling cycles, which means a value of 100 should be enough. starting current in amperes. active power readings are cleared when current measurement drops below this limit. shoul d be set according to iec 61036 standard. constant offset, which is added to all measur ement results. improves linearity at low amplitudes, if properly scaled. should be around ? lsb x 255 = 128. this is the number of samples to accumulate during each calculation cycle. large values create more stable results but at longer intervals. should be an integral multiple of number of samples per mains cycle. this is the inverse of nmax. it is a pre-ca lculated constant, which is used at the end of each accumulation cycle. this is the length and spacing of display pulses, in units of sampling cycles. the main program is mostly idle (looping) and is interrupted only when a fresh sample is available from the adc or when the ti mer/counter requires service. the most frequently occurring event is the adc inte rrupt service, which must be complete before the next service request arrives. in order to monitor that the adc isr does not consume too many instructions cycles t he service routine sets and clears a pulse upon entry and exit, respectively. by default, the duty cycle pulse is routed to th e lowest bit of port b. the duty cycle is readily monitored with an oscilloscope connect ed to pb0. the closer the duty cycle is to 100%, the higher is the risk that there w ill not be enough clock cycles to process all data. a conservative duty cycle is below 50%. program constants amp_lo sat_lo, sat_hi gain_hold i_min offset nmax norm dp_on duty cycle
AVR465 21 2566a-avr-07/04 as a summary, some firmware defaults are shown in the table below. table 7. firmware defaults. parameter value note compiler iar 3.10 device atmega88 8kb flash, 1024b ram, 512b eeprom starting current 2ma see i_min constant calculation cycle 200ms see syst em clock and nmax constant energy pulse rate 10000 imp/kwh see mc calibration coefficient energy pulse length 50ms see syst em clock and ocr1b initialisation display pulse rate 100 imp/kwh see dpc calibration coefficient display pulse length 100ms see sy stem clock and dp_on constant terminal setting 38400 bauds see usart initialisation setting up the meter in stand-alone mode the meter only needs to be attached to the mains wires. during calibration and testing, the meter must be connected to a computer terminal via the serial interface and for programming purposes the meter must be connected to a computer via the in-system programming (isp) interface. it is recommended to isolate the meter fr om other hardware using optocouplers. the meter must be operated with care when connected to mains (high voltage) lines. one common pitfall is to neglect ground wirings and nonchalantly proceed with connecting the meter to external hardware, such as a personal computer. the results can be destructive. figure 11. short circuit between live and neutral wire. other hardware 465 ln short circuit the meter has no galvanic isolation from liv e wires, which means even the apparently harmless meter ground is firmly bolted to the live voltage. connecting the meter to another mains-powered hardware can lead to short-circuit between live and neutral wires, as shown in the figure above. not a recommend thing to do. summary: defaults warning: ground precaution
22 AVR465 2566a-avr-07/04 for stand-alone operation, the meter is simply connected to the mains wires as illustrated in the schematic. the meter autom atically starts to measure power and stores energy consumption data in the display counter. note that the meter needs to be calibrated before reliable meas urement data can be expected. for programming, calibration and testing purposes the meter needs to be temporarily connected to external hardware, such as a computer or a microcontroller. the external hardware writes the firmware into the flash memory of the meter mcu. it then assesses the accuracy of the meter and writes calibration data into the eeprom of the mcu. the meter is ready to run in stand-alone mode after programming and calibration has completed successfully. a general illustration on how to connect the meter for programming, calibration and metering is shown in figure 12. please note that this is a generalized block schematic and does not include all recommended safety precautions. figure 12. connecting the meter to external hardware. 465 stk500, avrisp, jtagice mkii, or similar signal generator high voltage & current usart isp stk500, or similar computer running avr studio and terminal rs-232 rs-232 it is recommended to create a galvanic is olation barrier between the mains-coupled meter and the other hardware. this can be done using optocouplers at the isp and usart interface or at the rs-232 inte rface. optocoupling both isp and usart makes the stk500 and debugger ?safe? , but requires many optocouplers. alternatively, creating the galvanic barrier at the rs-232 interfaces requires less optocouplers but makes all devices except the pc hazardous. another alternative is to use an isolation transformer to create a floating front-end, which can then be bolted to the same gr ound as the rest of the electronics. the meter avr is programmed via the in-system programming (isp) interface, which means the device does not need to be removed for programming. the isp connector (j1, see schematic) is connected to a pr ogrammer (stk500, atavrisp, or similar) or a debugger (atjtagicemk ii, or similar). software su ch as avr studio can then be used for programming flash and eeprom of the target avr. the meter constantly sends measurement dat a via the asynchronous interface. to read measurement data (also during calibrati on), the asynchronous interface must be connected. the asynchronous connector (j2, see schematic) is wired to a microcontroller directly or to a comput er via a rs-232 buffer. the asynchronous interface cannot be wired to a rs-232 port directly, since it is not buffered. a rs-232 buffer is readily found on the stk 500. connect the asynchronous interface of the meter to stk500 pins labeled rs232 spare. then connect the stk500 d- connector labeled rs232 spare to the serial port of the computer. use a terminal software of choice to read data from the serial port. a general illustration on how to connect the meter for programming, calibration and metering is shown in figure 13. also s hown in the figure is a recommended optical isolation board. hardware set-up warning: galvanic isolation programming calibration & metering
AVR465 23 2566a-avr-07/04 figure 13. example set-up for calibration and/or metering. to download the firmware into the meter first open the compiler workspace, compile the project and use avr studio to send the compiled file to the target, as described above. alternatively, use avr studio to send the precompiled firmware directly to the target. set up fuses to match hardware environment. the default is to use external crystal, with full output swing and long start-up ti me. this means fuses cksel are set to 0111 and fuses sut to 11. fuses ckdiv8 and ckout should be unprogrammed. calibration example there are many methods for calibrating the meter. here is presented one. this method requires a programmable, high-vol tage, high-current signal generator. also required is hardware for programming the avr in the meter. an stk500 can be used, but a debugger such as jtagice mkii is recommended, since it allows eeprom to be edited more easily. connect the signal generator to the meter front-end. then connect the meter to a pc using a rs-232 buffer circuit, such as the spare rs-232 interface on the stk500. start a terminal software on the pc and config ure it to receive data from the meter. start by writing the following set of calibr ation coefficients to eeprom. this will set phase calibration to zero and gain to unity in all calculations. table 8. initialization of calibration coefficients. addr. + 0x00 + 0x01 + 0x02 + 0x03 + 0x04 + 0x05 + 0x06 + 0x07 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x08 0x00 0x01 0x00 0x01 0x00 0x01 0x00 0x01 0x10 0x00 0x01 0xff 0xff 0x27 0x10 0x00 0x64 0x18 0x00 0x00 0x00 0x00 0x43 0x57 0x00 0x00 if using a programmer, create a text file as shown below and load the contents of the file into the eeprom. the file content is of type intel hex. firmware set-up set-up step 1 - initialisation 465 rs232 spare signal gene- rator high voltage & high current stk500 rs232 ctrl rs232 spare isp6pin j2 j1 com1 com2 pc dc dc rxd /rst sck mosi vout v0 vin gnd txd miso galvanic isolation "safe" side power supply avr studio terminal
24 AVR465 2566a-avr-07/04 :1000000000000000000000010001000100010001eb :100010000001ffff271000640000000043570000ac :00000001ff next, reset the meter. this will load the calibration coefficients into memory. apply nominal voltage and large ? preferably full-scale ? current to the meter. voltage and current should be in phase, i.e. t he power factor should be unity. allow measurement results to settle for a fe w seconds and then record voltage and current readings. calculate gain coefficients us ing the previously presented equations. table 9. example readings. input measured gain error calibration coefficient u = 1241.699 5.3987 ug = 65536 / 5.3987 = 0x2f6b i l = 630.63784 126.1276 ilg[0] = 0x007e 230v 5a pf 1 i n = 626.58277 125.3166 ing[0] = 0x007d using a programmer or a debugge r of choice, load gain coefficients to eeprom. in this example, the following coefficients are loaded. table 10. new calibration coefficients. address coefficient data 0x06 ilg0, high byte 0x00 0x07 ilg0, low byte 0x7e 0x0c ing0, high byte 0x00 0x0d ing0, low byte 0x7d 0x12 ug, high byte 0x2f 0x13 ug, low byte 0x6b 0x1c crcw, high byte 0x43 0x1d crcw, low byte 0x57 reset the meter. continue to apply nominal voltage and a large current to the meter. allow readings to stabilize and then record active power, vo ltage and current readings. use voltage and current readings to calculate apparent power; s = ui. compare with active power readings and evaluate phase error, as follows: equation 27. phase error. ? ? ? ? ? ? ? ? = s p acos derive phase calibration coefficient based on phase error, and add the result to the default phase calibration coefficient. an example is shown in the table below. step 2 - gain step 3 - phase
AVR465 25 2566a-avr-07/04 table 11. example readings. input measured apparent power phase error pcc u = 230.038 pcc0 = 0 i l = 4.99541 p l = 1131.194 s l = 1149.1341 phi l = 10.138 pcc1 = 0x7359 230v 5a pf 1 i n = 5.00943 p n = 1106.641 s n = 1152.3593 phi n = 16.193 pcc2 = 0xb83e enter phase calibration coefficients in to eeprom (locations 0x00?0x05), leave other coefficients untouched, and writ e 0x4357 to crcw. reset the meter. still apply nominal voltage and high current to the meter. record current measurements, and then reduce in put current by a factor of about 8, so that the meter automatically switches to medium amplific ation range and that the sampled data has a high amplitude. again record current and th en again reduce input current by a factor of about 8. record third set of current m easurements. then use the recorded data to calculate final gain coefficients for all current ranges, as shown in the table below. table 12. example readings. input measured gain error calibration coefficient 230v, 5a i l = 4.90191 i n = 4.93608 0.9804 x 126.1276 = 123.66 0.9872 x 125.3166 = 123.71 ilg[0] = 0x007c ing[0] = 0x007b 230v, 1a i l = 1017.25948 i n =1016.93559 1017.25948 / 1 = 1017 1017 ilg[1] = 0x03f9 ing[1] = 0x03f9 230v, 0.1a i l = 687.69546 i n = 690.78431 687.69546 / 0.1 = 6877 6908 ilg[2] = 0x1add ing[2] = 0x1afc note that the gain errors for low amplification are multiplied with the previously evaluated. this is because the previous coeffi cients were in effect during this set of measurement. write new current gain coefficients to eeprom (locations 0x06?0x11), update crcw to 0x4357 and reset meter. the example meter was tested after the above calibration. the signal generator was connected to the front end of the meter and was programmed to perform a current sweep from 10ma to 10a. active power readings were recorded from the energy pulse output. all measurement results were within 1%. step 4 - final gain step 5 - verify
26 AVR465 2566a-avr-07/04 measurement results measurement results were recorded for a manually assembled prototype at room temperature. the following table shows typical current consumption figures for this application. table 13. typical current consumption figures. condition typical duration meter running, all led?s off, display pulses low 3.0 ma continuous meter running, all led?s on, display pulses low 7.5 ma continuous meter running, all led?s on, display counter increment 12.5 ma 100ms the measurement accuracy was tested on a calibrated energy meter. the reference was a programmable, three-phase signal generator (type omicron, model cmc56). the signal generator was programmed to supply the meter with known voltages and currents at various power factors and t hen read back the frequency of the energy pulse (ep) at each setting. for each measurement point, only one pulse interval was recorded, i.e. no averaging was done. the results from 57 measurement points were then gathered into three curves illustrating the dy namic accuracy for three given power factors. figure 14 illustrates how meter accuracy sta ys within 1% over a wide dynamic range. the current scale has been normalised, i.e. 1.000 corresponds to maximum current (10a, 20a, or whatever). the solid line repr esents the relative error at unity power factor, i.e. when voltage and current are in phase. the dotted line indicates relative error at power factor 0.8, capacitive, and the dashed line shows relative error at power factor 0.5, inductive. figure 14. typical measurement accuracy. pf = 0.5i pf = 1 pf = 0.8c 1.000 0.100 0.001 0.010 +1.00% -1.00% +2.00% +3.00% -2.00% -3.00% (scale normalised) power consumption accuracy
AVR465 27 2566a-avr-07/04 flow charts figure 15. main program. reset initialise key pressed? cycle full? key service cycle service yes yes no no main program
28 AVR465 2566a-avr-07/04 figure 16. initialisation. initialise initialise() set up i/o pins. configure timer /counter. configure usart & adc. readcalibration() read calibration coefficients from eeprom. initgaincontrol() initialise variables that control the gain. setgain(low) set low gain on both current input channels. turn on watchdog & interrupts end initialisation
AVR465 29 2566a-avr-07/04 figure 17. character input service. key service getchar() = 'x' or getchar() = 'x' ? service for key x yes no end character input service
30 AVR465 2566a-avr-07/04 figure 18. calculation cycle service. cycle service rms current below threshold? clear active power yes no clear cycle_full flag sum = accumulator accumulator = 0 make a copy of accumulated data, then clear accumulator to make way for new data. adjust gain & clear gain control flags increase or decrease gain of current channels, according to control flags. then reset flags. normalise & add/subtract offset normalise data, then add a constant offset to it. subtract, if accumulated data is negative. calculate & calibrate take square root of current and voltage data, then multiply accumulated data with calibration coefficients. css (continued on next page) calculation cycle service
AVR465 31 2566a-avr-07/04 end active power above threshold? yes no p(l) within 5% of p(n) ? no yes p(l) and p(n) both positive ? no yes display measurements signal earth fault signal reversed current send measurement data over usart interface. voltage in volts, current in amps and active power in watts. setpulse() calculate and set new pulse rate, based on active power measurement s. css
32 AVR465 2566a-avr-07/04 figure 19. setpulse(). setpulse(power) power <> 0 ? 3600 x f clk yes no end take absolute of power t < t min ? yes no extended counter top value set ? yes no t = t min set new compare match for t/c and new top value for extended counter. active power can be positive or negative, depending on the flow direction of current. sign is irrelevant when calculting pulse interval. pulse interval t = t max power x presc x mc t = f clk = clock frequency presc = t/c prescaler mc = meter constant t > t max ? no yes extended counter = c max counter = c max extended counter = t / c max counter = remainder set counter value as new t/c compare match setpulse()
AVR465 33 2566a-avr-07/04 figure 20. timer/counter compare a. tc1_compa_isr top value set? increase counter x yes no end counter x < top? no yes set t/c to clear output on next match counter x > top? no yes clear counter x (set or clear t/c output) this is handled automatically by timer/counter hardware. clear counter x, set ocr to max, clear on next match configure t/c to clear output on next match increase counter d counter d = dpc? yes no set dpp output high set display pulse flag high dpc is a calibration constant and can therefore be adjusted. top > 0 means extended counter is active. maintain counter as long as top > 0. dpp and dpn pulses are maintained by adc_isr function after display pulse flag has been. timer/counter isrs
34 AVR465 2566a-avr-07/04 figure 21. timer/counter compare b. tc1_compb_isr end configure t/c to clear output on next match force compare match configure t/c to set output on next match
AVR465 35 2566a-avr-07/04 figure 22. adc isr. adc_isr voltage sample? invert sample no yes end apply high-pass filter apply phase calibration current signals are inverted in the gain stage. invert them back. hysteresis counter > 0 ? yes no remove dc offset from signal. reset gain control flags & decrease counter sample > max or sample < min ? yes no active gain control flag lessgain filtered sample above threshold? yes no clear gain control flag moregain accumulate data and set cycle_full flag when full increase adc multiplexer maintain dpp & dpn outputs adc isr
36 AVR465 2566a-avr-07/04 schematic figure 23. schematic. load l n 1 2 3 4 5 6 7 ,kwh z1 pc6 (/reset) pd0 (rxd) pd1 (txd) pd2 pd3 pd4 vcc gnd pb6 (xtal1) pb7 (xtal2) pd5 pd6 pd7 pb0 pc5 pc4 pc3 (adc2) pc2 (adc1) pc1 (adc0) pc0 gnd aref avcc (sck) pb5 (miso) pb4 (mosi) pb3 (/ss) pb2 (oc1a) pb1 u1 t2 t1 avcc vcc x1 kim meyer, atmel finland, 2004 miso sck /rst vcc mosi gnd j1 vcc l50 ep r52 d52 r51 d51 r50 d50 earth revdir dpp dpn 230v r10 d10 vout u4 +vin gnd vcc v1 rxd gnd txd gnd j2 c57 c56 d11 c12 c11 c58 c59 c50 c10 c51 465 r35 r45 r24 u2 avcc u3 c52 c53 4 8 7 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 28 27 26 25 24 23 22 21 20 19 18 17 16 15 r40 r30 r44 u2b 7 6 5 r43 8 6 9 r42 11 12 10 u3d u3c r41 c40 r34 u2a 1 3 2 r33 1 13 2 r32 4 5 3 u3b u3a r31 c30 r36 vcc c31 r37 r21 r20 r23 r22 c20 vcc r53 r54 c54 c55 2 4 6 1 3 5 1 3 2 4
AVR465 37 2566a-avr-07/04 bill of material order codes are according to farnell catal ogue in 2004. display counter and current transformers are not part of the inventory. table 14. bill of material. reference component value order code c10 capacitor, x2, metallised polyester 0.68 uf 3549460 c11 capacitor, electrolytic, 16v 470 uf 3201508 c12, c31, c57 capacitor, electrolytic, 16v 10 uf 3201454 c20, c30, c40 capacitor, electrolytic, 16v 47 uf 3201478 c50 ? c56 capacitor, ceramic 100 nf 896755 c58, c59 capacitor, ceramic 18 pf 236950 d10 diode, zener, 500mw, 15v bzx55-c15 369081 d11 diode, 1a, 400v 1n4004 251707 d50, d51 led, red, 5mm, low current hlmp-4700 323135 d52 led, yellow, 5mm, low current hlmp-4719 323147 j1 straight pin header, 6-way 2x3 511079 j2 straight pin header, 2-way 1x2 143187 r10 resistor, 1w, 500v, 5%, carbon film 470 ? 510476 r20, r23, r37 resistor, 0.4w, 5%, metal film 680 k ? 333037 r21, r24, r35, r45 resistor, 0.4w, 5%, metal film 1 k ? 332690 r22, r36 resistor, 0.4w, 5%, metal film 3.3 m ? 333116 r30, r40 resistor, 0.4w, 5%, metal film 68 ? 332550 r31, r41 resistor, 0.4w, 5%, metal film 6.8 k ? 332793 r32, r42 resistor, 0.4w, 5%, metal film 39 k ? 332884 r33, r43 resistor, 0.4w, 5%, metal film 330 k ? 332999 r34, r44 resistor, 0.4w, 5%, metal film 470 k ? 333013 r50, r51, r52 resistor, 0.125w, 5%, carbon film 1 k ? 477783 r53, r54 resistor, 0.125w, 5%, carbon film 10 ? 477667 t1, t2 current transformer, tae hwa trans td76v n/a u1 8-bit avr? microcontroller atmega88 n/a u2 dual, low-voltage, rail-to-rail op amp lmv358 3555768 u3 quad bilateral switch cd4066bcn 380957 u4 linear regulator, 3.3v lm1117mp-3.3 120765 v1 varistor, 40j 250 v 318619 x1 crystal, quartz 4.000 mhz 492917 z1 display counter n/a this bill of materials does not include any price estimates, since local variations can be large.
38 AVR465 2566a-avr-07/04 developing the meter further this application has been created as a cost-effective alternative for tamper-proof, single-phase metering. not all customers may base their decision on the same assumptions as we have and therefore so me customers may experience an urge to redesign some parts of the meter. we do not only encourage the customer to do so, but also provide some discussion and suggestions on how to get started with it. the current front end includes operational amplifiers providing input signals for the a/d inputs of the avr. it should be noted t hat the adc input contains a s/h (sample and hold) capacitor and that operational am plifiers are not very good at driving capacitive loads (capacitive loads introduc e phase lags into the output signal, which reduces phase margin in the amplifier). hence, there needs to be a series resistor between the amplifier output and the adc inpu t. typically, a 1-kohm resistor will do nicely, but this needs to be verified agains t the data sheet of the manufacturer of the operational amplifier. there is no reason why additional gain r anges could not be implemented, using the same ideology as illustrated in this design. naturally, there is a limit on how much the input signals can be amplified before noise starts to degrade measurement accuracy, but it is possible to increase the dyna mic range above the present. alternatively, adding more gain ranges and reducing the range difference from current eight to, say, two or four may provide a more linear transfer function and increase the absolute accuracy to better than 1%. both alternativ es are included at little extra cost (only switches and a few resistors required). the power supply uses half-wave rectificati on. the efficiency of the power supply can be increased by using full-wave rectification. this means that at a cost of a few extra diodes, the power supply will be able to deliver more current to the meter without drawing more energy from the mains lines. the power consumption of the supply is around 10va, which may proove too high for some applications. for example, iec6 0136 standard limits the maximum power consumption to 10va. with the component values given in this document, power consumption is just around 10va. to lower the consumption, reduce the size of c10 (see schematic at end of document) and recalculate necessary component values, as described earlier. if c10 is made too small, the input voltage to the regulator will not rise high enough for regulation to work properly. power consumption of the microcontroller section can be decreased by putting the device into sleep at the end of each sampling cycle and waking it up again when a new data conversion is ready. the microcontroller can be configured to run from internal rc clock, as described in the data sheet. using the internal oscillator removes the need for an external crystal and lowers the overall price of the meter. t he drawback is the internal oscillator (just like any rc oscillator) is sens itive to variations in temperature. this means the frequency changes with temperature and that measurement results will change accordingly. in addition, the bit error rate of asynchronous communication will increase if the system cl ock is not stable enough. analog front end power supply microcontroller section
AVR465 39 2566a-avr-07/04 this application note is written with the atmega88 in mind, but the design is easy to migrate to almost any other avr. alternative design ideas include: ? remove tamper detection logic and turn the design into a standard single-phase meter. firmware should then fit into 4kb and the microcontroller can be replaced by an atmega48, for example. ? add functions such as remote reading, demand recording or multiple tariffs. upgrade to atmega168, for example, if the firmware exceeds 8kb. ? add integrated lcd support simp ly by migrating to atmega169. no software is ever complete and there ar e probably as many potential improvements as there are readers of this document. the good news is the firmware is open source and can be edited to fit any application. some recommended starting points for software enhancements include: ? put the mcu to sleep as often as possible. ? add apparent power, s, to measurement set. hint: s = ui. ? add reactive power, q, to measurement set. hint: s 2 = p 2 + q 2 . ? consider alternate reactive power approach. hint: if u(t) is delayed 90 degrees then reactive power can be calculated t he same way as active power, i.e. q = int{u(t-90) x i(t)}. note: academic discussion on this method?s validity under non- sinusoidal conditions has been recorded since 1927 (see c. i. budeanu, ?puissances reactives et fictives?, instytut romain de l?energie). meter firmware
2566a-avr-07/04 disclaimer atmel corporation 2325 orchard parkway san jose, ca 95131, usa tel: 1(408) 441-0311 fax: 1(408) 487-2600 regional headquarters europe atmel sarl route des arsenaux 41 case postale 80 ch-1705 fribourg switzerland tel: (41) 26-426-5555 fax: (41) 26-426-5500 asia room 1219 chinachem golden plaza 77 mody road tsimshatsui east kowloon hong kong tel: (852) 2721-9778 fax: (852) 2722-1369 japan 9f, tonetsu shinkawa bldg. 1-24-8 shinkawa chuo-ku, tokyo 104-0033 japan tel: (81) 3-3523-3551 fax: (81) 3-3523-7581 atmel operations memory 2325 orchard parkway san jose, ca 95131, usa tel: 1(408) 441-0311 fax: 1(408) 436-4314 microcontrollers 2325 orchard parkway san jose, ca 95131, usa tel: 1(408) 441-0311 fax: 1(408) 436-4314 la chantrerie bp 70602 44306 nantes cedex 3, france tel: (33) 2-40-18-18-18 fax: (33) 2-40-18-19-60 asic/assp/smart cards zone industrielle 13106 rousset cedex, france tel: (33) 4-42-53-60-00 fax: (33) 4-42-53-60-01 1150 east cheyenne mtn. blvd. colorado springs, co 80906, usa tel: 1(719) 576-3300 fax: 1(719) 540-1759 scottish enterprise technology park maxwell building east kilbride g75 0qr, scotland tel: (44) 1355-803-000 fax: (44) 1355-242-743 rf/automotive theresienstrasse 2 postfach 3535 74025 heilbronn, germany tel: (49) 71-31-67-0 fax: (49) 71-31-67-2340 1150 east cheyenne mtn. blvd. colorado springs, co 80906, usa tel: 1(719) 576-3300 fax: 1(719) 540-1759 biometrics/imaging/hi-rel mpu/ high speed converters/rf datacom avenue de rochepleine bp 123 38521 saint-egreve cedex, france tel: (33) 4-76-58-30-00 fax: (33) 4-76-58-34-80 literature requests www.atmel.com/literature disclaimer: atmel corporation makes no warranty for the use of its produc ts, other than those expressly contained in the company?s standar d warranty which is detailed in atmel?s terms and conditions locat ed on the company?s web site. the company assumes no responsibi lity for any errors which may appear in this document, reserves the right to change devices or specificat ions detailed herein at any tim e without notice, and does not make any commitment to update the information contai ned herein. no licenses to patents or other intellectual prope rty of atmel are granted by the company in connection with the sale of atme l products, expressly or by imp lication. atmel?s products are not authorized for use as critical components in lif e support devices or systems. ? atmel corporation 2004. all rights reserved. atmel? and combinations thereof, avr? , and avr studio? are the registered trademarks of atmel corporation or its subsidiaries. other terms and product names may be the trademarks of others.


▲Up To Search▲   

 
Price & Availability of AVR465

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X