Friday, October 11, 2013

Lightning Discharges

     As a result of natural environmental phenomena, there may exist lots of  positive and negative charge centers in the air. The distance between those charge centers may vary up to 500 km long and their charge distribution changes. If the electric field density in the vicinity of a negative charge center reaches a critical value ,typically 10 kV/cm, the small length of air is started to be ionized and an ionized channel is formed. This ionized channel is also called "streamer". The critical electric field value for ionization is directly proportional to the breakdown value of air. This breakdown value can be changed by humidity and temperature but ionization is most likely start in large water droplets in air. 
     As I said, the distance between the positive and negative charges centers in air may vary up to 500 km ,thus, the excessive negative charges may prefer to discharge through ground (another positive charge center) which is much more closer to negative charge center. After first streamer ,about a couple of ten microseconds later, the second streamer arises and it follows the same way with the first streamer but it goes a little bit further than the first streamer. This process continues a number of times ,each time the ionized channel propagates 10 to 200 metres, up to the ionized channel is reached to a critical distance to ground. This process is called "stepped leader". Each time the stepped leader propagates in air, an excessive amount of negative charges move towards ground. When the stepped leader reaches to a distance of 10 to 50 metres from earth, the field intensity of the earth (positive charge center) reaches a sufficient value to form an upwards streamer in order to make connection between stepped leader and earth. Then the excessive amount of current flows from earth to clouds along ionized path so that the negative charges neutralized. This neutralizing current is called "return stroke". The figure below explains the whole characteristics of lightning discharges.

Figure 1: Lightning Discharge Phenomenon

Reference: EE575 - Advanced High Voltage Techniques (METU)

Thursday, June 13, 2013

Cascaded Multi Level Voltage Sourced Inverter Test

     Inverters are power electronic devices which converts DC to AC in power systems. In variety of areas inverters are used such as UPS (Uninterruptable Power Supply), Motor Drives, STATCOM, Active Power Filter (APF), Dynamic Voltage Restorers (DVR), Renewable based systems etc. There are lots of different inverters which are design for satisfying the requirements such as harmonic spectrum, voltage level, current level, DC link voltage or current, air or water cooled, thyristor or IGBT semiconductors etc. In my application, I will intruduce an inverter which is cascaded 5 level voltage sourced inverter for 13 MVAR STATCOM application. This inverter is used to supply required reactive power to the bus for reactive power compensation. Actually, there are 3 phases and 5 H-Bridge Inverters in each phase so that each phase have 5 level operation. DC link voltage for each H-Bridge is 1200 V in normal operation; however, I will test the whole systems' fiber optical connections and control algorithm by simply connecting 9 V batteries to their DC link capacitors. Figure 1 shows the cascaded 5 level voltage sourced inverter (6.5 MVAR systems in left and right side which are connected in parallel). Figure 2 shows the connection of 9 V batteries to the DC link capacitors.

Figure 1: Cascaded 5 level voltage sourced inverter ( 13 MVAR)

Figure 2: 9V Batteries connection to the DC link capacitors of Inverter

Figure 3 : 9V Battery Array

     This test is very important for High Power applications, because before energizing the inverter we should make sure that all of the fiber optical connections and control algorithm are correct. Also one of the most important thing is that the inverter's phase sequence should be fit the grids phase sequence. If the phase sequence and phase angles of each phase in mains are not completely fit with our control system, there may be excessive currents flowing through inverter. So we should check all the necessary connections and algorithms before we connect the system to the grid. 
     Each DC link capacitor is charged up to 1200 V DC and nominal current passed through each phase will be 600 Ampers in normal operations, however, we can do the test in very small DC link voltages (9 V batteries) with no load connected to the system so that we can check whether the IGBT's are turned on at the time it is fired or not. Also, we can check if there is a wrong connection or short circuit. 

     Test Results

     The 3 phase balanced 5 level voltage scheme is observed at the Oscilloscope screen as can be seen in figure 4. Note that the peak value of the waveform is 50 V, which is 5 batteries in series. The most important benefit of this test is that we realized that some of the fiber optical cables was broken while building the system in field. 

