Ac Power Logger Using Mcp39009 Engineering Essay

In this project we are going to record power consumption using MCP3909 by using AVR 5A microcontroller. This MCP 3909 is an energy metering IC with SPI interface and active power pulse output. Where the MCP3909 used in two different phases that can be operated at a time like 1.Output through active pulse power and 2. Waveform obtained as output through SPI interface.

For the output real pulse power, the device gives frequency output proportional to instantaneous power. For the waveform output, it gathers data from the current and voltage channel and both are 16 bit second order delta sigma ADC .

Through out this project time I learnt to do coding in C programming to get pulse output that shows the consumption of power. This program is developed to use with microcontroller Easy AVR 5A type of AT Mega 16. This program is executed by using AVR Studio by running it through AVR Flash and the output pulse wave form is gathered at AT Mega 16 board and we can check using oscilloscope.

Here to have connection between AVR board AT Mega 16 and CPU we use USB which acts like supply and we use USART to transfer data between each other. As in my project I have MCP3909 as separate board I should give correct connection between MCP 3909 and AT Mega 16 correct supply connections.

As I am doing project in embedded microcontroller with C programming and output I get is pulse waveform so for better performance and other reasons I took Easy AVR AT Mega 16 development board with 8 KHz frequency.

My project is AC power logger using MCP3909 where MCP 3909 is an energy metering IC with SPI interface and active power pulse output. Where the MCP3909 used in two different methods where they can be operated at a time like 1.Output pulse power and 2. Waveform we get as output through SPI interface.

For the active real power pulse output, the device gives output frequency which is proportional to instantaneous power. For the waveform output, it gathers data from the current and voltage channel and both are 16 bit second order delta sigma ADC which over samples input signal at frequency equal to MCLK/4 and allows large range of input signals. For channel 0, the increase in the current at channel 0 is done through programmable gain amplifier increase..

As I get pulse count at output when we use oscilloscope to get exact count and good performance I use Easy AVR 5A AT Mega 16 microcontroller. This AT Mega 16 microcontroller allows assembly language and C language programming but I did coding for counting the power consumption using MCP3909 in C language.

In this first I gave USB and USART connection between CPU and AT Mega 16 board, here I gave MCP3909 connection with AT Mega 16 and gave current and voltage channel input to MC3909 and I get pulse output this is with out SPI pin not in use but still they should be connected. But for SPI connection program I will give voltage and current with 50hz frequency and take output voltage and current values from the hyper terminal connection and calculate the output values.

In this whole project time I began to understand the SPI and USART connection to write program in C language and also understood how the MCP3909 works .

The energy meter is a device which is used for electrical measuring, it is used to record electrical energy consumed in specific period of time in terms units

Every house, small factory, business establishments, shops, offices etc need at minimum one energy meter to register power consumption. The one who supplies electricity raises bills based on readings shown in energy meter. The one who produces electricity sale the electricity to the electricity boards and board will sale this to costumer.

So the data generated by the energy meter is the base to raise bill by the power supplier. This energy meter products are available in single and three phases at different current ratings as per customer requirements.

This energy meters are basically electrical and mechanical components. The design of energy meter depends upon which rating of voltage and current meter has to work.

In this project the energy metering IC that we take is MCP3909 which is used for supporting IEC 62053 which is standard international meter. It gets the output frequency which is proportional to real power as input so as to access the ADC channel and output of multiplier data. The delta sigma which is 16bit ADC is used to allow large range of currents using the design. The exact or appropriate energy IC is available in the industry which is highly reliable and which has 24-lead SSOP output pin.

In this functional as we can see it shows ch0 and ch1 channels where these are inputs and given from the current and voltage transformers .The gains g0 and g1 are also given as input and the dual functionality pin is connected for SPI connections and also for f0, f1,f2. The outputs we take from the active power DTF conversion as HFout and other outputs Fout0 and Fout1 are obtained from stepper motor output drive for active power.

The above one is the general block diagram of MCP3909, but the diagram that I use here shows the diagram with the connections , this shows how the MCP 3909 is internally connected to oscillators ,jumpers and for the output using its 24pins. It shows that for the jumper j7 it connects internally to fout 0/1, hfout. For the jumper j2 it shows the connections to spi communications connected and the jumper j6 to ch0 and ch1 channels.

The digital voltage acts as digital circurity in MCP3909 where it is the one where we get digital power supply. This pin requires appropriate by pass capacitors and should be maintained to 5V.

In both the input channel levels this pin acts as HPF and where it controls the flow of signals. The logic 1 will activate both the filters for removing the DC offset from the system and this logic 0 will disable both the filters so due to this they allow DC voltage.

This is analog circuit pin which is used to give analog power supply with in MCP 3909 an this pin requires exact bypass capacitor which gives ramp signal with rising and falling edges and it must be maintained at 5V.

This pins are used for current measurements and where they initially take analog voltage as input and convert to current and this will have PGA for small input signal. The linear and the region where it characteristics of this channel are dependent on PGA gain. It relates to maximum voltage of 470Mv/G and the voltage range changes from 1 to 6 V with respect to Agnd. .

This pins are used for voltage measurement and this pins initially take difference analog voltage input. The linear and specific behaviour of this voltage channel is maximum at 660mV with absolute voltage 1V

Here for the internal 2.4V reference the output is the reference in/out and with temperature coefficient of 15ppm/c. Here by applying the voltage to this pin from the specified range we can use external reference and these reference in/out pin uses bypass capacitor to AGND even when using internal reference..

This is the analog ground where all the ADC,PGA,POR and band gap reference are connected to ground and this is analog circuit. To have noise signal to be cancelled this pin should be connected to same ground as Dgnd with star connection.

This is the normal ground connection where SINC filters, multipliers, HPF, LPF, digital to frequency convertor and oscillator; this is used as internal circuit connection. To have accurate and noise to be cancelled this digital ground should be grounded same as analog ground with star connection.

The output pins that are connected to MCP3909 are frequency outputs that give us real power and the signal that we get when connected to oscilloscope is pulse where this pulse period is directly proportional to power and Fc constant. This pins helps us to activate the electro mechanical counters and also two phase stepper motor.

The high frequency output supplies instantaneous real power information and out put is periodic pulse and where it is directly proportional to measured l power and HFC constant obtained by F0,F1,F2 logic gates and the output that obtained is the fastest output frequency.

