Chapter Three Drave
Chapter Three Drave
1
acquiring of the sampling is set by the phase locked oscillator. The phasor processor
calculates the phasor, frequency and ROCOF. These measurements are time-tagged with
GPS- time, which makes it possible to compare measurements from two geographically
separated PMUs, because all samples that are compared are captured at the same GPS-
time. In the communications stage, the PMU measurement is streamed to the internet,
usually to phasor data concentrators (PDC) for analysis .
Digital filters are divided into two different categories, FIR and IIR filters .
FIR (Finite Impulse Response) filters are characterized by its finite-length impulse response. An
N :th order filter’s impulse response settles to zero in N + 1 samples. They are generally used in
applications where linear phase response is sought after, and there is enough computational
power and memory. Additionally, they are generally also numerically stable since all poles in the
transfer function are located within the unit circle. The increased demand on computational power
means that they will include a larger time delay, however the linear phase response leads to a
constant group delay. Therefore always maintaining the original shape of the signal.
IIR (Infinite Impulse Response) filters are characterized by its infinite-length impulse response.
They are widely used in applications that require very low latency. They will require lower order
for the same magnitude response as an FIR filter. However, as the phase response is generally
non-linear, an IIR filter introduces a non constant group delay which may require more
compensation in some cases. They are also less numerically stable compared to FIR filters.
3
measurements. A measured quantity of an AC signal is referred to as a phasor, which
corresponds to the DC equivalent of an AC signal, commonly called the RMS value and its
angle relative to a reference AC signal. Therefore a synchronized measured AC signal is called
a synchrophasor.
where Xm is the signal’s peak value and ω = 2πf is the angular frequency and ϕ is the
initial phase-angle.
Xm iϕ
Xm
X = √ e = √ (cos(ϕ) + isin(ϕ)) = Xr + iXi 2
2
2
√
where Xm/ 2 is the RMS value, Xr is the real part and Xi is the imaginary
part of the signal . A visual representation of equation 2 is shown in figure 3.
4
Figure 3.2 Synchrophasor representation
When the signal is in this form the amplitude and phase can be calculate by using
the following equations [14]: √ q
Xamp = (|Xrms| cos(ϕ))2 + (|Xrms| isin(ϕ))2 = X2 + iX2
r i
sin(ϕ) X
θ(t) = tan−1 = tan−1 i
4
cos(ϕ) Xr
5
Each phasor value is then time-stamped aided by a local clock in the PMU. The local clock is
synchronized with a pulse per second (PPS), creating a phase locked oscillator [11]. The PPS is
generated from a syn- chronization source, and indicates the start of a UTC (Universal Time
Coordinated) second. The local clock is responsible for the timing of the data acquisition and
thus, by synchronizing the local clock and PPS, all samples can be related to a known UTC time .
The synchronization process is visualized in figure 3.4.
Figure 3.4 Synchronization of phasor value with local clock using PPS
Hilbert Transform
The Hilbert transform is used with the objective of creating a unique complex-valued analytical
signal, which is a representation of the original real signal extended into the complex plane. It can be
used with the condition that the original signal has narrow-banded frequency and is real. This
transformation allows for the determination of instantaneous properties of the signal, by calculations
on this analytical signal. The Hilbert transform is defined by [15]:
∫
1 ∞ x (τ )
x˜(t) = H[x(t)] = dt 5
π −∞ t − τ
This is only used for a continuous signal x(τ ). For digital signal-processing the Hilbert transform
is based on the discrete Fourier transform .
In order to understand the Hilbert transform, a basic understanding of negative frequencies in the
Fourier transform is needed. The frequency of a real-valued signal in the time domain is often
6
represented in a one sided spectrum in the frequency domain, disregarding the negative
frequencies. They do not contain any information not found on the positive side of the spectrum .
However, for the inverse Fourier transform it is important that the negative side is a mirror of the
positive side in order to cancel out the imaginary parts when using the inverse Fourier transform
and thereby providing a real signal. The negative frequencies serve this purpose of canceling out
the imaginary part .Since the Fourier transform is complete (no information is lost), the Fourier
transform data contains the same information as the real-valued data. The Hilbert transform
preserves the complex nature when trans- forming back into time domain, which as earlier
discussed was removed by the negative frequencies. And as previously discussed the negative
frequencies for real signals contain redundant information [15]. The Hilbert transform process can
be explained in these steps:
4. Perform the inverse Fourier transform to obtain the complex-valued analytical signal.
This complex-valued analytical signal is used to find the envelope and phase of the original real-valued signal
using equation 3 and 4. The amplitude refers to the envelope and the phase is the angle of the complex signal at
each instantaneous time [15]. The derivative of the phase estimated by the Hilbert transform represents the
frequency and the second derivative of the phase simply represents the ROCOF:
7
Department of Electrical Engineering, Uppsala 8
University
1 dθ
f (t) = f0 + 6
2π dt
df 1 d2θ
ROCOF = = 7
dt 2π dt2
where f0 is the nominal frequency, in this case 50Hz similar to the Swedish power grid.
Accuracy
The IEEE C37.118.1 standard defines the Total Vector Error (TVE) which is the relative
difference between the calculated phasor values and the actual phasor values of a theoretical
synchrophasor and is written as:
TV E = 8
r i
s
(X¯ r − Xr)2 + (X¯ i − Xi)2
2
X +
X2
where X¯ r and X¯ i are the estimated phasor values and Xr and Xi are the theoretical
components [11, p. 18]. It defines the error in percentages and the IEEE C37.118.1 standard
tolerates a maximum steady-state error of 0.01 radians (0.57 degrees) which corresponds to 1%
TVE and a time error of ±31µs for a 50Hz system [9, p. 6].
The errors of the frequency and ROCOF calculations are evaluated by using the following equations [11,
p. 19]:
∆
FE = absolutefrequencyerror = f˜− f = ∆f 9
∆
RFE = absoluteROCOFerror = RO˜COF − ROCOF = ∆ROCOF
10
Communication
TCP/IP - UDP
The PMU data can be sent over the network using either TCP/IP (Transmission Control
Protocol/Internet Protocol) or UDP (User Datagram Protocol). These are transport layer protocols,
which have direct impact on the user experience whereas other layers do not. Due to their inherent
properties, the suitability to complete a task is unambiguously decided by the task itself. TCP/IP
establishes a connection with a client before transmitting any data. The client has to confirm the
connection and the procedure is called a handshake. This allows for confirmation of data delivery
and allows the sender to become aware of errors so that the host can retransmit the lost data packages
[20]. In contrast, UDP does not perform this handshake, and simply sends data over the internet, and
the data can be accessed by any listening device. There is neither confirmation of data delivery nor
retransmission of lost data packages . DP transmits data as fast as possible, also disregarding the
bandwidth of the internet, which TCP/IP can adjust to so that no data goes missing .
8
Due to the handshake, confirmation of delivery and retransmission of lost data packages, TCP
connec- tion is slower at sending data over the network compared to UDP . However, UDP is less
reliable, since data delivery cannot be guaranteed [20]. The difference in data transmission speed
makes UDP suitable for real-time applications .
Frames
There are four frames defined in the C.37.118.2 standard; data, configuration, header and command
[10]. The general communication procedure can be visualized in figure 5.
The client (the PDC) initiates contact by sending a command frame to the PMU and requesting a
configu- ration frame. The PDC then requests a header frame, which is sent in a command frame.
After the PMU has sent the header frame, the PDC sends a command frame to the PMU to start
transmission of data. The PDC can stop the PMU’s transmission of data by sending another
command frame.
The number of bytes of each part of the message is indicated below the corresponding part. The
SYNC part provides synchronization and frame identification. Framesize gives information about
the total number of bytes in the frame. The IDCODE is used for identifying the source of a
frame, or destination for a command frame. SOC is an abbreviation for second of century, which
is a time-stamp of seconds passed since 1st of January 1970 at midnight (00:00:00). FRACSEC
is related to time and the quality of the reported time. Lastly, every message is concluded with a
CHK. For further details of general messages, please refer to the standard.
The different frames have strict guidance on their formatting, details of which are not included in
this paper. For further details, please refer to the standard. However, all messages are written in
hexadecimal numbers. So if 1 million seconds have passed since 1st of January 1970 at midnight,
the message would contain 0xF 4240, since this is 1 million in hexadecimal numbers. As an
example, the standard regarding the data frame is presented in appendix A.
Matlab Communication
In Matlab, the function udpport() can be used for UDP communication by using a UDP socket on
the local host. This requires both host and client to be connected to the same WiFi, alternatively,
an Ethernet con- nection can be established.
A UDP-object can be created on the host and data can be written to the socket by using the
function write(). The function has to contain the UDP-object, data to be transferred, data-type,
name of client and port number used on the client. On the client side a separate UDP-object has
to be created. Specifically, the port used on the client and the name of the client has to be
specified. In order to read the data from the socket, the function read() can be used. The client
side UDP-object, bytes to read and data-type has to be specified in the read()-function. A
complete example using udpport() is shown in appendix B.
1
0
Implementation
Overview
The initial concept for the project involved creating a basic model in Simulink, utilizing the built-in blocks and
later writing a more complex implementation in Matlab code. However the project quickly shifted from this
approach, and instead the Simulink model was built exclusively with elements that could be directly applied in
the code implementation. Instead, the Simulink model was used as a tool for testing new methods and
troubleshooting since it was easier to analyze the data in Simulink. The only piece not implemented in
Simulink was the communications part. View the code and the model as separate programs aimed at achieving
the same calculations. The implementation in Matlab code can be observed in appendix C.
1.1 Simulink
The final Simulink model can be seen in figure 7
Input signal generation was performed in the first Matlab function block, taking input parameters
to simulate different scenarios. This signal was sent into the filter designer, where it was filtered to
remove noise from the signal generation. The filtered signal was thereafter sent to the "PMUcalc"
block, where all variables were calculated for transmission (only included in Matlab code). The
remainder of the model focused on error estimation, including the theoretical phase block at the
top. Finally, the TVE calculation was performed (equation 8).
Matlab
11
The generated input signal was assumed to already have been sampled at 2500Hz and passed
through an anti-aliasing filter. Thus the input signal was generated as a digital signal. The code
was designed to allow the signal’s amplitude, fundamental frequency, harmonics and amplitude
of these harmonics to be specified by the user in order to simulate different conditions.
In order to calculate the phase-shift, the input signal had to be compared with a reference signal.
This was generated as a simple digital sine wave with the same sample time as the input wave, its
frequency was set at 50Hz with an amplitude of 100V .
In order to simulate real-time data, the signal generated was sent as one instantaneous value for each
time- step. All blocks have built-in data buffers; the calculation blocks save 500 samples and the
filter saves 1000 samples. In order to calculate on these values the buffers consists of arrays that are
shifted circularly, chang- ing the last element at each time step. Therefore the calculations are
incorrect for the first 1000 iterations of running the code since the buffer has to fill up. However, this
was handled in Matlab by not sending any data when the data buffers are filling up.
Filter design
After generating the signal, the input signal was filtered using a FIR bandpass filter (see 2.4.1) in order to
remove unwanted disturbances. It was designed and implemented using the “Digital filter design”-block from the
DSP toolbox in Simulink, and later exported into Matlab code. The block was used for its minimum-order-
function which automatically determines the necessary order of the filter to satisfy the given specifications,
which can be specified as seen in figure 9. The filter was designed to significantly attenuate frequencies outside
the 30 – 70 Hz range, in order to eliminate any disturbances consisting of harmonics. The filter implemented
was of order 558 and its magnitude and angle response can be seen in the figure 3. 8, as well as the input
parameters (figure 3.9).
12
Figure 3.8 Magnitude and phase response of the implemented FIR filter.
Calculations
On the filtered signal, the amplitude, phase, phase-shift, frequency and ROCOF were calculated
using equa- tions 3, 4, 6, 7. Calculations were made purely in Matlab code blocks and used a
sliding window including 500 samples, this means that for each time stamp a new calculation was
made and each data point was used 500 times. Utilizing the Hilbert transform introduced edge
effects on the calculated data, causing large errors close to the beginning and end of the window.
Therefore measurements were taken at the most accurate values in the middle of the array and
13
this naturally introduced a delay. This delay was compensated for when time-stamping,
calculating at the middle of the window resulted in a delay equivalent to 250 samples or 0.1s,
since the sample time was 0.0004s (sample frequency of 2500Hz)
Phase
To calculate the instantaneous phase from the data buffer of values the Hilbert transform was
used (see 2.4.3). The built in hilbert()-function in Matlab gives the analytical signal with
complex values. On this analytical signal the function angle() 4 was used which calculated the
phase according to equation 4 and wraps it to [−π, π]. Wrapping means keeping the value
between the boundary, so the number of full rotations is discarded. An example of to visualize
instantaneous phase of a cosine wave can be seen in figure 10:
Amplitude
Amplitude was also calculated by using the Hilbert transform. The analytical signals envelope was
obtained by taking the absolute value of the signal at each instantaneous time, directly giving the
estimated amplitude.
Phase-shift
Phase-shift was calculated using the reference wave of 50Hz previously mentioned. Instantaneous phase of the
reference was calculated using the same calculation as for the input signal. The phase-shift was then defined
using the mod() function on the reference phase minus the input phase. Wrapping it between 0 and 2π.
The ROCOF was calculated using the definition of the derivative (equation 7). It uses a separate
data buffer of length two saving the latest frequency calculation.
15
16
Synchronization
Time-stamping was performed by using the Windows-clock for the first stamp. This was to establish
the starting time for when the code started executing. Then 0.0004s was added to the previously sent
time- stamp, in order to avoid drift induced by calculation speed of the code. Since the simulation
time did not follow real time, meaning x seconds of simulation time took more than x seconds in real
time to complete, this method had to be used.
3.2 Communication Interface
In order to transmit and receive the PMU data, a WiFi connection was established between a
sender computer and a receiver computer. Both computers were running Matlab and running their
respective program files (appendix C) during the transmission of data. The connection was
established according to 2.5.3. Since the PMU is a device which sends data in real-time, UDP
was used for the communication interface to simulate the real PMU accurately. This is because
the UDP interface is faster than TCP/IP, as explained in 2.5.1. Moreover the project was not
concerned with the reliability of the data transmission.
After the PMU data was calculated, each of the quantities were formatted using sprintf() in order
to control the byte length of each variable. For example sprintf(’%08.4f ’, amp) means the
amplitude quantity is rep- resented with 8 bytes and 4 decimal precision. These were then
packaged into a “sender message” with the quantities being separated by a backslash in order for
the receiver code to split the message into the separate quantities, using the function split().
Furthermore, the total byte-size of the message had to be specified in the receiving code, and this
was calculated by simply adding the number of bytes in sprintf(), and adding a byte for each
backslash used. The message byte-length was also confirmed using the function strlength(). The
code implementation is presented in appendix C, listing 7.
Upon unpackaging the data in the receiver code with the function read(), the data was plotted in a
graph (figure 12) with a moving window to simulate real-time communication.
16
17
Figure 12: Plotted results in Matlab for a 100V and 50.1Hz signal.
The model correctly calculates amplitude and frequency, as seen in the first and third
subplot of the figure. In the second subplot, the phase-shift is reminiscent of a reverse
sawtooth wave. This is because the reference signal has a frequency of 50Hz, and the test-
signal 50.1Hz. And since the frequency is constant at 50.1Hz, the ROCOF in the fourth subplot
is near 0, which is expected.
17
18
To evaluate the frequency calculation, a signal with an incrementally rising frequency from
49.5Hz to 50.5Hz was used, allowing the system to reach steady state between each change.
Waiting for steady state was important since changing the frequency with an increment of
the input signal results in sharp edges in the
18
19
wave at the point of shifting frequency. This occurs because the Hilbert transform derives
the phase to calculate the frequency as described in 2.4.3. So when the frequency changes
with an increment, the phase "jumps" and the derivative of the phase, the frequency, shows
large spikes. This can be seen below in figure
13. The frequency was delayed to line up with the calculated frequency, this is done in the
time stamping in practice.
The error increases as the fundamental frequency is further from 50Hz and is symmetrical
around 0 error, this error changes with different lengths on the input array. However, the
model’s accuracy must be highest around 50 Hz, as this is the fundamental frequency
around which the power grid operates. Comparing this error to the maximum allowed
according to the standard of 0.005Hz in steady state it can be observed that this calculation
stays within this error for fundamental frequencies between 49.9Hz and 50.1Hz.
19
For the ROCOF calculation it was evaluated during a steady state test, meaning no change
in input param- eters. The result can be seen in figure 14.
The maximum error is around 0.27mHz/s and this is within the allowed ROCOF error of a
PMU of ±10 mHz/s during steady state testing.
These results were tested using a step input as defined in the standard. Starting out at 100V ,
increasing to
110V allowing the system to reach steady state and then back to 100V .
4.2.2.1 Amplitude
Figure 15: Comparing amplitude and TVE results during step test.
According to the standard the allowed over- and undershoot are 5% of step amplitude which
the results are clearly under.
20
The delay time is defined as the time required for the calculated amplitude to reach half of
the step amplitude, so in this case 105V . In the standard the allowed delay time is the
sampling time divided by 4 so 0.0001s. This was achieved in the second step down to 100V , for
the first step the delay time was measured to one time step.
The response time, defined as the duration for the TVE to drop below 1% following a step
[9], was measured as 0.019s. However this measurement incorporates the compensation
accounted for in the time-stamp, which is 0.2116s. Without considering this compensation,
the response time would fall short of meeting the stan- dard, set at below 0.182s for a 30Hz
sending frequency.
The TVE in the steady state sections between stepping is allowed to reach 1% according to
the standard but recommended to be far below this threshold, the model fulfills this
requirement.
The phase error is calculated into the TVE and therefore the results remain the same as
previously discussed in 4.1.2.1. Observe that this is the phase defined for a cosine wave,
and not the phase difference between the reference and the measured wave. The simulation
also calculates a phase difference to a reference sine wave of 50Hz, this measurement was
not compensated for group delay of the filter which is not by itself an issue as long as the
measurements being compared are taken under the same simulation conditions.
21
the 3 biggest factors and discussion on how to reduce them.
The FIR filter as previously mentioned has a constant group delay, introducing a delay of
279 samples. This could be reduced by either lowering the constraints on filtering and
therefore reducing the order, or changing method to an IIR filter and compensating for the
group delay in other ways.
The computation stage introduced a time delay of 250 samples in order to calculate in the
middle of the data buffer to minimize error. This was done to avoid the associated edge
effects, however the corresponding time
22
delay could be reduced. The current array of 500 samples includes 10 periods of the
fundamental frequency, reducing this number would decrease the delay. However this
could require more pre-proccesing of the data to reduce the increasing error.
The Matlab functions used for sending and receiving were too slow to comply with the
standard, this was investigated by Mathworks and it was deemed to be related with
performance issues in Matlab. This could be resolved by sending the data with another
program or by sending it internally from Matlab not using the UDP functions.
This clearly shows the large delay from the FIR filter of 0.1116s between the fundamental
and the output. As previously mentioned an IIR filter could be implemented with a much
lower order and have the same effect on the magnitude, the FIR needs order 558 while
the IIR only needs order 16 to fulfill the criteria. The reason for using a FIR filter instead
of IIR is its linear phase response, which results in a constant group delay for all input
frequencies. Adjusting for this constant group delay of 279 samples is done when
transmitting data and is simpler compared to IIR’s non-constant group delay, which requires
compensation using an all-pass filter with the inverse phase response of the IIR or a similar
solution. In this project ensuring correct measurements was deemed more important than
calculation speed, therefore the FIR was used.
As shown in figure 1, the PMU consists of an anti-aliasing filter in the measurement stage.
However, the anti-aliasing filter was excluded in the model, partially explained in 3.3.1. In
reality, a PMU receives an analog signal from the grid, which is put through an anti-aliasing
filter to prevent aliasing in the ADC. In order to generate a "continuous" signal the model
23
would have to work on two different sample times, one much smaller than the other.
Furthermore the filter would be analog and its phase delay therefore generally
24
nonlinear. This would as previously mentioned in 2.4.1 require more complex
compensation, increasing demand on computational power. This would slow down the code
execution, defeating the purpose of real- time simulation. In order to circumvent this issue,
a sine wave could possibly be generated with a waveform generator and then filtered
against aliasing using common electrical components such as resistors, capacitors and
inductors. For this particular instance, where the fundamental frequency was 50Hz and the
sampling frequency was 2500Hz, the components should be dimensioned to create
2πR
a cutoff
frequency at around 1250Hz or less as described in 2.3.1. Using the formula for aC RC lowpass
filter’s cutoff frequency, fc = 1 , a resistor of 10Ω and a capacitor of 13µF should suffice.
Then the filtered signal would be sampled in Matlab and the implementation described in
the paper could be applied.
4.5 Communication
The IEEE C.37.118.2 standard has a rigid framework for how a real PMU should transmit
the data. This includes not only the described general framework, but also specific guide as
to how the different frames should be composed, presented in appendix A. As these
frameworks and guides were explored at the begin- ning of the project, it was quickly
realized that adhering to the standard was not feasible within the given time-frame of the
project. Therefore, the first and third objectives described in 1.3 were reduced to simply
specify any data communication that the students could choose. Some of the alternatives to
following the standard were to read the data in Wireshark or in Matlab. This also meant
that PMU connection tester could not be used to read the data frames, since the software
only reads messages written according to the standard. Thus, similar communication to to
figure 5 could not be replicated.
Wireshark is a tool for analysing internet traffic, where technical information about IP-
addresses and ports can be seen. Furthermore, a user can see the data content of any non-
encrypted message. The idea was to transmit non-encrypted messages, as data security was
not a priority in the project. However, Wireshark does not provide any convenient way of
processing and visualizing the received data. Therefore, simply sending the phasor value
measurement from one Matlab session and receiving the data in another Matlab session was
the preferred option.
The implementation described in 3.4, was approved after consultation with the supervisor.
The imple- mentation yielded the results presented in figure 12. However, there was
significant delay in receiving the data. The PMU computation stage of the code simulated
30 seconds worth of data, which took 43 seconds to run in real-time. When the code had
finished, only 2 seconds worth of simulation data had appeared in the results graph.
Identical results were obtained from connecting the two computers via WiFi and Ethernet,
dismissing a limited WiFi bandwidth as the cause of slow sending/receiving rate, since a
connection over Ethernet has more bandwidth than WiFi. Since there were no other
immediate cause of the significant delay between sending and receiving Matlab support
was asked to look at the problem. They confirmed that there were inherent performance
issues with the udpport()-function. Due to the time constraint of the project, any further
25
investigations into other solutions were abandoned.
26
5 Conclusion
Throughout the project, some modifications were made to the original project objectives in
order for the project to be realistic given the resources and time-frame. The modifications
included only using the stan- dard as a guide as to how the PMU should be designed and
how it should perform, instead of strictly adhering to it. The major deviations from the
standard were the time-delay, caused by the FIR filter, Hilbert transform and udpport, and
the composition of standard compliant frames.
Using an FIR filter was preferred because of the linear phase response. In order to lessen
the delay from the FIR filter, an IIR filter could be implemented. The IIR filter is much
faster but does not have a linear phase response, which means the filter delay is variable for
different frequency components, which could be difficult to uniformly compensate for.
Furthermore, the use of data buffers for the Hilbert transform also added delays.
Calculating in the middle of the buffer in order to avoid edge effects introduced 250
samples worth of delay, around 0.1s. However, the most significant delay occurred in the
transmission of data between the sending code and the receiving code. It was later
confirmed by the Matlab support that there were known performance issues associated
with the udpport -function, used in the project. Therefore, the current recommendation is to
use another program for the implementation altogether.
Since the students were unable to write standard compliant messages in Matlab, the
specified software in the objective, PMU connection tester, could not be used to test the
receiving frames. This is a fundamental part of the standard and thus any future extension
of the project may include correct message formatting.
The project did not include the measurement stage and the anti-aliasing filter, and the GPS
time syn- chronization. As discussed, the anti-aliasing filter would have served no purpose
since the test-signal was digital. In a future project, the anti-aliasing filter may be included.
Also, the synchronization was made with the Windows-clock, according to the objectives,
but not GPS-time. The GPS-time synchronization is a core function the PMU, since the PMU
technology relies on comparing simultaneously measured quantities. This requires high
accuracy which the GPS-time can deliver. The GPS-time may be implemented in any future
work or extensions of this project.
The Hilbert transform was the main tool used by the project in the calculations. It was
deemed to work well enough on this theoretical data, however it is yet to be tested on real
data from the grid. The main problems with the transform were edge effects as previously
shown in figure 11, and the large errors when shifting frequency in figure 13. It was
discussed if the edge effects could be lessened by applying a window function to the data
before the transform, this might both lessen the delay and the error from the calculations
and should be tested in future work. For the shifting frequency error it was unclear if the
error stemmed from the Hilbert transform or from the fact that shifting the frequency
27
created sharp edges in the phase, this should be tested on real data to see if the error
persists. There are many other transforms which might be tested for calculating
instantaneous values, such as the HHT (Hilbert-Huang transform) or the Wavelet transform.
These different methods could provide better results in the model and compared in future
work.
28
To conclude, the model successfully implemented a PMU in Matlab and Simulink. A test-
signal with several harmonics was generated and the model filtered the signal and correctly
calculated amplitude, phase-shift, frequency and ROCOF within the requirements of the
standard for the applied test. Time-stamping was also performed and the data was sent
over the internet via UDP to another Matlab session. Where data was plotted with a moving
window to simulate real-time monitoring. The model provided a solid groundwork for its
intended use. The implementation, although incomplete, mimics the behavior of a PMU. Any
future work may include the complete workings of the PMU, along with optimisation of the
code for faster execution and reduction of errors.
29
30
6 Appendix
A. IEEE C37.118.2 standard regarding data frames are shown in tables 1 and 2.
31
Table 2: Word definitions unique to data frames
32
B. Establish connection between two computers in Matlab using the following code.
3
while true
4
data_to_send = data ;
write ( u_send , data_to_send , datatype ," name_of_receiving_computer ",
5
port_of_receiving_computer );
end
6
2
while true
3
data = read ( u_receive , bytes_to_read , datatype );
4
end
5
1 clear Signal_Filtering ;
clear PMUcalc ;
2
clear;
3
4
% ---------------- - UDP --------------- -
5
10 % Parameters
11 T = 5; % Simulation end time
time = 0 :0 .0004 : T; % Sampling freq of 2500 Hz
12
fund_amplitude = 100;
13
fund_freq = 50;
14 k = 0.1; % Amplitude of harmonics realtive to
15 fundamental harmonics = [3 , 5 , 7]; % Harmonics to
include
16
17
% Start iteration and
18 time currenttime = 0;
19
20
33
21 i = 0;
22 counter = -500; % Counter for setting sending frequency ( 30 Hz )
23
24 timestamp = datestr( now , ’ HH: MM: SS. FFF ’); % Checking current time
25
32 i = i + 1;
33 counter = counter + 1;
34
46 % Timestamping
47 % Converting back to string to be able to send with UDP
48 current_timestamp = datestr( timestamp_datetime , ’ HH: MM: SS. FFF ’);
49
34
64 write (u, datatosend , " string " ," hostname_receiver " ,8080)
counter = 0;
65
end
66
end
67
2
% ------------ - Data buffers --------------------- -
3
persistent measvalues
4 persistent
5 referencevalues
persistent flst
6
persistent tlst
7
8
% Global variable
9 arrays if isempty (
10 measvalues )
11 measvalues = zeros (500 ,1);
12 referencevalues = zeros (500 ,1);
13 tlst = zeros (500 ,1);
14 flst = zeros (2 ,1);
15 end
16
% Saving last 500 values (10 ish periods , 0.2
17
secs ) measvalues = circshift( measvalues , - 1);
18 referencevalues = circshift( referencevalues , - 1);
19 tlst = circshift( tlst ,- 1);
flst = circshift( flst ,- 1);
20
referencevalues ( end ) = reference ;
21 measvalues ( end ) = currentvalue ;
22 tlst( end ) = t;
23 % -------------------------------------------- -
24
28
% Phase calculation
29
phase = angle ( analytic_signal (250));
30
31
32 % Frequency calculation
33 phaseh = unwrap ( angle ( analytic_signal));
34 freq = diff( phaseh (225 :275 )) / (0 .0004 * 2 * pi);
35
frequency = mean ( freq );
flst (1) = frequency ;
36
37
38
39
35
40
45
46 % Caluclating envelope
47 envelope H = abs ( analytic_signal (250));
48
49 % Calculating ROCOF
50
flst (1) = frequency ;
rocof = ( flst (2)- flst (1))/( t- tlst (2));
51
52
% ------------------------------------------- -
53
54
5 persistent signallst
6 persistent tlist
7
10 if isempty ( signallst)
11 signallst = zeros (N, 1);
12 tlist = zeros (N, 1);
13 end
14
20
23 % Defining fundamental
24 % Uses A ( Amplitude ) and f ( frequency ) from input
25
36
29 % Adding harmonics
30 harmonics_amplitude = A * k; % Amplitude of harmonics relative to
the fundamental
31
for i = 1: length ( harm )
32
noisy_harmonics_signal = harmonics_amplitude * sin (2* pi* harm ( i)* t);
33 signal = signal + noisy_harmonics_signal ;
34 end
35
42
1 function y = firorder558 ( x)
2 % FIRORDER 558 Filters input x and returns output y.
3
4 % MATLAB Code
5 % Generated by MATLAB ( R) 9.12 and DSP System Toolbox 9.14.
6 % Generated on: 16 - Apr - 2024 10 :33 :51
7
8 %# codegen
9
10 % To generate C/ C++ code from this function use the codegen command . Type
% ’ help codegen ’ for more information .
11
12 persistent Hd;
13
14
if isempty ( Hd)
15
% The following code was used to design the filter coefficients :
16
% % Generalized REMEZ FIR Bandpass filter designed using the FIRGR
17
function .
18 %
% % All frequency values are in Hz.
19 % Fs = 2500; % Sampling Frequency
20
21
22 %
23 % Fstop 1 = 30; % First Stopband Frequency
24 % Fpass1 = 46; % First Passband Frequency
25 % Fpass2 = 54; % Second Passband Frequency
26 % Fstop 2 = 70; % Second Stopband Frequency
27 % Dstop 1 = 0 . 0 0 0 5 6 2 3 4 1 3 2 5 1 9 ; % First Stopband Attenuation
28 % Dpass = 0 . 0 0 0 5 7 5 6 4 6 2 0 9 6 6 ; % Passband Ripple
29 % Dstop 2 = 0 . 0 0 0 5 6 2 3 4 1 3 2 5 1 9 ; % Second Stopband Attenuation
37
30 % = 20; % Density
31 dens Factor
32 %
% % Calculate the coefficients using the FIRGR function .
33 % b = firgr(’ minorder ’, [0 Fstop 1 Fpass1 Fpass2 Fstop 2 Fs / 2]/( Fs /2),
[0
34 ...
35 % 0 1 1 0 0], [ Dstop 1 Dpass Dstop 2 ], {
dens }); end
36
37
y = step ( Hd , double ( x));
38
39
40 % [ EOF
]
Listing 6: FIR filter code (filter coefficients folded away).
1 u2 = udpport (" LocalPort " ,8080 ," LocalHost "," ZORRO ");
2
title (’ Phasor␣Measurments ’)
3
ax1 = subplot (4 ,1 ,1);
4 line1 = animatedline ( NaT , NaN , ’ Line Style ’ , ’ - ’);
5 ylim ([70 120])
title ( ax1 ,’ Amplitude ’)
6
xlabel(’ Time ’)
7
ylabel(’ Voltage ␣[ V]’)
8
9
ax2 = subplot (4 ,1 ,2);
10 line2 = animatedline ( NaT , NaN ,’ Line Style ’ , ’ - ’);
11 ylim ([0 6 .28 ])
title ( ax2 ,’ Phase ’)
12
xlabel(’ Time ’)
13
ylabel(’ Phase ␣[ rad ]’)
14
15
ax3 = subplot (4 ,1 ,3);
16 line3 = animatedline ( NaT , NaN ,’ Line Style ’ , ’ - ’);
17 ylim ([49 .5 50 .5 ])
18
title ( ax3 ,’ Frequency ’)
xlabel(’ Time ’)
19
y l a b e l ( ’ F r e q u e n c y ␣ [ Hz]’)
20
21
ax4 = subplot (4 ,1 ,4);
22
line4 = animatedline ( NaT , NaN ,’ Line Style ’ , ’ - ’);
23 ylim ([-10 10])
24
title ( ax4 ,’ ROCOF ’)
xlabel(’ Time ’)
25
ylabel(’ ROCOF ␣[ Hz/ s]’)
26
27
i = 0;
28
while true
29
30
31
32
33
38
34 i = i + 1;
35 raw = read ( u2 ,46 ," string
36
"); data = split( raw , ’\’);
37
45
start = endtimestamp_datetime - seconds (5);
46
47
addpoints ( line1 , endtimestamp_datetime , amplitude ); drawnow ;
48 xlim ( ax1 ,[ start endtimestamp_datetime ]);
49
50
addpoints ( line2 , endtimestamp_datetime , phase ); drawnow
51
; xlim ( ax2 , [ start endtimestamp_datetime ]);
52
53
54
addpoints ( line3 , endtimestamp_datetime , freq );
drawnow ; xlim ( ax3 ,[ start endtimestamp_datetime
55
]);
56
57
58
addpoints ( line4 , endtimestamp_datetime , rocof); drawnow ;
xlim ( ax4 , [ start endtimestamp_datetime ]);
59
end
60
61
62
39