Figure 4 : Test Result in Oscilloscope

The batteries can be supplied from the links below.

Friday, June 7, 2013

Creating 100V DC Source Using Batteries

     Mostly for testing purposes, systems may require DC sources. These sources may have different levels from 1.5 V to some hundreds of volts. The easiest way for creating a DC source is using commercial batteries. There are variety of batteries with different voltage levels such as 1.5 V or 9 V. In my application, I needed a nearly 100V DC source for charging a capacitor. For this purpose, I cascaded ten 9 V batteries in a form as figure below so that I could measure 96.55 V using a multimeter. 

Figure 1: 96.55 V DC supply with battery stack

     Due to the shape and terminal structure of 9V alkaline batteries, we can form a rigid stack of batteries for getting a different levels of DC source. One can easily obtain DC sources in a discrete levels of 9.6 volts since a fully charged battery has 9.6 V. One of the most important thing with this stack is that it has dangerous voltage levels while the count of batteries getting increasing. However, also note that each battery has internal resistance so the current that can be supplied through batteries is limited. In other words, the DC source is very useful but it has limited power due to internal resistance.

The batteries can be supplied from the links below.

Friday, April 26, 2013

Power Quality Issues I: Voltage Sag and Swell

      Power Quality is one of the trend topics in energy industry. The term "Power Quality" simply focuses on the measurable features of the supplied power in a power system. Supplied power for some load is basically said to have quality (actually this is an hypothetical term), if the supplied voltage magnitude is at rated value and the frequency of it is constant at system synchronous frequency with no other frequency components. In addition to this simple definition, the term power quality can be enlarged to general term to represent a power system that does not contain any unintended, harmful components of voltage, current or power and any unintended phenomena at supplied voltage.
     All loads in a power system are designed to operate at its design specifications which are determined considering the rated values of an ideal mains supply. Thus, any unintended failures, voltage phenomena or harmful current components nearby are harms most of the loads. Actually, some of them are very vulnerable to unintended behaviours of mains. A supply with less quality (do not forget this is an hypothetical term) causes trouble to industrial loads and consequently this means the loss of labor, time and money for industrial plants. The power quality problems may be seen in supply voltage, frequency or nearby currents.In this article, I will mention one of the supply voltage problems that the industrial plants mostly face namely "voltage sag and swells".
     These kind of distortions  are usually due to overloading of huge loads, short-circuit failures or lightning discharges. Voltage sag is defined as the case when the magnitude of the mains voltage is reduced below 90% of rated voltage for a short while. Similarly, voltage swell is defined as the case when the mains voltage is increased above 110% of rated voltage for a short while. Actually, the interconnected network can not prevent these situations; however, it can only be protected by the protection devices after the failure is detected. In medium voltage level, the typical time that should be passed for a protection device to act on a failure is 100 msec. Thus the voltage sags and swells may last typically from 100 msec to a couple of seconds. During this time the voltage magnitude is reduced/increased significantly and the vulnerable loads should be protected during this time interval. Figure 1 illustrates a real voltage sag which is measured by a Class A power quality measurement device in field. As can be seen in figure 1, the three phase voltage sag is so severe that the supply voltage is dropped down to 90 V from 210 V.

Figure 1: Three Phase Simultaneous Voltage Sag

Similarly figure 2 illustrates a real voltage sag and swell happenning at the phase voltage components at 20kV Medium Voltage (MV) level.

Figure 2: Voltage Swell and Sag in a Three Phase Voltage

Actually, the voltage sag or swell lasts for a very short time in degrees of some hundreds of miliseconds; however, they may cause harmful results for industry. The harmful results of voltage sag/swell may be stoppage of pruduction, damages on motor drives, damages on raw or processed materials etc. For example, figure 3 represents the supply voltage and load current of an industrial printing house at the instant of the voltage sag occus.