These oscillators will provide sine waveform with clock source and these oscillators are mainly used to give clock signal for master in the device. The clock frequency is given as 3.57MHz and this clock frequency value should range from 1to 4 MHz with out any error.

In this to convert the signal from digital domain which has wide dynamic range we use PGA to do this function which is common thing done in wireless communication. To load normally input signal from analog to digital we need to increase the amplitude so to do this we use PGA. High resolution sigma to delta ADC’s all have Programmable Gain Amplifier at input to the sigma to delta modulator is given as shown below

The PGA on the AD’s chip offer eight input ranges to ADC with 2.5 voltage reference, the eight reference voltages are 2.56V,1.28V,640mv,160mv,40mv.if reference voltage is doubled to 5v then full scale input for each range is halved. So the actual signal range for any PGA settings are given as,

VREF*1.024/2(7-RN) where RN value is 111 when ref voltage is 2.5v

The main use of PGA is that the noise in terms of micro voltage decreases when the gain increased. In effect the input signal is gained up but the noise is not gained up, so there is an improvement in signal to noise ratio.

The pins reference sampling rate is given at 524 khz and capacitor value is fixed so there is no variation in reference current and any gain error that has due to resistance on reference input is also fixed. If reference current changes on sigma to delta the gain error that occurs also varies and the benefit of using ADC will be lost.

The PGA for the ADC offers benefits of high resolution and low noise at high gain , but without the disadvantages of requiring regular calibration every time the range is changed. A buffered input and new reference sampling scheme avoid many of the problems associated with previous multirange ADC.

All the delta sigma ADC’s , registers, filters, multipliers are controlled by reset of master clear and this pin is also used to change their serial interface and behaviour or functionality. The logic 0 controls the ADC and registers in reset condition. The only one that uses power during master clear is oscillator.

The microcontroller manufactures produce other design products so that they are related to their own design and in this we require another output pin. This condition or situation is correct for small design products where they have eight pins are fewer than that.

This microcontroller has two output pins, one input pin , RAM flash and ADC module .For programming the microcontroller mode you need MCLR and supply pins(VCC and GND). To run or make the coding active we need mainly power supply and MCLR,microcontroller must see the difference between normal and program mode. Here the MCLR takes 12V to enter program mode and it takes external reset or input pin to enter into normal mode.

The microcontroller design uses one pin for analog input and has other three outputs and it also requires an additional output, so for this reason the circuit uses MCLR pin as output. To make MCLR pin to act as output the microcontroller uses weak pull-ups.

Analog to Digital Conversion (ADC) is the process of sampling continuous analog signal and converting the signal into quantitized representation of signal in digital domain and all the ADC architectures will convert analog signal into digital representation.

The conventional ADC process takes input signal x(t) into sequence of digital codes x(n) at sampling rate fs=1/t, where T represents sampling interval this sampling function is equivalent to modulating input signal by set of carrier signals with frequencies 0,fs,2fs …. The sample signal is expressed as summation of original signal component and frequency, here the frequency modulated by integer multiple of sampling frequency. The signal component at frequency in input signal cannot be properly sampled and such signals get folded in base band signal creating in this non-linear is referred to as aliasing . Anti-aliasing filters are therefore required to prevent aliasing. Many A/D converters have successive or continuous approximation register and flash converters operate at nyquist rate fn. These converters sample analog signal at sample frequency equal to twice maximum frequency of input signal.

Sigma Delta AD converters do not digitize the incoming analog signal into digital sample of n-bit precision at nyquist rate, sigma delta ADC samples the analog signal by an sample ratio N resulting Fn<<FS and this sampling is done at lower precision. Almost all sigma delta ADC’s are mainly I bit A/D and the output of this modulator is proportional to magnitude of sine-wave input, this 1-bit A/D signal generated at N*fs(oversampling rate , nyquist rate ) can be digitally filtered and decimated back down to nyquist rate n-bit precision samples.

One of the advantages of sigma-delta ADC over nyquist ADC is the relaxation of the requirements for the anti aliasing filter. The requirement of anti-aliasing filter for nyquist rate ADC require sharp pass band (fs) to stop band (fn)

The sigma delta ADC contains simple analog circuits like voltage reference, comparator, integrator,summing circuit and switch and in this the digital circuit consists of digital signal processing which acts as filter. Now consider technique of oversampling in frequency domain when converting to dc signal it has quantization error up to ½ LSB and this sampled data has quantization noise. If ADC is less than perfect or exact value its noise is greater than quantization noise so due to this its resolution will be small than n bits and its actual resolution is given by

The sampling rate is chosen as Kfs then quantization noise is q/sqrt12 due to this noise will spread at bandwidth dc to Kfs/2 , So to reduce noise we use digital low pass filter at output with out disturbing the wanted signal. K is referred as sampling ratio and this sampling relaxes requirement on the analog antialiasing filter.

Here the data rate is less than the sampling rate and to satisfy nyquist criteria and this is done by using low pass filter to reduce the bandwidth, this process can be done by giving Mth result to output with neglecting the remainder and this process is known as decimation by factor M. This M can have any value such that output data rate is greater than twice the bandwidth.

If we use oversampling to improve resolution then the oversampling must be factor of 22N to get N bit resolution increase, the sigma delta converters does not require any large oversampling because it limits to pass band signal and shapes the quantization noise to fall outside the pass band as shown in figure.

Here we have 1-bit comparator (ADC) when we use it integrator output, then sum the input voltage with output of 1-bit DAC which we get from ADC output.. The digital low pass filter and decimator at digital output are added to get sigma delta ADC and after this signal is given to modulator where it modifies quantization noise by making it to lie above pass band filter ,so due to this the ENOB is larger than the expected sampling ratio.

Read also  Cost Comparison Between Duplex Steel And Carbon Steel Engineering Essay

The sigma delta ADC operation is like the input given as Vin which is dc and the integrator consistently move up and down at node A and here output of comparator is given to 1-bit DAC and summing point at node B. This negative feedback value will force the average dc voltage at node B to be equal to Vin. The output voltage from the DAC is controlled in the 1-bit data stream of the comparator output. After that when the input signal rises at Vref, the number of ones at the serial bit stream also increase and due to this there is decrease in zeroes and in the same way as the signal of Vref goes negative the serial bit stream at one decrease and at zero it increases. Here it shows that average value at voltage as input is in serial bit stream which comes from comparator and decimator and filter allow stream and give output.