As can be seen from figure 3, after voltage sag the load current is significantly reduced, which means a production stoppage. For these kind of instants ,actually, their motor drives loses their states and the paper inside the rolling machines are cut due oscillations in motor torque. This situation causes printing office to lose 2 hours in production and they should be throw away both the printed and raw paper which is inside the machine at the instant that voltage sag/swell occurs.
     The solution for this issue
     Power electronic sytems can solve this problem, since they detect the failure and act in about some tens of microseconds. Some of the systems that can solve this problem is Dynamic voltage restorer (DVR) and dynamic UPS.

Tuesday, April 16, 2013

Quadratic Equation Solver for Android

     Solving quadratic equations is actually very straightforward operation. However, a tool for doing all the operations for solving quadratic equation on behalf of you is very useful. My first android application is a quadratic equation solver and graph drawer called QuadE. QuadE simply asks for the quadratic equation parameters from the user. The parameters as you know are stated as below;
After user enters the parameters the tool calculate the roots. Actually there are two cases for the solution of the quadratic equation, the first is the real roots case the other is imaginary roots case. Consider the real root case, for the roots to be real the delta of the equation should be zero or positive. For this case the roots are real and the curve corresponding to quadratic equation intercepts the x axis. If delta of equation is positive, curve intercepts the x axis at two different points. If delta is zero , the real roots are coincide and there are only one root so that only one interception of x axis. The latter case is as I said imaginary roots case. If delta is negative, the roots are imaginary meaning that the curve corresponding to quadratic equation do not intercept the x axis at any point.Please note that the imaginary roots should be in a form that they should be their complex conjugates.

     The root calculation procedure is reviewed, now we can continue with the key part of the tool, curve drawing. Actually curve drawing is simple, the main idea underlying drawing the equation curve is simply apply all the points in the x axis and find the corresponding y axis coordinates that holds the quadratic equation. However, the challenging part is that what will be the x and y axis scales so that we can see all the critical points on the graph. To achieve this goal, showing all the critical points in the graph, we should determine all of the critical coordinates and determine a scale which is more than all of the critical values. The scale determination algorithm is as follows; 

- find the roots(if any) X1 and X2 
- give 0 to x and calculate f(0) , so that we can find y interception, Y.
- find the maximum or minimum value, take the derivative of the quadratic equation with respect to x and equate it to the zero. (this gives us the point that the slope is 0 which means max or min value) f'(x) = 2ax + b
- solve the 0 = 2ax + b to find Xext, and apply F(Xext) to find Yext.
- Now we have all of the critical values; X1, X2, Y, Xext, Yext.
- The scale should be a larger value than the maximum of critical values. For example scale can be 4 times larger than the maximum critical value, so that the user can see all of the critical points.

After finding the scale value, the other things are very easy, just divide the whole x axis by for example 2000 values and find the corresponding y values for them. After finding all of the coordinates simple connect the neighboor coordinates by a straight line. If we take enough coordinates for the curve, the straight line combinations will be seen as a smoothly changing curve. 

     My application can be freely downloaded from the android market with a name of Quadratic Equation Solve/Graph at an address of . Please rate the labor at android market and do not forget to leave comments for enhancement of further releases.

Download Quadratic Equation Solve/Graph / Android

Recommended to be run on

Thursday, April 4, 2013

POWER SYSTEM HARMONICS IN DETAIL: Subject 2: Effect of FFT Window Size on Harmonic Spectrum

     Power system harmonics are integral parts of Power Quality concerns. Harmonics causes lots of harms on fragile loads in the system and they cause overloading of the power system elements such as transformers or cables. Therefore, they should be eliminated, however, in order to eliminate them totally ,at first we should correctly measure their magnitudes by our control system.
Our aim : Measuring the whole harmonic spectrum of a signal of any Power System variable.
Tools we have: We have measuring probes, interface electronic card and a microcontroller based control system. 

Methodology: At first we should determine frequency resolution for our harmonic spectrum. Generally 10 Hz resolution is enough for ordinary power system load currents and voltages as stated in the IEC 61000-4-7 recommendation for 50 Hz synchronous frequency. For 10 Hz resolution, the window size will be 1/10 = 0.1 sec. After knowing the window size, we can sample all the data included by the window and calculate the FFT(Fast Fourier Transform) for finding the harmonic spectrum.

     Effect of  FFT Window Size on Harmonic Spectrum

     Up to now it is seem to be well defined, however, this is not the actual case. If we have integer number of complete cycles for a harmonic in a measuring window, the result of FFT gives us the correct magnitudes. However, if the frequency of harmonic component is not the integer multiplication of fundemental frequency, then there won't be complete cycles in an FFT window. Therefore, the magnitude of the actual signal is shared by the nearby frequencies and most importantly high frequency components,which does not exist in reality, will appear at the harmonic spectrum. Let me try to explain what is the reason of this situation. FFT is a linear transform that transforms the time domain signals into the frequency domain. Actually for FFT calculations we never use the whole signal (it can not be practical since the signal is from -infinity to +infinity), instead of that we use a part of it and assume that the signal continues periodically as if it continues from the beginning of the window. Figure 1 illustrates what I try to explain.
Figure 1: Case when window size contains complete cycles of periodic signal

     As can be seen in figure 1 when we have complete cycles of periodic signal, the FFT behaves correctly to the signal. and if we have a 250 Hz signal at window size 100 msec, corresponding harmonic spectrum is as in figure 2.
Figure 2: Harmonic Spectrum of 250 Hz signal in 100 msec window(10 Hz resolution)

     As expected, 250 Hz component is appeared at harmonic order of 25. This is because we have 10 Hz resolution. Please draw your attention to that the signal magnitude is calculated correctly as 1 and there will be no high frequency components, their magnitudes are too small and they can be ignored. As a result, our FFT code calculates the magnitude of our signal which is sampled at 25 kHz correctly as 1, since the window contains 25 complete cycles. 
     Let me pass through the most impressive result. What if our frequency is slightly deviates to 255 Hz. Actually please consider that 255 Hz component is not the harmonic component of an ordinary load, this value can be an individual harmonic in addition to the characteristic harmonics. In other words, 255 Hz can not be generally appear as a characteristic 5th harmonic, this can only be happen if the system frequency  deviates to 51 Hz, which is an unlike situation 50 Hz deviates +-0.2Hz at max. We ,for this article, are dealing with the individual load harmonic of 255 Hz. This kind of harmonic components (inter-harmonics) can be encountered mostly in the loads of metal industry, especially for metal melting Induction Furnaces. If you want to reach this kind of load characteristics please contact me. Since we have 255 Hz signal, our FFT window contains 25 complete cycles and 1 half cycle, which means that our control system calculates FFT of a signal of 255 Hz which is distorted at every 100 msec. I try to explain this case in figure 3.
Figure 3: Case when window size does not contain complete cycles of periodic signal

     Figure 3 shows an exaggerated version of the case I try to mention but this is a good illustration. Actually in our case, the distortion happens once for every 25 cycle. Let us see what happens to frequency spectrum for this case.

Figure 4: Harmonic Spectrum of 255 Hz signal in 100 msec window(10 Hz resolution)

     Figure 4 shows the frequency spectrum when we have 255 Hz signal in 100 msec window. I can hear your criticisms like it is normal that the magnitude of the signal is reduced since our resolution is 10 Hz, thus the magnitude is shared by the nearby points. The criticism is totally correct, because in the IEC recommendation the harmonic components are calculated with geometric sum of nearby components for this kind of cases. However, the point I want to draw attention is that there are higher frequency components appearing in the harmonic spectrum which are actually does not exist. When you thoroughly look at the figure 4, you can see that the magnitude of 400 Hz component is about 3% of the individual harmonic, which is an important result. Unlike the harmonic spectrum in figure 2, this case creates the high frequency harmonic components which do not exist in reality. This situation is totally the result of wrong measurement and may cause limit exceeding for higher order harmonics, whose magnitude in reality do not exceed the limits.
     I tried to explain the effect of FFT window size on Harmonic Spectrum of a signal. Actually, the results I show are inevitable for inter-harmonics, since we can not form a window which contains the complete cycles of all harmonic components. However, if we increase our resolution, meaning size of the FFT window, we can significatly reduce the effect of this measurement defects. This time we should consider the storage and execution time concerns. Our control system can not calculate the FFT if our data is huge ,actually we can not even store them, and our process time increases significantly.