The data from the 1-bit ADC is not worth full when the given input value is single sample interval, so when we have more number of samples that are averaged will provide correct value. The sigma delta can not give detailed values in the time domain because of the single bit data output, so when the single input is near positive side it shows more ones than zero and in the same way when the input signal is near to negative it shows more number of zeroes than ones and if it is in midscale then it shows equal number of zeroes and ones.

The below figure shows the output of integrator for two conditions where the first one is for input zero near the midscale so decode them pass output samples through low pass filter that averages every four samples this shows the bipolar zero. So from this we can say that if more number of samples are averaged more dynamic range is obtained.

The sigma delta ADC can also be seen as synchronous voltage to frequency converter with the counter. If the number of ones in the output data stream is counted from the samples then the counter output will give digital value of output, this method applies only when have dc or for slow changing input signal. The 2N clock cycles are counted to achieve N-bit resolution and there by for getting effective sampling rate.

Here noise shaping is explained in frequency domain by using sigma delta modulator. In this the integrator which is present in the modulator represents an analog low pass filter with transfer function H(f)=1/f and this transfer function shows that the amplitude not directly proportional to frequency.

The one bit quantize gives quantization noise Q and it is given to output sum block. If we have input signal X and output signal Y the value that comes out of summing point is X-Y and after that it is multiplied by the transfer function and this is given as,

From the equation if we see that if f=0 the output Y reaches X with no noise , and at high frequency the amplitude of the signal reaches zero and noise value reaches Q. So due to this the analog filter has signal effect on low pass and high pass effect on noise Q. This filter does noise shaping at given frequency in delta sigma model and higher order filter gives more attenuation in sigma delta modulators but some precautions should be taken.

We get good quantization noise and best ENOB for given sample when we have more integrator and summing points in sigma delta modulator.

This figure is giving the relationship between order of sigma delta modulator and oversampling amount to reach SNR. If oversampling is taken 60 then the second order capable of giving SNR of 80db and also gives ENOB value as 13 and in this we have filter to reduce noise and decimator to decide degree.

This carries 13 bit outside but if you want to use additional bits, these added bits that carry signals has no useful value and buried in quantization noise unless the post filtering is used. The resolution can be increased from the 1-bit system by increasing the oversampling ratio or by higher order modulator.

In the other method for the waveform output we give current and voltage as input which are 16bit and then given to second order sigma delta ADC where it oversamples input at frequency equal to MCLK/4 and with this it allows for wide range of input signals.

The input current channel (channel 0) usable range is increased with the programmable gain amplifier and this is linked with block diagram of MCP3909 and gives in detail of its signal processing blocks.

To cancel the system offset on both the channels we use to high pass filter and from output of filter we get voltage and current, so when calculating power we should not get any offset. As this signals are not having DC offset so the averaging technique is used to give active power output.

The power signal at we get after filtering is active power output it is DC component and for averaging technique use sine and non-sine waveform after this the ADC takes real power to give output pulse where the frequency is directly proportional to real power. The frequency present at FOUT 0, FOUT1 outputs are used to drive counters and stepper motor which shows power consumed.

Every pulse from F0, F1, F2 settings are used to give fixed amount of energy , the HFOUT has less integration and high frequency to represent power signal and due to less time it helps the user to get values fastly under steady condition. .

For the current and voltage transducers the MCP3909 analog inputs are connected and each pin has specifications like it should pass from 5kV to 500V contact charge. The differential input is given for both the channels to reduce noise and absolute voltage should be kept at 1V related to AGND so this can do error measurement.

The common mode signal is taken to respect both last condition and input voltage difference range and for good common mode ration to should be referred to ground. The current channel has PGA gain to measure small signal with out other signal. The maximum differential voltage we have at channel0 is 470mV/Gain. The maximum voltage fro channel1 is 660mV. For channel 0 gain selection is given as,

This MCP3909 has internally POR to check supply voltage AVdd and this check when the systems power is on or off. This POR has built in hysteresis and timer to check potential ripple and noise on power supply. For this the threshold voltage is typically set to 4V. The MCP3909 is kept in reset state if the supply voltage falls less than threshold voltage and hysteresis value is 200mV to prevent glitches.

Once the power is on the internal timer stop sending the pulse with MCLK=3.58MHz there by preventing potential metastability.

For calculating the active power the MCP3909 use digital filter which is first order IIR filter where we can extract real power (DC component) from the power signal. Since the input power signal has harmonic content. We get ripples from the filter output at line of frequency when the filter is not ideal.

To reduce the noise for line frequency at 50Hz we use cut off frequency as input clock (MCLK=3.58 MHz). The rejection of frequency component will be more than 20db. In this at the frequency converter the output of filter is stored and then it is helpful to compare threshold for Fout0/1 and HFout and each time threshold is crossed we get pulse.

The Fout0/1 require more energy to get output pulse than HFout , like integration period and as this acts as filter the output ripple or noise is minimum. The threshold or transfer function of HFout and Fout0/1 are different to each other.

The threshold energy or transfer function are different to each other , the Fout0/1 output frequencies are quite low in order to allow integration.

In this synchronous serial transmission clock is shared between sender and receiver or the sender gives timing signal so that the receiver knows when to read next bit of data. In this serial transmission if we do not have data to send then fill character is sent instead of data so to keep transmission continually, these synchronous communication is efficient because in these we have only data transmission between sender and receiver.. for example the synchronous transmission is used between printer and fixed device where data is sent in one set of wire and clock is sent in different wire.

This RS 232 is asynchronous serial communication method which is used for computers and others, it is called as asynchronous because there is no synchronizing clock present like which is in SPI where it is serial protocol, the serial protocol is such that it automatically synchronize itself. We can use RS 232 to easily create data link between boards and standard PC, you can makes data loggers that read analog value from ADC and give it to PC this is done by writing program that shows data with using graphs.

In serial communication the byte is sent or transmitted one bit at time but in parallel communication the whole data like byte (8 bit) transmitted at a time. So for that we use parallel communication to send data in shorten distance like between graphic card and CPU and these parallel can have say many wires as possible , but serial communication uses one wire to transfer data so it is used for long distance.