Friday, March 29, 2013

Induction Machine Model for Start-Up Simulation

     This article is about the basic modelling of induction machine using the delta equivalent circuit parameters. With this model, we can easily observe how input voltage, stator current, electromechanical torque and shaft speed changes with time during start-up. Basic mathematical model of an induction machine is formed using the mathematical equations of current,torque and mechanical motion equation. The mathematical model is simulated for 1 second to observe the start-up situation. The MATLAB model for this purpose is as stated below;

% Induction Motor Model

t = 0:0.001:1; % 1sec simulation with time step of 0.001 sec
dt = 0.001;

% Motor Parameters
R1 = 0.205; % Ohm
R2 = 1.408; % Referred value, Ohm
X1 = 1.507; % Ohm
X2 = 1.507; % Ohm
Rc = 315.6; % Shunt branch, Ohm
Xm = 42.5; % Shunt branch, Ohm
Vin = 537.4*cos(2*pi*50*t); % Input voltage,50 Hz, Vphase 220 V
I = zeros(1,1001);
s = 1; % slip=1 at the beginning
w = zeros(1,1001); % rotor speed
Pe = 0; % Electromechanical power output
Te = zeros(1,1001); % Electromechanical torque
Jm = 0.1285; % kg/m2 , Inertia of machine

% Load parameters
Tl = 0; % Load Torque
Jl = 0; % Load Inertia

Xeq = X1 + X2;
Leq = Xeq / 100 / pi;

for n=2:1001
   Vth = abs(1i*Xm/(R1 + 1i*(X1 + Xm))*Vin(1,n)); 
   I(1,n) = (Vin(1,n) + I(1,n-1)*Leq/dt) / (R1 + R2/s + Leq/dt); % Motor Current 
   Te(1,n) = 3*Vth^2*R2/((R1 + R2/s)^2 + (X1 + X2)^2)/s/100/pi; % Electromechanical Torque
   % Torque balance equation
   w(1,n) = w(1,n-1) + (Te(1,n) - Tl)/(Jm + Jl)*dt; % new speed value 
   s = (100*pi-w(1,n))/100/pi ; % new slip value

     After we run this code, w, Te and I vectors against time is created at the workspace. We can plot them to see their variation in time during start-up.

     Simulation Results (NO-LOAD Start-Up)

 Simulation Results (LOAD with only inertia no torque Start-Up , inertia Jload = 3xJmotor)

     Note that the in rush current of the motor start-up is easily observed in current graphs. 
     Note that the results are for 2 pole machine
     When a load of only inertia that is 3 times larger than motor inertia, the start-up time is increased.
     Please investigate the torque graphs, the mean of the torque values shows a typical torque-speed curve, which is expected.
     Since there is no load torque and friction&windage torque is neglected, the motor current reduced to zero after rated speed is reached. 

     What if the motor is suddenly loaded with a constant torque of 40 Nm during 1.5 < t < 1.7 sec ?

MATLAB can be get from Amazon at link,

Wednesday, March 27, 2013