In series the logic level changes with the bit being transmitted (0 or 1) and to know which is start bit and end bit in byte we need to add synchronize line and note the value of data line when the clock line is high but this is the way the serial buses like SPI work . UART is not having clock because it is asynchronous but start bit and stop bit are used to synchronize the incoming data.

When the word is in transmission start bit is added at start of each word and this tells the receiver that data is read to sent and forces the receiver clock to be synchronous with clock of transmitter. These two must not have same frequency drift but can have same clock. After the start bit is sent each bit in word are given least significant bit (LSB) and each bit from transmitter is sent with same time and receiver is in half way to check that bit is one or zero. The sender will not know when receiver looks at the bits but sender knows when the clock says to begin to send next bit of word.

When the complete data word is sent the transmitter adds parity bit and at the receiver uses this parity bit for error checking and at last the one stop bit is sent by the transmitter, if the receiver does not receive the stop bit when it is supposed to be the UART thinks the entire word to be garbled and reports framing error to host when data word is read. This framing error occurs because the sender and receiver clocks are not running at same speed.

Whether the data is sent or not the UART automatically discard start, stop and parity bit and if another word is coming the start bit for new word comes as soon as the stop bit for existing word been sent

RS 232

In this it has two data line like RX and TX , where TX is the wire where data is sent out to other device and RX is the line in which other device put data it needs to send. We know that high = 5v and low =0v for MCU boards and this RS 232 has high=12v and low=-12v. So to make RS 232 to interface with MCU which understands 0 to 5 volts we use MAX232.

As RS232 has no clock line for synchronization perfect timing is needed so transmissions are carried out in certain speed which is bits per second and number of bits transmitted per second is know as baud rate. Some standard rates are 1200, 2400, 4800, 9600, 19200, … etc.

RS 232 – Level conversion

As seen above the RS232 signals differ from signals in MCU, this level converter will convert RS 232 signals from -12 to 12 volts from PC to signal 0 to 5 volts to fed to MCU.

It is good to check the operation so we use converter to see its working nature, so for this we need Hyper-terminal windows software which is used to open COM port and to send and receive textual data. For testing we need to connect output RX/TX together so data written to COM ports to enter our circuit and converted to MCU board signal level.

After this understand the USART of AVR Microcontroller and write code to activate USART to send and receive data, like other microcontrollers AVR also has main hardware for serial communication this is called USART. In this USART hardware you need to write data to one of registers.

Clock generation.

This generator generates the base clock for transmitter and receiver, this USART supports four modes of clock operation 1. Normal Asynchronous, 2. Double speed asynchronous, 3. Master synchronous and 4.slave synchronous mode. The UMSEL bit in the UCSRC (control and status register) is the one that selects between synchronous and asynchronous operation. Double speed(asynchronous mode) is controlled by U2X found in UCSRA register. When UMSEL=1 the data direction register for the XCK controls weather the clock source is internal (master mode) or external (slave mode) and this is shown in block diagram

Txclk- transmitter clock(internal signal)

Rxclk – receiver clock(internal signal)

Xcki – used for synchronous slave operation

Xcko – used for synchronous master operation

Fcso- system clock

Baud rate generator

The USART Baud rate register and down counter are connected as programmable prescaler or baud rate generator. The down counter which is running at the system clock(fosc) is loaded with UBRR value each time the counter has counted down to zero and clock is generated each time counter reaches zero and the clock generated is the baud rate generator clock output = fosc/(UBRR+1).

The transmitter divides the baud rate generator clock output by 2,8.16 depending on the mode and this baud rate generator is directly used by receiver clock and data recovery units.

The baud rate generator equations are given as,

Operating mode

Calculating baud rate

Calculating UBRRvalue

Asynchronous normal mode

Baud= fosc/(UBRR+1)16

UBRR= fosc/16baud  – 1

Asynchronous double speed mode

Baud= fosc/(UBRR+1)8

UBRR= fosc/8baud  – 1

Synchronous master mode

Baud= fosc/(UBRR+1)2

UBRR= fosc/2baud  – 1

Read also  Bridge expansion joints – performance and materials

External clock

The synchronous mode operation is done by using external clock and external clock input from XCK is sampled by synchronous register to reduce change in stability and the output from synchronous register must pass through edge detector before it is used by transmitter and receiver. This process includes two CPU clock period delay and its frequency is given as

FXCK < fosc/4

USART of AVR

The USART of AVR is connected to CPU by these six registers

UDR- USART Data Register: basically this is not one but two register , when you read it data is stored in receiver buffer and when you write it gives to transmitter buffer.

UCSRA: USART Control and Status Register: as it name says it stores some status about USART and there are some of this kind like UCSRB and UCSRC.

UBRRH and UBRRL: This is USART baud rate register, it i s16 bit wide so UBRRH is high byte and UBRRL is low byte .

To write programs with using USART you need to study about each register, the seen behind using USART is same with other internal peripheral. now we will describe each registers clearly

This bit is set when USART completed receiving byte from host and program should read from UDR and this flag bit is set when unread data is present in receiver buffer and gets cleared when receiver buffer is empty. If the receiver is disabled, the receiver buffer is flushed and the RXC will completely zero.

Bit 6- TXC: transmit complete

This bit is set 1 when USART has completed transmitting byte to host and program can write new data to USART through UDR. The transmit flag bit is cleared automatically when TXC interrupt is executed.

Bit 5 – UDRE – USART Data Register Empty

The UDRE flag first tells us that the transmit buffer (UDR) is ready to receive data , so if UDRE is one then buffer is empty and the UDRE flag can generate data register empty interrupt.

Bit 4 – FE- frame error

This bit is set when character is sent to receive buffer has an frame error, these FE is zero when stop bit of data received is one and it is present until the receiver buffer is read.

Bit 3 – DOR – data over run

This data over run occurs when the receiver buffer is full with character and still it has new character waiting to receive shift register and new start bit is detected and it is valid until the buffer had read it and set this to zero when it is writing to UCSRA.

Bit 2 – PE – parity error

When the next character is received in buffer and has parity error when received then parity checking is enabled at point UPM=1 and it is valid until the receive buffer (UDR)is read.

Bit 1- U2X- double the USART transmission Speed

This bit is activated for asynchronous operation and keep this bit zero when using synchronous and writing this bit to one will reduce baud rate divider from 16 to 8 by doing this it increases transfer rate of asynchronous communication.

Bit 0 – MPCM – multi purpose communication mode

When MCPM bit is written one the frames that are received by USART receiver that do not have address information will be ignored and transmitter is not affected by MCMP SETTING

Here the UCSRC and UBRRH registers share same address , so to decide which register user want to write is decided by 7th bit of data , if it is 1 data is written to UCSRC else it goes to UBRRH this 7th bit is called URSEL(USART register select)

Bit 5:4 – UPM1:0 – parity mode

This bit is enabled when transmitter will automatically generate and send parity with each bit transmitted frame and receiver will generate parity value for incoming data and compare it to UPM0 .if mismatch is detected the PE flag in UCSRA is set.

So we set UCSRC =(1<<URESL)|(3<<UCSZ0)

Bit 0 – UCPOL – clock polarity

This bit is used for synchronous mode when it is one and bit to zero when asynchronous mode is used. The UCPOL bits set relation ship between data output and data input sample and synchronous clock(XCK).

Bit 7 – RXCIE:Receive Complete Interrupt Enable:

when this bit is written one then related interrupt is enabled , the global interrupt flag in SREG is written one and RXC bit in USCRA is set.

Bit 6- TXCIE:Transfer Complete Interrupt Enable:

when this is one then related interrupt is enabled, the global interrupt in SREG is written to one and TXC bit in UCSRA is set.

Bit 5 – UDRIE – USART data register empty interrupt enable

When writing this bit to one enables the interrupt in UDRE flag and global interrupt flag in SREG is written to one when UDRE bit in UCSRA is set.

Bit 4 -RXEN:Receivable Enable

when you write bit to one the USART receiver is enabled and you see that its related i/o pin switch to its secondary function. And invalidate the FE, DOR and PE Flags.

Bit 3 – TXEN – transmitter enable

When enable the transmitter thing is over ride in normal port operation and when disabled the shif register and buffer register transmitter are no longer overridden at the TXD port.

Bit 2 -UCSZ2:USART Character Size

The UCSZ2 bits combined with the UCSZ 1:0 bit in UCSRC set the number of data bits.

Bit 1 – RXB8 – receive data bit 8

This bit is active when the character that it takes has 9 bits and must be read before reading the low bits from UDR.

UCSRB=(1<<RXEN)|(1<<TXEN).

Some functions of usart to be seen to write program

USARTReadchar(char data ) function

It helps to read data from USART , if we use PC to send data to your microcontroller the data is automatically received by the USART of AVR and put in buffer and bit in register UCSRA (universal synchronous/asynchronous receiver/transmitter control and status register A) is set to indicate data in buffer . Now it is our duty to read this data from register and process it other wise if new data comes previous data will be lost . so wait until RxC bit (bit no7 ) in UCSRA is SET and then read the UDR register of USART.

Syntax

Void While(!(UCSRA & (1<<RXC)))

{

{

// DO NOTHING

}

// now usart got data from host and available in buffer

Return UDR

}

USARTWrite char()

It helps to write given char data to USART , actually we write to buffer of usart and rest is done by usart that means it automatically sends data over RS232 line. Before writing check weather free or not, if not free we wait until it is free it means usart is still busy sending some other data and once finished takes new data from buffer.

Note that in buffer it is not current data which the usart is busy sending , usart reads data from buffer to its shift register which it starts sending and thus buffer is free from data.

Every time usart gets data from buffer and thus making it empty it notifies this to CPU by telling UDRE(USART data register ran empty) . it does by setting bit (UDRE bit no5) in UCSRA register.

Syntax

Void USARTWrite char()

{

// wait until transmission is ready

While (! (UCSRA & (1<<UDRE)))

{

// do nothing

// now write data to usart buffer

UDR= data;

}

}

UDR= data ; // data goes to transmitter

Data = UDR; // data comes from receiver

Using the USART of AVR Microcontrollers : Reading and Writing Data

SPI

SPI bus is mainly 4 wire serial communication used by microprocessor peripheral chips. This SPI is synchronous serial data link which is standard one developed by Motorola and it provides support for low/medium bandwidth connection between CPU and other devices.

SPI bus is normally synchronous serial interface for connecting low speed devices with less number of wires, in this a synchronous clock shifts serial data in and out microcontroller in terms of 8-bits.

SPI bus is master/slave interface and when two of them communicate one is used as master and other as slave device. The master gives serial clock and in SPI data is simultaneously transmitted and received because it is full duplex protocol.

Many devices communicate using master/slave relation, where master initially gives data frame. When master generates clock and selects slave device data can be transferred in both directions so master and slave should know that the value they get is meaning full or not.

SPI has four signals as, clock (SCLK) , master data output and slave data input(MOSI),master data input and slave data output(MISO), and slave select(SS). In it two are data signals (MOSI and MISO) other two are control signals (SCLK and SS).

The master provides clock signal for synchronization and clock signal controls and tells when the data is valid for reading and when data can change. As SPI is synchronous it has clock pulse along with data while RS -232 and other asynchronous do not use clock but data must be timed accurately.

As SPI has clock signal , this clock can change with out change in data but the data rate can change with the change in clock rate . This makes SPI ideal when microcontroller clock is not clear.

The master device controls the clock line (SCK) and no data is transferred untill the clock is changed and all slaves are controlled by clock which is controlled by master device. In slave the clock cannot be changed but SSP register will control how device will respond to the clock input .

SPI is known as data exchange protocol so as data is clocked out new data is clocked in. So when data is transmitted this data must be read before transmitting again otherwise data will be lost and SPI becomes disabled.

These SPI is used transmitter/receiver because it has two data lines one for input and other one for output ,this data exchange is controlled by clock (SCK) which is controlled by master device.

Slave select(SS) will control when device is accessed and this signal must be used when we have more slaves in system and it is optional when we have one slave in the circuit. This SS indicates to slave that master wishes to start SPI data exchange between slave and itself .

The signal is most often active low and as line is low it indicstes that SPI is active ,and it is often used to improve noise immunity in system and its function is to reset SPI slave so that it is ready to receive next byte.

Block diagram

The system has two shift registers and master clock generator and when the slave is selected low the SPI initiates the communication. Master and slave prepare to send data in their shift registers and master produce clock on SCK to interchange data.

SS or CS Pin Functionality