POWER SYSTEM HARMONICS IN DETAIL: Subject 1: Effect of Two Closely Located Harmonics

     Harmonics in power system can be basicly introduced as the unintended frequency components, generally higher than system frequency, of current or voltage in the power system. The sources of current harmonics and the harm of them to the power system is stated in an article about Active Power Filters in the blog, thus; I will skip that part. Instead of the drowning in details, I will mention the case of two very closely located harmonics and their effect on harmonic spectrum. Almost everyone who is dealing with power system signal processing can know that the close harmonics tend to increase the magnitude of frequencies between them in FFT spectrum. However, the point that I will draw attention will be a different side of this situation, actually, the behaviors while they are approaching each other to almost 2 Hz. 
     Some loads in Metal Industry behaves very different than other widely known industrial load. For example, arc furnaces, laddle furnaces or induction furnaces for metal melting purposes have very distructive behaviours to the power system. For the introduction of this article, I will briefly mention some behaviours of induction furnaces. For one of the induction furnaces that I take measurements with my collegues in the field, We recognised that the load creates harmonic spectrum other than the characteristics of any other load in industry. The induction furnace creates variety of interharmonics whose frequency value is changing dynamically between 280 Hz and 550 Hz. In other words, there are not fixed frequency harmonics, there can be for example 312 Hz harmonic currents, while the harmonic was in 290 Hz 10 minutes before 312 Hz. The harmonic frequencies are changing during the melting process. I and my collegues are recognised that there can be two harmonics ,which are 2 Hz apart each other, at the same time. Let me know explain what happens at this case.
     As you may know the whole current or voltage signal can be expressed as the sum of fundemental and harmonics frequency sine waves. Therefore, for our example ,for the sake of simplicity, we can consider the sum of 282 Hz and 280 Hz harmonic components whose magnitudes are A and B, respectively. Considering the fundemental Cosine Sum formulation in equation (1), we can apply the rule to our power system signal to get equation (2).

     For the sake of simplicity, we can consider that the phases of our harmonics are equal to zero in order to reach equation (3). If we consider that the magnitudes A and B of the harmonic components are equal to each other as A, we can reach to equation (4).

     When we apply our example to the equation (3) , by putting the frequency values 282 and 280 Hz, we can reach to the result of equation (5). Similarly if we consider that the magnitudes of the harmonics are the same at A, the equation (6) is reached. What is the interpretation of the equation (5) ? Equation (5) means a 282 Hz signal whose amplitude is modulated with a sine wave of 1 Hz. The physical meaning of this situation is that the 282 Hz harmonic component has high magnitude during 0.5 seconds and low magnitude in the following 0.5 seconds. Actually, if you have an active or passive filter for filtering this harmonic, you can hear an audible voice whose intensity is increasing and decreasing at every 0.5 seconds. What if the magnitudes are the same for two harmonics ? This causes the most severe result. The magnitude of the harmonic is increased up to double and decreased down to zero at a frequency of 1 Hz. Similarly, the physical meaning of this situation in active or passive filter case gives that the audible voice is extremely increased and totally ceased with a period of 0.5 seconds.

     Now let me verify this situation using MATLAB.
MATLAB can be get from Amazon at link,

Used MATLAB code for different magnitudes;

t = 0:1.5625e-4:1; % 6400 samples/second sampling frequency
A = 1; % magnitude of 282 Hz component
B = 0.3; % magnitude of 280 Hz component
X = A*cos(2*pi*282*t) + B*cos(2*pi*280*t); % Signal to be analysed
plot(X); % plotting the resultant waveform

Figure 1: Resultant Waveform with A = 1 and B = 0.3

Figure 2: Resultant Waveform(zoomed) with A = 1 and B = 0.3

Used MATLAB code for same magnitudes;

t = 0:1.5625e-4:1; % 6400 samples/second sampling frequency
A = 1; % magnitude of 282 Hz component
B = 1; % magnitude of 280 Hz component
X = A*cos(2*pi*282*t) + B*cos(2*pi*280*t); % Signal to be analysed
plot(X); % plotting the resultant waveform

Figure 3: Resultant Waveform with A = 1 and B = 1

Figure 4: Resultant Waveform with(zoomed) A = 1 and B = 1

Monday, March 25, 2013

TCP/IP Ethernet Communication Using Stellaris ARM Cortex M3

     Stellaris ARM Cortex M3 is a product  of Texas Instruments (TI). Unlike powerful DSP’s or floating point microcontrollers, this microcontroller is not suitable for Power Electronics applications control system. However, due to its communication features it can be a very good monitoring processor. The microcontroller has an Ethernet module and its evaluation kit has already mounted Ethernet connector. I am using Stellaris ARM Cortex M3 for monitoring purposes in one of my Active Power Filter project. The microcontroller has the analog inputs for necessary channels like active filter current, line voltage, dc link voltage and heatsink temperatures. These analog information is converted to digital and sent to the Human Machine Interface (HMI) of automation system via Ethernet communication. This is the duty to be conducted by this microcontroller. In this article, I will try to explain the methods to conduct this applications with basic TCP/IP protocol and explain ,in detail, my solution.
     TI provides lots of sample codes and manuals for different applications. One of these sample codes and manuals is about TCP/IP protocol. There are two modules served for this purpose which are generated by Adam Dunkels namely uIP (micro IP) and lwIP (lightweight IP). One can use these methods to communicate to any device using Ethernet communication.
     uIP is smaller in size than lwIP. It contains basic functions to establish or finish the connection and sending or receiving data. uIP is not a complex structure thus; it is better for simple applications. lwIP , on the other hand, has more complex structure than uIP but its features are a bit more developed. Actually, for basic communication purposes, one can use uIP easily for Ethernet communications.
     My solution ,on the other hand, uses the open-sourced uIP stack ,however; I add my functions for establishing, finishing connections and receiving or sending data routins. By this way, I form a code that listens any of the device that requires connection establishment and sends the data immediately after receiving data from the host. 
     The physical connection is started when the host sends a broadcast in ARP (Adress Resolution Protocol), stating its own MAC adress, IP and the destination IP adress. If our microcontroller has the same IP adress of host requires, our system sends an answer stating its own MAC address and IP in ARP. After this process, now the host knows our IP address. To establish the connection the host sends a SYN flaged packet in order to initialize the sequence number and the rules of connection (like window size, protocol number IPv4, TCP protocol and its listening port). Our system turns an answer of SYN/ACK packet to understand the rules and port numberof the host. Finally, the host send and ACK packet to show that it succesfully establish the connection and ready to transfer data with the stated rules. After the synchronisation is handled, the host sends a data whenever it wants using the PSH,ACK flaged packet. This packet contains the data to be transfered and requires an acknowledge that the data is reached correctly. Once, our system get the PSH,ACK flaged packet, we immediately send an ACK packet to say that we succesfully get the data. After we successfully receive the data we send our information to the host using PSH,ACK flaged packet. Similarly, it is expected that the host sends ACK packet when it reads our information. The data sending cycle continues until the host finishes or reset the connection. To finish the connection, host sends FIN,ACK packet for healty ending of connection or RST,ACK packet if it needs to force the connection to end.
      My code for handling all these TCP/IP communication procedure is as stated below.