When the master mode is set then SPI has no automatic control over CS line this status can be controlled by software before communication starts and writing byte to SPI data register activates clock and hardware shifts 8- bits into slave. After transmission the clock stops setting the end of SPIF for transmission .

After that the SPIE (interrupt enable) in the SPCR register is set the master continue to shift next byte by writing into SPDR thenn at last the incoming byte is kept in buffer for last use.

Now when slave mode is taken the SPI is still sleeping with MISO state untill the CS is made high , in this state software can update the data in SPI register (SPDR) but still data is not shifted out by the clock made high untill the CS is driven low.

As one byte completely shifted the end of transmission is done thwn the SPCR is set with the SPIE enabling and interrupt is requested . the slave continues to place new data into SPDR before reading imcoming data and the last incoming byte is kept in buffer register for future use.

SPI is high speed synchronous data transfer between microcontroller and other interface. Uses three wires for synchronous data transfer and operates in master or slave and allows LSB or MSB first bit to transfer and supports multi bit rates and also supports speed master SPI mode.

As we have seen the SPI uses three wires and the SS of slave is connected to ground this enables slave device , if you want to keep slave mode on sleep use SS to activate SPI by pulling low and this pin makes slave to be active from sleep mode.

Here the system is single buffered in transmission direction but doubled buffered in receive direction that means the byte transmitted cannot be written to SPI data register before shift cycle is completed. When receiving data the received byte can be read from SPI data register before next byte has been shifted

This SPI interface uses mainly three internal registers like SPCR,SPSR and SPDR, but from this three we mainly have to discuss about

When the serial transfer is complete then SPIF flag is set and when this is set the interrupt is generated to SPCR and this sets as global interrupt and enables it. If CS is input and given low the SPI in master mode also set SPIF flag , this flag is cleared with hardware when running the interrupt vector.

Bit 6- WCOL- write collision flag

This bit is set when the SPI data register is written usning data transfer and this WCOL bits are cleared when first reading the SPI status register.

Bit 5 to 1 this bits are reserved in atmega 16 and always read zero untill changed.

Bit 0 SPI2X Double the SPI speed

When these bit is given logic one the speed of SPI is doubled when this SPI is in master mode and minimum SCK period will be tw clock periods and when SPI is in slave mode SPI works at Fosc/4 or less.

SPDR- Data register

These is read /write register used to transfer data between register file and SPI shift register , writing to this register shows data transmission and reading the register causes shift register receive buffer to read.

The SPI has four combinations of SCK phase and polarity with respect to data . if chip has control bits in these four states they are reffered as clock polarity (CPOL) and clock phase(CPHA ). The SPI transfers data in 8-bit block and you can transfer as many 8-bits you want , for 16-bit to write value active low CS starts from begining of first 8-bits and ends at 16th-bit.

The MCP3909 device contains three serial modes that are used by changing pin functionality of NEG ,F2,F1,F0 pins to SDO, SCK, SDI , CS. These modes are entered by giving MCP3909 serial command on pins during time window (twin) after reseted . During this window time F2 as SCK, F1 as SDI,F0 as CS after they entered in serial mode the device must be reset to do it we use MCLR pin or power on reset.

Due to this the SPI data can access upto 20MHz, this speed enables quick data change between conversion time. After all the modes are entered the PGA ,A/D converters, HPF,LPF,Multiplier and other digital sections are functional in energy metering system.

Read also  Stackelberg Leader Follower Models For Strategic Decision Making Engineering Essay

Here is the coding that helps to write in c which enables the input and output and also sets the registers for both master and slave

It shows the transfer of data between SPI and Master

Void SPI_MasterInit(void)

The USB has asymmetric design having host, downstream ports and multiple peripheral devices connected to star topology . Many USB hubs can be included in tiers and allowing tree structure with up to five tier levels .

The USB host has multiple controllers and each controller provides one or more USB ports this are linked in series to hubs and it always has one root hub which is built into the host controller.

The universal serial bus is host controlled and this can be only one for bus, the USB has host controller and multiplier connected in tree like fashion using hub devices. USB’s main advantage is to reduce the need of adding expansion cards into computer and improve plug and play facility by allowing devices to swap or add data to system without rebooting.

The MCP3909 ADC processing board for 16-bit MCU also contain USB connection for high speed sampling and data collection. This circuit also has 512x 8 SRAM for data collection.

Loading of this driver is done using PID/VID(product ID/vendor ID) which is attached to hardware , USB has its own controllers for usb1.1 it had UHCI(universal host controller interface ) and OHCI(open host controller interface) and for usb2.0 we use EHCI(enhanced host controller interface).

USB pins

USB is serial bus. It has four wires of which two are used for puwer supply(+5v and GND ) and other two for differential data signals(D+,D- pins). NRZI(non return zeron invert) used to send data with sync field to synchronise the host and receiver clocks.

USB supports three data rates, low speed data rate is mostly used for human input devices like keyboards, printers etc. Full speed data rates are supported by USB hubs assume that the devices divide the USB bandwidth in first come first serve basis so it is easy to run out of bandwidth with several devices.

AT mega 16

The AT mega 16 is low power CMOS 8-bit microcontroller based on AVR enhanced RISC architecture. RISC (reduced instruction set computer) , it is microprocessor architecture that uses small, highly optimized set of instructions rather than more specific set of instructions and this are the features that are beign used by most RISC processor,

One cycle execution : mainly RISC processor have CPI of one cycle and this is due to clear usage of each instruction on the CPU and technique called ;.

Large number of registers the RISC design builds large number of registers to prevent large amount of interaction with memory.

The AVR core combines large set of instruction set with 32 general registers and all these registers are directly connected to ALU which allows two independent registers to get connected to one single execution clock cycle. These RISC architecture long code is efficient in giving output ten times faster than CISC microcontrollers.

Port A is mainly used to serve analog inputs to analog to digital converters. This port A is used as 8-bit bi-directional input/output port if the A/D converter is not used . this port A also used as intrenal pull up resistor and its output buffer has symmetricl characterstics with both high sink and source usage.

If the pins from PA0 to PA7 are used as inputs and pulled low externally then these internal pull up resistors get activated with the current source.The port A pins are in tri-state and in this reset condition is active even if the clock is not running.

Port B (PB7 – PB0)

Port B is an 8-bit bi-directional input/output port with internal pull up resistors and output buffer has symmetrical characterstics with high sink and source capability. When the port B pins are externally pulled low then source current is produced if pulls up resistors are activated. This port B is tri-stated and reset condition is active even if the clock is not running.

Here we take master clock output ,slave clock as input for SPI channel and when SPI is enabled as slave this pin is taken as input regardless of DDB7 setting. When SPI is enabled as master the dat direction is controlled by DDB7

MISO Port B bit 6

Here we have master input and slave output pin for SPI channel , when SPI is enabled as master then it is taken as input regardless of DDB6 and when SPI is slave the data direction is controlled by DDB6.

MOSI Port B bit 5

Here we have master output and slave input and this pin is active regardless of DDB4 and the SPI will be slave when this pin is driven low and data direction of this pin is controlled by DDB4 when master is enabled.

SS PortB bit 4

This is slave select and SPI is taken as input regardless of DDB4 and it is activated when pin is driven low.

Port C (PC7 to PC0)

It is 8-bit bidirectional I/Oport with internal pull up regsistors and has linear relation ship with high sink and source. The port C pull up resistors are active when the source current produced from external pull low of port C pin.

If the JTAG interface is enabled the pull up resistors on pin PC5, PC3, PC2 will be activated even if reset occurs.

Port D (PD7 to PD0)

These portD is also 8bit bidirectional input/output port wih internal pull up resistors and it is tri stated where reset conditon is active even if clock is not running.

This AVCC is the supply voltage for the portA and A/D converter. It should be externally connected to VCC even the ADC is not used and if adc is in use it should be connected to VCC through low pass filter.

Easy AVR Development board

The above diagram is the Easy AVR 5A microcontroller for my project AC power logger using MCP3909 I used the above AT Mega 16 kit. Here the AVR is made to work with microprocessor coding and this AVR board allows assembly and C language programming where I developed the source code using C programming.

Here we selected Easy AVR 5A board where it has many on-board peripheral such as LCD and LED and these are selected by switches. USB cable provides program communication and power connection.

Here in these board graphical LCD and normal LCD modules are removable but must be used carefully because they are sensitive to electrostatic voltage discharge and mis-connection so take them or keep them to board when supply is off.

Here we use AVR Studio with the Win AVR/GCC complier and this is free to all users and widely used standard one.To run this AVR board GCC compiler is used to debug code where normally code is written in C , assembler or mixture of both. After compilation many downloaded files are obtained with the .hex file.

This .hex file is then transferred to board using second stage called AVR FLASH , check weather the board connected to CPU and Easy AVR with USB cable and check it is ON/OFF and switch button to ON.

AVR STUDIO

Here we should see AVR studio a given window is obtained then click on new project and write name in space box and click next from the that we get select AVR simulator and device to AT Mega 16 and click finish

After clicking finish button we get three block windows like project tree window in left and editor window and build window.

Now the next step is to copy and paste the code into the editor window and configure it. In this configure window change the frequency to 8MHz and click ok and check that we get that build is successfull with 0 warnings and 0 errors.

AVR FLASH

To download hex file open AVR flash from the programs and check that device is set to AT Mega 16 and that frequency is set to 8.0MHz and after then we get small red USB symbol present in window and check weather SW6 buttons all ON and SW9 LCD_BCK and TX ON. Then load the coding and click write and check for errors.

Now after running the program we get output and now if we check the pin with oscilloscope we get pulse wave from.

Coding

Now after having knowledge about what the project is doing and what each part in MCP3909, SPI, USART, and Easy AVR AT Mega16 Board internally are doing and after this by giving the related connections and now we build the program.

1.Active pulse output

In this we give connection between SPI, USART, PC and when we run the program using AVR Studio and FLASH and find the graph using oscilloscope we get pulse output which show the count and says that energy is consumed.

#include<avr/io.h>

#include<util/delay.h>

#define FOSC 8000000 // clock frequency

#define BAUD 9600

#define MYUBRR FOSC/16/BAUD-1

//initialize UART//

void USART_Init(unsigned int ubrr)

{

//Set Baud Rete//

UBRRH=(unsigned char)(ubrr>>8);

UBRRL= (unsigned char)ubrr;

//Enfeeble Receiver and Transmitter//

UCSRB = (1<<RXEN)|(1<<TXEN);

UCSRC = (1<<URSEL) | (1<<USBS) | (3<<UCSZ0);

}

void USART_transmit(unsigned char data)

{

//Wait for empty transmit buffer

while(!( UCSRA & (1<<UDRE)));

//put data in to buffer//

UDR=data;

}

void USART_send_string (unsigned char *strdata)

{

while(*strdata != ‘’)

{

while( !(UCSRA & (1<<UDRE)));

//Put data in buffer//

UDR = *strdata;

strdata++;

}

}

unsigned char UASRT_Receive(void)

{

// Wait for data to be received //

while(!(UCSRA) &(1<<RXC));

//get receive data from buffer//

return UDR;

}

int main(void )

{

unsigned char pindata, temp;

unsigned int count=0;

DDRA=DDRB=DDRC =0xFF;

DDRD =0x7F; //PD7 is connected to FOUT 2 of MCP3909

USART_Init(MYUBRR);

USART_send_string(“nr Energy metering IC with active power pulse output nr”);

while(1)

{

do

{

pindata = PIND;

pindata = (pindata & 0x80 )>>7;

}while(pindata!=1);

count++;

if((count%100)==0) // 100 pulse =1unit

{

USART_send_string(“nr power consumsed is”);

temp = count;

USART_transmit(temp/100);

temp=temp-((temp%100)*100);

USART_transmit(temp/10);

USART_transmit(temp%10);

}

do

{

pindata = PIND;

pindata = (pindata & 0x80 )>>7;

} while(pindata!=0);

}

}

Source Code explanation

#include<avr/io.h>

Here, we are including the AVR Input / Output header file in our program.

#include<util/delay.h>

Here, we are including the AVR delay header file in our program.

#define FOSC 8000000 // clock frequency

Defining the FOSC of the AVR as 8MHZ

#define BAUD 9600

Defining the Baud rate of the serial communication as 9600 bits/sec

#define MYUBRR FOSC/16/BAUD-1

Baud Rate calculation

//initialize UART//

This program is used to initialize the USART

void USART_Init(unsigned int ubrr)