EthernetPacketGetDMA(unsigned long ulBase, unsigned char *pucBuf, long lBufLen)
    int k,freq_index;
                long len;
                int Data_len = 0;
    // Check the arguments.
    ASSERT(ulBase == ETH_BASE);
    ASSERT(pucBuf != 0);
    ASSERT(lBufLen > 0);
        len=ROM_EthernetPacketGetNonBlocking(ulBase, pucBuf, lBufLen); // get the received packet on pointer pucBuf
                // ARP packets handled here
                                if(*(pucBuf+12)==0x08 && *(pucBuf+13)==0x06 && *(pucBuf+41)==DEFAULT_IPADDR3)
                                               {ARP_SEND[k] = *(pucBuf+k+6);  // Dest MAC
                                               ARP_SEND[k+32] = *(pucBuf+k+6);   // target mac }
                                               {ARP_SEND[k+38]=*(pucBuf+k+28); }

                    // IP packets handled here
                                if(*(pucBuf+12)==0x08 && *(pucBuf+13)==0x00) // IP packets here
                                for(k=0;k<6;k++)                // destination MAC
                                 if(TCP_SEND[19]==0xFF)   // identification increments every send procedure
                                               TCP_SEND[k+30]=*(pucBuf+k+26);     // Destination IP
                                               TCP_SEND[36]=*(pucBuf+34);     // Destination Port
                                               TCP_SEND[46]=0x50; // header length
                                 ///****** SYN packets here
                                if(*(pucBuf+47)==0x02)  //SYN packets
                                {    for(k=0;k<4;k++)
                                 {TCP_SEND[k+42]=*(pucBuf+38+k);  }
                                 TCP_SEND[45]++; // Ack num + 1
                                 TCP_SEND[47]=0x12; // SYN,ACK
                                 TCP_SEND[48]=*(pucBuf+48);  // window size
                               TCP_SEND[46]=*(pucBuf+46);  // header length
                               for(k=54;k<len;k++)      // options
                                }// end SYN
                                ////////*** ACK packets here
                                else if (*(pucBuf+47)==0x10)
                                {  // data transfer cycle is ended. Nothing is necessary to do                 
                                }// end ACK
                                ////////*** PSH,ACK packets here
                                else if (*(pucBuf+47)==0x18) 
                           {Data_len = *(pucBuf+17)-0x28; // how many bytes of data are received?
                                 {TCP_SEND[k+38] = *(pucBuf+k+42);
                                 TCP_SEND[k+42] = *(pucBuf+38+k); }
                                TCP_SEND[45] += Data_len;
                                 TCP_SEND[46] = 0x50;
                                 TCP_SEND[47] = 0x10; // ACK
                                 TCP_SEND[48]=*(pucBuf+48);  // window size
                                if(*(pucBuf+55) == 0xCC)
                                if(*(pucBuf+55)==0xAA && Data_len == 22)
                                                               receiveArray[k] = *(pucBuf+54+k); }
                                sendArray[0] = 0x02; // ID2
                                sendArray[1] = 0xBB; // ack
                                               sendArray[k] = receiveArray[k];
                                sendArray[22] = (mALARM >> 8) & 0x00FF;            // alarm high byte
                                sendArray[23] = mALARM& 0x00FF;                         //alarm low byte
                                sendArray[24] = (_IQ7int(Vdc_mean) >> 8) & 0x00FF;   //dc link voltage
                                sendArray[25] = _IQ7int(Vdc_mean) & 0x00FF;
                                GP_CURRENT = _IQ7int(Iha_mean);
                                GP_CURRENT = isqrt(GP_CURRENT);
                                sendArray[26] = (GP_CURRENT >> 8) & 0x00FF;  // active filter current
                                sendArray[27] = GP_CURRENT& 0x00FF;
                                freq_index = 0;
                                for(k=28;k<108;k=k+4)  // send frequency values
                                                               sendArray[k] = (freq[freq_index][0]>>8) & 0x00FF;
                                                               sendArray[k+1] = freq[freq_index][0] & 0x00FF;
                                                               sendArray[k+2] = (freq[freq_index][1]>>8) & 0x00FF;
                                                               sendArray[k+3] = freq[freq_index][1] & 0x00FF;
                                sendArray[108] = T1_int;   // send temperatures
                                sendArray[109] = T2_int;
                                sendArray[110] = T3_int;
                               }// end PSH,ACK
                    ////********** FIN,ACK packets here
                   else if(*(pucBuf+47)==0x11)  
                                 {TCP_SEND[k+38] = *(pucBuf+k+42);
                                 TCP_SEND[k+42] = *(pucBuf+38+k); }
                               TCP_SEND[45] += 1;
                                 TCP_SEND[42]++; }
                                 TCP_SEND[46] = 0x50;
                                 TCP_SEND[47] = 0x10; // ACK
                                 TCP_SEND[48]=*(pucBuf+48);  // window size
                                TCP_SEND[47] = 0x11; // FIN,ACK
                               }// end FIN,ACK
 } // end else if
            // Clear the RX Packet event and re-enable RX Packet interrupts.
            if(HWREGBITW(&g_ulFlags, FLAG_RXPKT) == 1)
                HWREGBITW(&g_ulFlags, FLAG_RXPKT) = 0;
                ROM_EthernetIntEnable(ETH_BASE, ETH_INT_RX);
  return len; 
}// end function 

For the whole source code and detailed information please contact me.