{

//Set Baud Rate//

UBRRH=(unsigned char)(ubrr>>8);

Assigning to the baud rate high order register

UBRRL= (unsigned char)ubrr;

Assigning to the baud rate low order register

//Enfeeble Receiver and Transmitter//

UCSRB = (1<<RXEN)|(1<<TXEN);

Enabling the receiver and transmitter mode of USART

UCSRC = (1<<URSEL) | (1<<USBS) | (3<<UCSZ0);

Enabling the 1 stop bit for USART communication as well as 8bit data mode , no parity

}

This program transmit the char of data through RS232

void USART_transmit(unsigned char data)

{

//Wait for empty transmit buffer

while(!( UCSRA & (1<<UDRE)));

//put data in to buffer//

UDR=data;

}

This program transmit the string of data through RS232

void USART_send_string (unsigned char *strdata)

{

while(*strdata != ‘’)

{

//Wait for empty transmit buffer

while( !(UCSRA & (1<<UDRE)));

//Put data in buffer//

UDR = *strdata;

//incrementing the pointer//

strdata++;

}

}

This program receive the character of data through RS232

unsigned char UASRT_Receive(void)

{

// Wait for data to be received //

while(!(UCSRA) &(1<<RXC));

//get receive data from buffer//

return UDR;

}

int main(void )

{

unsigned char pindata, temp;

unsigned int count=0;

Declare the PORT A,B,C as Output

DDRA=DDRB=DDRC =0xFF;

Declare the PORT D 0 to D6 as Output and D7 as input

DDRD =0x7F; //PD7 is connected to FOUT 2 of MCP3909

Calling the function Initializing the USART

USART_Init(MYUBRR);

Send a string of data “Energy metering IC with active power pulse output ” through RS232

USART_send_string(“nr Energy metering IC with active power pulse output nr”);

while(1)

{

This loop is for infinite

do

{

Read the data from PD7 pin

pindata = PIND;

Mask it to LSB position

pindata = (pindata & 0x80 )>>7;

Continue to read the PD7 pin till it becomes 0

}while(pindata!=1);

Increment the count value,

count++;

If count is terms of 100 , then another variable count1 is incremented, Now the count 1 is proportional to power consumed

if((count%100)==0) // 100 pulse =1unit

{

count1++;

USART_send_string(“nr power consumsed is”);

temp = count1;

Display the power consumed to hyper terminal

USART_transmit(temp/100);

temp=temp-((temp%100)*100);

USART_transmit(temp/10);

USART_transmit(temp%10);

}

do

{

Read the data from PD7 pin

pindata = PIND;

Mask it to LSB position

pindata = (pindata & 0x80 )>>7;

Continue to read the PD7 pin till it becomes 1

} while(pindata!=0);

}

}

Wave form using SPI

In this method we give connection between SPI, USART and PC.When we run the coding or program the voltage and current will be displayed in HyperTerminal.

#include <avr/io.h>

#include <util/delay.h>

#include <stdio.h>

#define USART_BAUDRATE 9600

#define BAUD_PRESCALE (((F_CPU / (USART_BAUDRATE * 16UL))) – 1)

char prn[32]; //buffer for printing

#define _CS_HI PORTB |= (1<<PORTB4) //SPI _CS = PB4, using SS as output

#define _CS_LO PORTB &= ~(1<<PORTB4)

#define _RST_HI PORTB |= (1<<PORTB3) //MCLR MCP3909 driven from PB3

#define _RST_LO PORTB &= ~(1<<PORTB3)

#define SDO_HI (PINB & (1<<PB6)) //MCP3909 data ready is on MISO

//————————————————————————————————-

//SPI mode. Note that SS (PB4) MUST be configured as output; if set as input, it

//can disable the SPI port by putting master into slave mode. Use SS as a chip enable

//SPI communication on ATmega16 PB7 = SCK PB6 = MISO PB5 = MOSI PB4 = SS

void SPI_MasterInit(void)

{

DDRB = (1<<DDB5)|(1<<DDB7)|(1<<DDB4)|(1<<DDB3); // Set MOSI, SCK, SS MCLR output, all others input

SPCR = (1<<SPE)|(1<<MSTR)|(1<<CPHA); // Enable SPI, Master, clock rate fck/4, mode 0,1

}

unsigned char spi_readwrite(unsigned char value) //Sends AND receives a byte over SPI

{

SPDR = value; //put byte ‘output’ in SPI data register

while(!(SPSR & (1<<SPIF))); //wait for transfer complete, poll SPIF-flag

return (SPDR); //return value in SPI data reg.

}

void serial_init()

{

UCSRB |= (1 << RXEN) | (1 << TXEN); // Turn on the transmission and reception circuitry

UCSRC |= (1 << URSEL)|(1 << UCSZ0)|(1 << UCSZ1); // 8-bit characters – URSEL bit set to select the UCRSC register

UBRRL = BAUD_PRESCALE; // Load lower 8-bits into low byte of UBRR register

UBRRH = (BAUD_PRESCALE >> 8); // Load upper 8-bits into high byte of UBRR register

return;

}

void uart_putc(unsigned char c)

{

while (!(UCSRA&(1<<UDRE))); //Wait for USART data register empty

UDR = c; //put char into data register

}

void uart_puts(const char *s )

{

while (*s) //output string until terminator (0x00) arrives

uart_putc(*s++);

}

/*————————————————————————————————-

Main program here. To check that SPI is working:

Connect EasyAVR to PC with USB and Serial cables. Open Hyperterminal on COM1, 9600baud 8bits no parity 1 stop bit

When running, Hyperterminal will show a moving cursor with spaces. Link MOSI (PB5) and MISO (PB6) with a wire

The terminal will now show characters, which are being sent out of MOSI (check with a scope) and received back

through MISO, then relayed through the UART to the PC. Check SCK with scope too, this should show 8 clocks per byte

at high speed. spi_readwrite() can be used for reading writing or both.

————————————————————————————————-

For MCP3909: Connect PORT B as follows

Red VCC VCC

Yellow SCK PB7 sck

Green SDO PB6 miso

Blue _CS PB4 ss

Yellow SDI PB5 mosi

Black 0V Gnd

Green MCLR PB3 separate header, pin 2

The data or clock is given in when it is rising edge and the clock or data out when it i

Order Now

Order Now

Type of Paper
Subject
Deadline
Number of Pages
(275 words)