Thursday, September 10, 2009

About revision

funny ....
my first day of final is this subject ....
but u know ...
i just finish or only one chapter ....
where my friends already start another subject ...
izit this is the problems i facing to ??
or my friends having the same problems too ??
curious .....
why ??
just wonder why ??
never mind ...
i think all this already doesn't matter ...
cause no one will care about it ...except myself ...
who can help u ??
no one ...
this is because everyone also selfish..
no one will waste their time to teach u this ..
they just will tell u ...
why u didn't listen to lecturer while lecturer giving his/her speech ??
this i can tell u why ...
coz no one not willing to study ....
this is because each person got their own study method ...
while lecturer teaching us lesson ...,
we did listen ..
but sometiems ....i sure u may no fully understand what lecturer want to teach ...
what u can do is just accept ...
well ..
u think this will over ??
nope ....
i can surely tell u about this ..
if u really dunno ...
u must ask ...
ask who ??
your friends ??
yourself ??
textbook ??
haha ...^^
this u have to figure out by ur own ...
for me ...
i will ask google ..
althought i know sometiems the information from gogle may not correct at all ..
but i still can understand ...
okie ...
talk too much nonsence...
hope u all dun mind to listen all the crap i talk above ...

Friday, September 4, 2009

Electromagnetic Fields and Waves Assignment

Introduction
In our assignment, the antenna that we study is called TERK TV5 Indoor Amplified TV Antenna. The model is SU-112 and is manufactured from PANASONIC. This indoor amplified do not have any advantages to the conventional rabbit ears antenna. The rabbit ear antenna is relatively short which stand about five inches high. From the side, the antenna looks like an infinity sign and from the top, it looks like two loops. The antenna only uses a cable to connect to the television which means that the antenna is powered from the television and only works when the television is on.
Objectives
The objectives of this assignment are to understand the principles on how the rabbit ear antenna works, the radiation of a TERK TV5 Indoor Antenna patterns, signal strength of the antenna, characteristics of the antenna, strengths and weaknesses an indoor antenna and the designation of the antenna.
Outcomes
We learn that this antenna have a unique type of signal strength and polarization pattern. We also learn that friends, library and internet sources are important to gain more knowledge on antenna. Beside that, we learn that by distributing the work among us, it can be done faster and teamwork is very important among us.












Theory
Antenna is a device use to propagates and receive radiated electromagnetic waves. Antenna helps transformed guided electromagnetic waves propagates freely in free space (or vise versa) from the transmission line (waveguides) to a specific direction depending on the directional characteristics of the antenna. A few of the important characteristics discussed in this assignment are antenna’s radiation pattern, power gain, directivity, and polarization.
Antenna Radiation Pattern
Radiation pattern describe the relative strength involve in the radiated field where the antenna radiates in various direction. Radiation pattern can also called reception pattern as it shows how the properties receiving of the antenna. The radiation pattern is three dimensional plots from the source. Usually, we take the measurement in two dimensional which is slices of the three dimensional pattern. The two forms that we take are the elevation pattern and the azimuth pattern. The elevation pattern takes the measurement from the side where the antenna radiates while the azimuth pattern takes from the top as the antenna radiates.
When both the elevation pattern (Figure 1.1a) and the azimuth pattern (Figure 1.1b) combines, it shows the three dimensional radiation pattern of the energy radiated from the antenna (Figure 1.1c).
These pattern measurements can be represented using rectangular form or polar form. Rectangular form shows great details but it is difficult to visualize the antenna behavior from different directions. This is because the radiation pattern only shows how high the power gain is different angle without showing the effectiveness of it.
Polar form however, is widely used because the polar coordinate graph can show the points by projecting in a rotating axis to an intersection with one of the several concentric circles. Polar coordinates can be divided into two classes which are linear and logarithmic.
Linear class is where the concentric circle are equally spaced, and also when graduated. This kind of grid can be used to prepare a linear plot of the power in the signal. For comparison, the concentric circles are then replaced with appropriate decibel response. Lobes with higher peaks (approximately 15 dB) or below the main lobe will disappear because the power gain is small. This actually helps enhance the plots with high directivity and small minor lobes. This will let the voltage of the signal to be able to be plotted on a linear coordinate system instead of the power of the signal but the degree in the linear power grid will then differ.
In logarithmic class, the polar coordinate system concentric lines are spaced periodically depending on the logarithm of the voltage of the signal. This can affect the appearance of the plotted patterns if different values a used. Therefore, if 0 dB is used as reference for the outer edge, the lobes (around 30 dB) that are below the main lobes can still be distinguish. This means that the spacing between 0 dB and -3 dB will be greater than the spacing between -20 dB and -23 dB and it so on. The spacing will then correspond to the significance changes in the antenna performance.
There are two types of radiation patterns, which are absolute and relative. Absolute patterns are used with absolute units of field strength or power while relative patterns are used relatively to the unit of the field strength or power.
The radiation patterns are different depending on the distance. The term near-field is used where the field pattern exists close to the antenna. The term far-field (or radiation filed) is used where field patterns are at large distances.
Usually, a sufficiently large distance is used as the minimum permissible distance depends on the dimensions of the antenna in relation to the wavelength. Therefore, the minimum distance from the antenna is given to be two times of the square of the largest dimension of the antenna divided by the wavelength.
rmin = 2d2/
where rmin is the minimum distance from the antenna, d is the largest dimension of the antenna, and  is the wavelength.




Figure 1.1


Power Gain
The gain is defined to be dimensionless ratio without any physical term such as Watt or Ohms in reference to a standard antenna. Two reference antennas that are commonly used are the isotropic antenna and the resonant antenna. The isotropic antenna can radiates equally well in all directions but real isotropic antenna do not exist. Theoretically it is used to compare with real antennas. Any real antenna radiates more energy is some directions than the other. The total power radiated is then the same as an isotropic antenna because antenna cannot create energy. Therefore, if additional energy is radiated in one direction, it will offset by equally radiating less energy in other directions.
The power gain of an antenna in a given direction is the ratio of the power input to the antenna to the power output from the antenna. Usually, the maximum gain is interested in which the gain in the direction in which the antenna is radiating the most power. The gain is referred in dBi, which is the logarithmic gain relative to an isotropic antenna while the gain will be written ad dBd, in which it is the logarithmic gain relative to a dipole antenna.
Directivity
Directivity of an antenna is how the concentrated of the radiated power in a particular direction when transmitting or when receiving energy. It is possible to direct radiated power to any wanted direction. For wireless link, fixed locations for both the receiver and transmitter antenna are used. For mobile application, an Omni-directional antenna is used as transceiver does not have any fixed position. An Omni-directional antennal can ideally radiate in all directions. Directivity measurement is usually obtained from the ratio of radiation intensity in a given direction to the average radiation intensity.
Polarization
Polarization is the orientation of the electric field of electromagnetic waves far from the source. In general, polarization is described by an ellipse. Two special types of elliptical polarization are linear polarization and circular polarization.
In linear polarization, the electric field vector stays in the same plane all the time. Electric field may then leave the antenna in vertical, horizontal, or oblique orientation. Vertical polarized radiation is less affected by reflections over the transmission path while in horizontal polarization, reflection cause variations in the received signal strength making it less likely to have man- made interference.
In circular polarization, the electric field vectors appear to be rotating with circular motion about the direction of propagation with one full turn for each RF cycle. This rotation can be circular right hand, circular left hand, elliptical right hand or elliptical left hand.
Polarization is important when we want to get the maximum performance of the antennas. Therefore, the initial polarization of the radio waves is determined by the antenna. By matching the polarization of the transmitting and receiving antenna, we can get the best performance.

Figure 1.2 Showing how the sine wave of the electric field moves in perpendicular to the magnetic field in the direction of propagation

When both the receiving antenna and the transmitting antenna have the same spatial orientation, polarization and axial ratio, maximum power can then be transfer. If both antennas are not properly aligned and do not have the same polarization, the power transfer will be lesser. Lesser power transfer will then reduce the efficiency and performance of the whole system.
If both antennas are linearly polarized but not properly aligned, it will result in mismatch loss which can then be calculated with,
Loss (dB) = 20 log (cosine )
where is the difference in the aligned angle between the two antennas.
In conclusion, the more mismatch in polarization between the two antennas, the more apparent loss it have.





Type of antenna
The antenna that we used is called the rabbit ear antenna. It two rabbit ear part can be adjusted to become shorter of longer by pulling the center part or the antenna. This will then create a reflector in the center. In our case study, we find that by putting the two rabbit ear to maximum we can get the maximum gain. The transmission line used in this case is 75 ohms and a capacitor type plug allows the antenna to just plug into the television without any power supply. In out study, we remove the capacitor plug and wired it to the spectrum analyzer to find the signal strength. This antenna does not have any switch to on/off or to amplifier the signal. Besides, this antenna also creates two loops in the rabbit ear form.
Advantages
The advantages of the rabbit ear antenna are fewer adjustments needed to find the best reception, by pulling the rabbit ear out or by pushing the rabbit ear in, we can find that the reception of the TV channel is well receive. Furthermore, the easy rotation can exploit deep response nulls for all polarizations. This can help rejects co-channel or adjacent channel interference despite transmit polarization. This rabbit ear antenna can minimize multipath distortion of circular polarized signal which null the opposite circular polarized signal.
Disadvantages
The disadvantages of the antenna are that when every channel changes the person need to readjust the antenna and as time goes by, the signal might receive some man- made interference that cause disruption in the picture quality.
Ways to Improve
This antenna overall can provide better signal if a reflector is placed behind the antenna that can help amplified the signal. By putting it in higher places, we can minimize the interference when a person passes by.







Details of Case Study and Its Finding
First we find that the maximum signal strength is 89.5cm we -20.0dBm. This is to find the power gain of the antenna. This is actually done by increasing the distance of it by 10 cm. First, we find the maximum signal strength by moving the antenna towards the transmitter. Then, by increasing the distance between the transmitter and receiver antenna, we get the following results:
Separation between transmitterand receiver (cm) Signal strength (dBm)
89.5 -20.0
99.5 -20.5
109.5 -21.8
119.5 -29.6
129.5 -26.8
139.5 -25.9
149.5 -24.3
159.5 -23.0
169.5 -20.0

After this finding, we proceed to find the polarization of the antenna. First we mark the maximum signal strength as 0 degree. By using the same distance throughout experiment and by turning it anti- clockwise every 30 degree, the following results are obtained:
Degrees Signal strength (dBm)
0 -20.0
30 -22.5
60 -22.7
90 -22.2
120 -21.2
150 -20.0
180 -20.0
210 -20.0
240 -20.0
270 -23.7
300 -24.6
330 -21.7
360 -21.8

After obtaining the result, the graph of separation between the transmitter and receiver versus the signal strength are draw (see next page). The polarization graph is also sketched (see the page after).
From the experimentation, we find that the rabbit ear antenna have a maximum signal strength at 89.5 cm and decreasing as the distance increase until a certain distance (129.5cm) the signal strength begin to increase again and reaches the maximum signal strength. We can conclude that this is a far-field antenna. This antenna increase in certain distance might be due the back part of the ear that helps reflect and receive signal making the signal strength increase. As the maximum strength is received at 169.5cm, we can conclude that the signal strength will decrease again as the distance increase and the signal continues.

For the second part, as we continue to turn, we find that at certain degree (0,150,180,210,240) the signal strength is at maximum. This is because the polarization is aligned. As for the 150,210and 240 case, we find that it is maximum might be due to the antenna received signal at that point is maximum as the degree is near to the 180. We can also conclude that this antenna have a front and back which the signal when approaching 0 and 360 the signal is lesser. As for the 360 case, we find that it might be due to transmission line is turned together making the receiver signal has minor interference.
The study has been repeated 3 times before the final results are obtained.














Discussion:
The low-noise broadband amplifier built into this indoor antenna features a simple one-touch adjustment for all stations, and TERK's patented selectable amplifier bypass prevents over modulation of stronger incoming signals. These controls allow you to provide the right amount of amplification to weaker signals, and yet not over do it with signals that don't need amplified. This amazing antenna also takes advantage of TERK's unique Complementary Symmetry technology that incorporates a pair of tuned receiving elements for excellent reception range and incredible clarity.
Conclusion:
In this assignment, we find that the TERK TV5 indoor antenna also known as rabbit ear antenna, is outdated in a way as more and more newer antenna is being designed. In a way, this antenna actually have more advantages compare as if no power supply is needed only the television. The best way to improve the antenna radiation is reduce the interference made by placing it a distance from any electronic devices that is not related (hand phones, radio). We also find out that this antenna have a radiation pattern in a figure eight and the signal strength depends on the distance and it can oscillates from low signal strength to high signal strength as the distance increase.








Antenna Comparison:

2009 Engineering Computing Assignment Ver2

Questions:

Question 1: Tic-Tac-Toe

For this question, you are going to use two-dimensional array concepts to program a game called Tic-Tac-Toe. You should set up the program so that a human can play against another human (two people). Tic-Tac-Toe is a board game with a 3 x 3 board of squares, all of which are initially empty. There are two players, known as ‘X’ and ‘O’, who take turns making moves. In this version of the game, the ‘X’ player will always move first. On a player’s turn, the player must place exactly one piece on an empty square of the board. The ‘X’ player always places pieces labeled ‘X’ and the ‘O’ player always places pieces labeled ‘O’. The game ends when either player fills three consecutive positions of the board, in a straight line that is either vertical, horizontal or diagonal. The player to first accomplish this wins. If the whole board fills with neither player able to get three of his or her pieces in a row, then the game is a draw.

Your program should begin by asking the name for player ‘X’ and player ‘O’. Then, your program should draw an empty Tic-Tac-Toe board on the screen. After that, your program should prompt the `X' player to enter a move, and redraw the board with the newly placed piece in the correct position. After every move, the program should test to see if the player won or the board is filled up, in which case the game is over and the program can print the winner (or that it is a draw).

You may assume that when the user is asked to enter a row and a column to place a piece, then the user always enters two integers. However, you should not assume that the user enters integers that correspond to valid board positions - the player may pick a spot that corresponds to a spot of the edges of the board, or a spot that is already occupied. In this case, the program should keep prompting the user for a new spot until the he or she enters a valid position (Your program should perform any necessary error checking).

The following is a sample run of one version of the choice. Your program should behave in a similar manner, but it does not have to be identical to this one.

Sample Output
.................................................
. TIC-TAC-TOE.
.................................................
Welcome to the game of tic-tac-toe!
Player1, what is your name? Shereen
Player2, what is your name? Chadd
0 1 2
--- --- ---
0 | | | |
--- --- ---
1 | | | |
--- --- ---
2 | | | |
--- --- ---

Shereen, please make your move:
Enter row: 0
Enter column: 0
0 1 2
--- --- ---
0 | X | | |
--- --- ---
1 | | | |
--- --- ---
2 | | | |
--- --- ---

Chadd, please make your move:
Enter row: 1
Enter column: 1
0 1 2
--- --- ---
0 | X | | |
--- --- ---
1 | | O | |
--- --- ---
2 | | | |
--- --- ---



Question 2: Laundry Management System

CLEAN LAUNDRY is a new laundry centre near UTAR University. As business is growing rapidly, they are having problems keeping track of their customers and their daily business transactions. You are asked to develop a simple laundry management system to cater for their business. Assume that there are maximum 40 customers per day.

The program will first read the customer information (name, age and sex), weight of the laundry and calculate the total payment for that customer. The price per kilogram for the laundry is based on the table below.

Weight| Price per kilogram
Less than 3kg| RM1.20
3kg to 6kg| RM1.00
More than 6kg| RM0.80

The program will then print a billing receipt that contains the following information:
• The centre information (name, address, and telephone number),
• Customer’s information.
• Weight of the laundry
• Price of kilogram
• Payment
Use structure to store the above information. You should include as well typedef and structure within structure whichever applicable.

Ask the user if they would like to continue (“STOP” for stop, “CONTINUE” for continue). When the choice is “STOP”, the program will display the summary of the day contains total number of customers for the day and the total payment for the day.


Answer:

* This tic-tac-toe program allow 2 human player to play againts each *
* other with player X always starts 1st. After each game, players will *
* be prompt if to play again. *
* All user input were taken as string to check for error and later *
* convert to a proper format for calculationa or storage. *
* String for input were given plenty of memory space to prevent *
* gets() function from giving error when operator input longer *
* than assigned memory space. *
**************************************************************************/

//preprocessors directives
#include
#include
#include
#include

//functions declaration
void welcome();
void name_X();
void name_O();
void print_table();
void won(char);
void players(char);
int winnercheck(char);
int check_draw();
int continues();


//global variables declaration
char nameX[100],nameO[100];
int checkX[3][3];
int checkO[3][3];

void main()
{
char con;
int i,j;
do{

//to initialize the array to 0
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
checkX[i][j]=0;
checkO[i][j]=0;
}
}

welcome();//call func print welcome screen
name_X();//cal func prompt name of X
name_O();//call func prompt name of O

players('x');

con=continues();//call func prompt user to play again?
}while(con==1);

}




void welcome()
{//clear screen and display welcome screen
system("cls");
printf("#################################################\n");
printf("#\t\t\t\t\t\t#\n");
printf("#\t\t TIC-TAC-TOE\t\t\t#\n");
printf("#\t\t\t\t\t\t#\n");
printf("#################################################\n");
printf("\tWelcome to the game of tic-tac-toe!\n\n");
}



void name_X()
{
int i;

do{//repeat while input is empty
printf("Player1, what is your name? ");
gets(nameX);//get player X name

if(strlen(nameX)==0)//check if input is empty
{
printf("Invaid Input!\n");
system("pause");
}
}while(strlen(nameX)==0);

//make 1st char of each word to uppercase
nameX[0]=toupper(nameX[0]);
for(i=0;i<(strlen(nameX));i++)
if(isspace(nameX[i]))
nameX[i+1]=toupper(nameX[i+1]);
return;
}
void name_O()
{
int i;

do{//repeat while input is empty
printf("Player2, what is your name? ");
gets(nameO);//get player O name

if(strlen(nameO)==0)//check if input is empty
{
printf("Invaid Input!\n");
system("pause");
}
}while(strlen(nameO)==0);

//make 1st char of every word to uppercase
nameO[0]=toupper(nameO[0]);
for(i=0;i<(strlen(nameO));i++)
if(isspace(nameO[i]))
nameO[i+1]=toupper(nameO[i+1]);
return;
}

void print_table()
{
int i=0,j=0;
system("cls");//clear screen
printf("\n\n");
//start printing table with correct marking
printf("\t 0 1 2\n");
printf("\t%c---%c---%c---%c\n",218,194,194,191);

for(i=0;i<3;i++)
{
printf(" %d |",i);
for(j=0;j<3;j++)
{
if(checkX[i][j]==1)
printf(" X |");
else
if(checkO[i][j]==1)
printf(" O |");
else
printf(" |");
}
printf("\n\t%c---%c---%c---%c\n",(i==2?192:195),(i==2?193:197),(i==2?193:197),(i==2?217:180));
}
return;
}


int continues()
{
char con[10];
int cont;
do{
printf("\nPlay again?\n1-yes\n2-no\n");
gets(con);//get user input as string
fflush(stdin);
cont=atoi(con);//convert stringt to int
if(cont!=1&&cont!=2)
printf("Invalid Input!\n\n");
}while(cont!=1&&cont!=2);

return cont;
}


int winnercheck(char player)//check if player has won he game
{
int i,j,win=0;
int check[3][3];

//copy content of array to a new array for testing
if(player=='x')
for(i=0;i<3;i++)
for(j=0;j<3;j++)
check[i][j]=checkX[i][j];
else
for(i=0;i<3;i++)
for(j=0;j<3;j++)
check[i][j]=checkO[i][j];

for(i=0;i<3;i++)
{
//check vertical
if(check[0][i]==1&&check[1][i]==1&&check[2][i]==1)
win=1;
}

for(i=0;i<3;i++)
{
//check horizontal
if(check[i][0]==1&&check[i][1]==1&&check[i][2]==1)
win=1;
}

//check diagonal "\"
if(check[0][0]==1&&check[1][1]==1&&check[2][2]==1)
win=1;

//check diagonal "/"
if(check[0][2]==1&&check[1][1]==1&&check[2][0]==1)
win=1;

return win;
}

void players(char player)//call player X or O turns
{
char inrow[100],incol[100];
int i,j,rrow,rcol,error,win;
char row[10],col[10];

do{
error=0;
system("cls");

print_table();//call func print 3x3 table
printf("%s, please make your move\n",(player=='x'?nameX:nameO));
printf("Enter row number: ");
fflush(stdin);
gets(inrow);//get row input
fflush(stdin);
printf("Enter column number: ");
gets(incol);//get column input
fflush(stdin);

if(strlen(incol)==0 || strlen(inrow)==0)//check if input is empty
{
printf("Invalid Input!\n");
system("pause");
error=1;
}
else
{

//strip white space from input
for(i=0,j=0;inrow[i]!='\0';i++)
{
if (inrow[i] != ' ' && inrow[i] != '\t')
row[j++]=inrow[i];
}
row[j]='\0';

for(i=0,j=0;incol[i]!='\0';i++)
{
if (incol[i] != ' ' && incol[i] != '\t')
col[j++]=incol[i];
}
col[j]='\0';

//check for illegal char in string
for(i=0;i {
if(inrow[i]>57 || inrow[i]<48 )
error=1;
}

for(i=0;i {
if(incol[i]>57 || incol[i]<48)
error=1;
}

if(error!=1)
{//if no error convert string to int
rrow=atoi(inrow);
rcol=atoi(incol);

if(rrow<0 || rrow>2 || rcol<0 || rcol>2)
{//check if value entered is in range
printf("Invalid input!\n");
system("pause");
error=1;
}
else if(checkO[rrow][rcol]==1 || checkX[rrow][rcol]==1)
{//check if the selected box is occupied
printf("\nThat box is already occupied!\n");
system("pause");
error=1;
}
else//mark selected box with X or O
(player=='x'?checkX[rrow][rcol]=1:checkO[rrow][rcol]=1);
}
else
{
printf("Invalid Input!\n");
system("pause");
}
}


}while(error==1);


win=winnercheck(player);//check if player won
if(win==1)
won(player);
else if(check_draw()==1)//check if the game is a draw
{
system("cls");
printf("\n\n\t\tIt is a Draw!\n");
}
else//if none win or draw, continue game with opposite player
players((player=='x'?'o':'x'));

return;
}

void won(char player)
{//clear screen then print winning player
system("cls");
if(player=='x')
printf("\n\n\t\t%s won the game.!!\n",nameX);
else
printf("\n\n\t\t%s won the game.!!\n",nameO);

return;
}

int check_draw()
{//function to check if any player has won the game
int sum=0,i,j;

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
sum+=checkX[i][j];
sum+=checkO[i][j];
}
}

if(sum==9)//if all boxes are filled(draw)
return 1;//return 1 if draw
else
return 0;//return 0 if not draw
}


/**********************************************************************

* This program uses structures to store groups of data. *
* The program will run maximum of 40 times and will terminate before *
* that if the operator decides to stop the program. *
* All user input were taken as string to check for error and later *
* convert to a proper format for calculationa or storage. *
* String for input were given plenty of memory space to prevent *
* gets() function from giving error when operator input longer *
* than assigned memory space. *
**********************************************************************/

//preprocessors directives
#include
#include
#include
#include

//constant definitions
#define L3 1.2
#define T6 1.0
#define M6 0.8

//structures
struct private_info{
char name[100];
int age;
char gender[7];
};

struct shop{
char shopname[100];
char shopadd[100];
char tel[12];
}shopDetail={"CLEAN LAUNDRY","NO. 12,JALAN PAHANG,KUALA LUMPUR.","03-12345678"};

typedef struct customer_detail{
struct private_info info;//structure in structure
float weight;
float payment;
}CUSTOMER;//define structure as CUSTOMER

//functions definitions
CUSTOMER get_cust();
void print_receipt(CUSTOMER);
void summary(int i,CUSTOMER cus[40]);
float calc(float weight);
int cont();

//main function
int main()
{
CUSTOMER cus[40];
int con=1,i;
//program run max 40 times and terminate or when con==0
for(i=0;i<40&&con==1;i++)
{
system("cls");//clear screen
cus[i]=get_cust();//store data into structure array
cus[i].payment=calc(cus[i].weight);//calc and store payment
print_receipt(cus[i]);//print receipt
if(i!=39)//if 40th iteration, do not prompt to continue
con=cont();//prompt to continue
}
summary(i,cus);//print summary
system("pause");//pause program when done
return 0;
}

CUSTOMER get_cust()
{
//extra long string to avoid corruption due to gets() *should use fgets()*
char temp_age[100],temp_gender[100],temp_weight[100];
int error,i,count;
CUSTOMER cus;

do{//repeat if invalid input
printf("Please enter customer's name: ");
gets(cus.info.name);//get name
fflush(stdin);//flush input buffer

if(strlen(cus.info.name)==0)//check if name is empty
printf("Invalid Input!\n");
else
{ //make every 1st char of word to be uppercase
cus.info.name[0]=toupper(cus.info.name[0]);
for(i=0;i if(isspace(cus.info.name[i]))
cus.info.name[i+1]=toupper(cus.info.name[i+1]);
}
}while(strlen(cus.info.name)==0);

do{//repeat if invalid input
error=0;
printf("Age: ");
gets(temp_age);//get age as string
fflush(stdin);//flush input buffer

if(strlen(temp_age)==0)//check if input is empty
{
error=1;
printf("Invalid Input!\n");
}
else
{ //check for unwanted char in string
for(i=0;i {
if(!isdigit(temp_age[i]))
error=1;
}
}

if(atoi(temp_age)==0)//age zero not allowed to enter the shop *laugh*
error=1;

if(error==1)
{
printf("Invalid Input!\n");
}
else //convert string to int and store into structure
cus.info.age=atoi(temp_age);
}while(error==1);

do{//repeat if invalid
error=0;
printf("Gender (M/F): ");
gets(temp_gender);//get gender as string
fflush(stdin);

if(strlen(temp_gender)>1)//make input invalid if length >1
{
error=1;
printf("Invalid Input!\n");
}
else if(temp_gender[0]!='M' && temp_gender[0]!='m' && temp_gender[0]!='F' && temp_gender[0]!='f')
{//allow 'm','M','f','F' only
error=1;
printf("Invalid Input!\n");
}
else
{//if no error,
cus.info.gender[0]=tolower(temp_gender[0]);
}

}while(error==1);

printf("---------------------------------------------\n");
printf("| WEIGHT | Price per kilogram |\n");
printf("---------------------------------------------\n");
printf("| Less than 3 kg | RM %.2f |\n",L3);
printf("---------------------------------------------\n");
printf("| 3kg to 6kg | RM %.2f |\n",T6);
printf("---------------------------------------------\n");
printf("| More than 6kg | RM %.2f |\n",M6);
printf("---------------------------------------------\n");

do{//repeat if invalid input
error=0;
printf("Enter the weight of laundry\n");
gets(temp_weight);//get weight as string
fflush(stdin);

if(strlen(temp_weight)==0)
{
printf("Invalid Input!\n");
error=1;
}
else
{
count=0;
for(i=0;i {//check for unwanted char in string, allow digit and dot only
if(temp_weight[i]==46)//allow only 1 dot
count++;
if( (!isdigit(temp_weight[i]) && temp_weight[i]!=46) || count>1)
error=1;
}
if(error==1)
printf("Invalid Input!\n");
else
cus.weight=atof(temp_weight);//convert string to num
}

}while(error==1);

return cus;
}


void print_receipt(CUSTOMER cus)
{
float rate;

if(cus.weight<3)
rate=L3;
else if(cus.weight>=3 && cus.weight<=6)
rate=T6;
else if(cus.weight>6)
rate=M6;

//clear screen and print receipt
system("cls");
printf("\t OFFICIAL RECEIPT\n\n");
printf("\t\t%s\n",shopDetail.shopname);
printf("\t%s\n",shopDetail.shopadd);
printf("\t TEL:%s\n",shopDetail.tel);
printf("-----------------------------------------------\n\n");
printf(" Customer Name\t\t: %s\n",cus.info.name);
printf(" Age\t\t\t: %d\n",cus.info.age);
printf(" Gender\t\t: %s\n",(cus.info.gender[0]=='m'?"Male":"Female"));
printf(" Weight of laundry\t: %.2fkg\n",cus.weight);
printf(" Price per kilogram\t: RM%.2f\n",rate);
printf(" ------------------------------------\n");
printf(" Subtotal \t\t: RM%.2f\n",cus.payment);
printf(" ------------------------------------\n");
printf("\n\n\n\n\n\n\n\n");

return;
}

int cont()
{
char con[12],con1[]="CONTINUE",con2[]="STOP";
int cont,i;

do{//prompt to continue
printf("Do you want to continue (\"CONTINUE\"/\"STOP\") ?\n");
gets(con);
fflush(stdin);

if(strlen(con)==0)//check if input is empty
printf("Invalid Input!\n");
else
{ //convert input to uppercase
for(i=0;i con[i]=toupper(con[i]);
//compare processed input with predefined string
if(strcmp(con,con1)==0)
cont=1;
else if(strcmp(con,con2)==0)
cont=0;
else
printf("Invalid Input!\n");
}
}while(cont!=1 && cont!=0);

return cont;
}

void summary(int i,CUSTOMER cus[40])
{
int j;
float sum=0;

//calc total payment
for(j=0;j sum+=cus[j].payment;

//clear screen and print summary
system("cls");
printf("\tTotal customer today : %d\n",i);
printf("\tTotal payment today : RM%.2f\n\n\n",sum);

return;
}

float calc(float weight)
{
float pay;
//calc amount needed to pay
if(weight<3)
pay=weight*L3;
else if(weight>=3 && weight<=6)
pay=weight*T6;
else if(weight>6)
pay=weight*M6;

return pay;//return amount
}

2009 Engineering Computing Assignment Ver1

Question:
Write a program that will ask the user to choose among these three choices/modules:
1) Weather balloons
2) Compass Heading
3) Drag Force

Each choice/module is described below:

Choice 1: Weather balloons
Weather balloons are used to gather temperature and pressure data at various altitudes in the atmosphere. The balloon rises because the density of the helium inside the balloon is less than the density of the surrounding air outside the balloon. As the balloon rises, the surrounding air becomes less dense, and thus the balloon’s ascent slows until it reaches a point of equilibrium.

During the day, sunlight warms the helium trapped inside the balloon, which causes the helium to expand and become less dense; thus, the balloon will rise higher. During the night, however, the helium in the balloon cools and becomes more dense; thus, the balloon will descend to a lower altitude.

The next day, the sun heats the helium again and the balloon rises. Over time, this process generates a set of altitude measurements that can be approximated with a polynomial equation. Assume that the following polynomial represents the altitude or height in meters during the first 48 hours following the launch of a weather balloon.

h(t) = -0.12t4 + 12t3 – 380t2 + 4100t + 220

where the units of t are in hours. The corresponding polynomial model for the velocity in meters per hour of the weather balloon is

v(t) = -0.48t3 + 36t2 - 760t + 4100


Write a program that will print a table of the time, altitude and the velocity for this weather balloon using units of meters and meters per second. Let the user enter the start time, the increment in time between lines of the tables and the ending time, where all the values must be less than 48 hours. Print a message to the user that specifies an upper bound of 48 hours. Make sure that your program checks the user input stays within the proper bounds. If the are errors, ask the user to reenter the complete set of report information.

After your table is printed out, also print the peak altitude and its corresponding time. Your program should also check that the final time is greater than the initial time. If it is not, ask the user to reenter the complete set of report information.


Choice 2: Compass Heading
While spending the summer as a surveyor’s assistant, you have been given a task to write a program that will transforms compass heading in degrees (0 to 360) to compass bearings. A compass bearing consists of three items: the direction you face (north or south), an angle between 0 and 90 degrees, and the direction you turn before walking (east or west).

For example, to get the bearing for a compass heading of 110.0 degrees, you would first face due south (180 degrees) and then turn 70.0 degrees east (180.0 – 70.0 is 110.0). Therefore, the bearing is South 70.0 Degrees East.

For the cardinal directions, the output should be the following:

Direction Heading Output
North 0.0 Compass Bearing: North 0.0 Degrees East
East 90.0 Compass Bearing: North 90.0 Degrees East
South 180.0 Compass Bearing: South 0.0 Degrees West
West 270.0 Compass Bearing: North 90.0 Degrees West


Choice 3: Drag Force
When an automobile is moving through the atmosphere, it must overcome a force (or wind resistance) called drag that works against the motion of the vehicle. The drag force can be expressed as:

F = ½ Cd * A * ρ * V2

where F is the force(in Newton), Cd is the drag coefficient, A is the projected area of the vehicle perpendicular to the velocity vector (in m2), ρ is the density of the gas or fluid through which the body is traveling (1.23 kg/m3), and V is the body’s velocity.

Write a program that allows a user to input A and Cd interactively to compute the drag force giving the range of velocities from 0 m/s to 40 m/s and display a table showing the drag force for the input shape given.




Answer:

/************************************************************************
* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX *
* XXXXXXX ENGINEERING COMPUTING *
* 3E XXXX *
* Assignment 1 *
* Group members (by alpha order) : *
* *
* *
* Due Date: xxxxxxxx *
* *
* Lecturer's name: Ms. xxxxxxxxx *
* *
* In the main function, switch case was used to select user option. *
* User input was checked if it is numerical else, it will return *
* invalid input to the screen and allow user to retry. *
* *
* In the balloon function, prompt for start and ending time. *
* altitute, velocity and time was calculated using equations provided.*
* Nested do loop was used to loop the program when the user entered *
* invalid input. Characters are not supported. Table was *
* printed using for loop. *
* *
* In compass function, it allow user to enter campass reading and *
* convert it to bearing reading. Characters is not supported. *
* Strcpy() function was used to assign string to a variable and later *
* to print desired string to screen using printf. *
* *
* In drag function, prompt area and drag coefficient. Drag force was *
* then calculated using equation given. Characters input is *
* unsupported. The program will loop if invalid input was given and if*
* user decide to continue using the function. *
************************************************************************/

//preprocessors directives
#include
#include
#include
#include
#include
//define constants
#define MAX_LINE_BUFFER 256
#define DENSITY 1.23

//functions declaration
void balloon();
void compass();
void drag();

float to_hour(float h,float m);
int round(float x);




void main()
{
//local variables
int choice,confirm;
char temp[MAX_LINE_BUFFER];
char str,test;

do{//post test loop to repeat program

system("cls");
printf("==================Main Menu==================\n");
printf("\t1\tWeather balloons\n");
printf("\t2\tCompass Heading\n");
printf("\t3\tDrag Force\n");
printf("\t4\tQuit\n");
printf("=============================================\n");
printf("Please insert your choice: ");
fgets (temp, MAX_LINE_BUFFER, stdin); //store user input to temp, max 256bytes
sscanf(temp,"%c",&test);//scan 1st char in user input

if(!isdigit(test))//if 1st char is not num, invalid input
choice=0;
else
sscanf(temp,"%d%c",&choice,&str);//scanf for first int and char from temp

if(!isspace(str))//if str is not whitespace, make choice invalid
choice=0;

flushall();//clear remaining input in stream i.e. char after str


switch(choice)
{
case 1 : balloon(); //call balloon function
break;
case 2 : compass(); //call compass function
break;
case 3 : drag(); //call drag function
break;
case 4 : printf("Ended!\n");
system("pause");
break;
default: system("cls");
printf("You have entered an invalid choice..!\n");
printf("Please enter you choice again.\n");
system("pause");
break;
}
}while(choice!=4);//stop looping when choice==4

}




//======================================== start of module 1 ==================================
void balloon()
{
int error=0,maxhour,hour,minute,maxminute,confirm;
float starthour,startminute,total_increment_hour,endhour,endminute,totalendhour,ihour,iminute;
float totalstarthour,height,velocity,maxheight=0,time,t;

do{
do{
do{
do{
system("cls");
//get start time
printf("Enter start time (less than 48hours)\n");
printf("Hour: ");//prompt for start hour
scanf("%f",&starthour);
flushall();
printf("Minute: ");//prompt for start minute
scanf("%f",&startminute);
flushall();
totalstarthour=to_hour(starthour,startminute); //call func to convert to hour only

if(starthour<0 || startminute<0 || totalstarthour>48)
{
printf("Invalid time input!\n");
printf("Please try again from the beginning.\n");
system("pause");
}
}while(totalstarthour>48 || starthour<0 || startminute<0);//start over if invalid input



//get end time
printf("\nEnter end time (less than 48 hours)\n");
printf("Hour: ");//prompt for end hour
scanf("%f",&endhour);
flushall();
printf("Minute: ");//prompt for end minute
scanf("%f",&endminute);
flushall();

totalendhour=to_hour(endhour,endminute); //call func to convert to hour only

if( endhour<0 || endminute<0 || totalendhour>48 || totalendhour<=totalstarthour)
{
printf("Invalid time input!\n");
printf("Please try again from the beginning.\n");
system("pause");
}

}while(totalendhour>48 || endhour<0 || endminute<0 || totalendhour<=totalstarthour);
//start over if invalid input


//get time increment
printf("\nEnter each line increment:\n");
printf("Hour: ");
scanf("%f",&ihour);
flushall();
printf("Minute: ");
scanf("%f",&iminute);
flushall();

total_increment_hour=to_hour(ihour,iminute);//convert to hour only

//check for increment value error
error=0;
if(ihour>(endhour-starthour) || ihour==(endhour-starthour) && iminute>(endminute-startminute))
{
printf("The increment must be less than the different of starting and ending time.\n");
error=1;
}
else if(total_increment_hour<0)
{
printf("Invalid value!\n");
error=1;
}
else if(total_increment_hour==0)
{
printf("The increment cannot be zero!\n");
error=1;
}
if(error==1)
{
printf("Please try again.\n");
system("pause");
}

}while(error==1);//start over if invalid input



//print table
printf("%c======================================================%c\n",213,184);
printf("| Time | Altitude | Velocity |\n");
printf("| | (meter) | (meter/hour) |\n");
printf("|-----------------+----------------+-------------------|\n");

do{
//convert hour to hour and minute
hour = floor(totalstarthour);
minute=round((totalstarthour-floor(totalstarthour))*60);
if(minute==60)
{
hour+=1;
minute=0;
}

t=totalstarthour;
height= (-.12*pow(t,4))+(12*pow(t,3))-(380*t*t)+(4100*t)+220;//calc altitute
velocity= (-0.48*pow(t,3))+(36*t*t)-(760*t)+4100;//calc velocity

//print content of table
printf("| %02d:%02d ", hour,minute);
printf("| %10.3f ", height);
printf("| %10.3f |\n",velocity);

if(height>maxheight)//to find greatest altitute
{
maxheight=height;
maxhour=hour;
maxminute=minute;
}

totalstarthour+=total_increment_hour;

}while(totalstarthour<=totalendhour);

printf("%c======================================================%c\n",212,190);

//printf peak altitute and coresponding time
printf("\nThe peak altitude is %.3fm, at %02d:%02d.\n\n",maxheight,maxhour,maxminute);
maxheight=0;//reset maxheight for user to continue in second loop
system("pause");

//prompt to continue?
do{
printf("Continue ???\n");
printf("1\tyes\n2\tno\n>");
scanf("%d",&confirm);
flushall();
printf("%d\n",confirm);
}while(confirm!=1 && confirm!=2);

}while(confirm!=2);//check if to continue
}


float to_hour(float h,float m)//convert hour and minute to hour in floating point
{
h=h+m/60;
return h;
}

int round(float x)//round up minute to fix trucation error of floating number
{
if((x-(int)x)>=0.5)
x=(int)x+1;
return x;
}



//==================================== start of module 2 ===========================
void compass()
{
//local variables
int confirm;
float bearing,dir;
char NorS[6],EorW[5];
do{
do{
bearing=-1;//initialize bearing to invalid value
system("cls");
printf("Bearing:\n ");//ask user to enter bearing
scanf("%f",&bearing);
flushall();
if(bearing<0 || bearing>360)
{
printf("Invalid bearing!\nPlease try again.\n");
system("pause");
}
}while(bearing<0 || bearing>360);//to start over if invalid input

//calc direction based on bearing quadrant
if(bearing>0&&bearing<90)
dir=bearing;
else if(bearing>=90&&bearing<=180)
dir=180-bearing;
else if(bearing>180&&bearing<270)
dir=bearing-180;
else if(bearing>=270&&bearing<=360)
dir=360-bearing;
else if(bearing==0)
dir=0;


//ternary conditional operators to decide which direction to print
(bearing<=90||bearing>=270? strcpy(NorS,"North"):strcpy(NorS,"South"));
(bearing<180? strcpy(EorW,"East"):strcpy(EorW,"West"));
printf("Compass Bearing: %s %.1f degree %s\n\n",NorS,dir,EorW);

//prompt to continue?
do{
printf("Continue ???\n");
printf("1\tyes\n2\tno\n>");
scanf("%d",&confirm);
flushall();
}while(confirm!=1 && confirm!=2);//prompt again if invalid input

}while(confirm!=2);//check if to continue
}



//============================================= start of module 3 =========================================
void drag()
{
float A,Cd,F;
int v,confirm,error=0;

do{
do{
do{
A=-1;//initialize area to invalid value
Cd=-1;//initialize coefficient to invalid value
system("cls");
printf("Please enter the value of projected area(in m%c)>>>\n",253);
scanf("%f",&A);//prompt for area
flushall();
if(A<0)//to check if area is valid
{
printf("Invalid area!\n");
printf("Please try again from the beginning.\n");
system("pause");
}
}while(A<0);//to start over if invalid input



printf("Please enter the value of drag coefficient>>>\n");
scanf("%f",&Cd);
flushall();
if (Cd<0)//to check if drag coefficient is valid
{
printf("Invalid coefficient!\n");
printf("Please try again from the beginning.\n");
system("pause");
}
}while(Cd<0);//to start over if invalid input


//print table
printf("%c=================================%c\n",213,184);
printf("| Velocity | Drag force |\n");
printf("| (m/s) | (N) |\n");
printf("|---------------+-----------------|\n");


for(v=0;v<=40;v++)//do for every v in between 0 and 40
{
F=(float)1/2*Cd*A*DENSITY*v*v;//calculate drag force
printf("| %02d ",v);
printf("| %10.3f |\n",F);
}

printf("%c=================================%c\n\n",212,190);

//prompt to continue?
do{
printf("Continue ???\n");
printf("1\tyes\n2\tno\n>");
scanf("%d",&confirm);
flushall();
}while(confirm!=1 && confirm!=2);//prompt again if invalid input

}while(confirm!=2);//check if to continue
}

2009 Communication systems assignment..

Question:
Universiti XXXXXXXX

Faculty of Engineering and Science


XXXXX Communication Systems
Assignment

In Lab 2, you are shown how to model a baseband binary NRZ coded communication system using Matlab. In this assignment you have to modify some of the functions given to you in Lab 2 in order to model a slightly different communication system. You are required to model a baseband binary communication system using Manchester coding, instead of NRZ coding. Again, sampling rate is 1000Hz and data rate is 100 bps.

i) The function nrz( ) has to be modified to produce the Manchester coded waveform. Use the short data string b = [1 0 0 1 1 1 0 1 0 1] and plot out the Manchester coded waveform. The Manchester coded waveform should range from -1V to +1V.
ii) Modify the low pass channel function lpchannel( ) so that it will have a bandwidth of 350 Hz. Send the signal through it and plot the output waveform.
iii) Modify the noise code so that it will produce added white Gaussian noise with single sided spectral density of N0 = 10mW/Hz. Add the noise generated to the signal and plot the resultant waveform
iv) Work out the voltage difference of the symbols s1 – s2 and put it into the correlator function corr( ). Plot the output of the correlator.
v) Produce a long string of data bits using the round( ) and rand( ) functions. Pass the data string through the low pass channel, add in white noise, estimate the transmitted data string using the correlator receiver, then measure the number of errors in order to produce the error probability. You are to do this for ratio of 1.0 to 4.0 at 0.5 intervals. You have to use as many data bits as is necessary in order to get a reliable Pe estimation. Plot out the Pe against the ratio.
vi) Work out the theoretical Pe for the different ratios and plot this curve on the same graph. Comment on any differences found.


Answer:

Name:xxx Course: 3E xxxx
ID: xxxxxxxx
Date of Submission: xxxxxxxxx


The Manchester coded waveform is ranged from -1V to +1V when b pass through mh function.

UEEA3523 Communication Systems

Output waveform of the signal rs go through low pass channel function with bandwidth of 350 Hz


Resultant waveform (rsn) that Gaussian noise with single-sided spectral density No = 10m W/Hz was added to the signal rs with the variance = 5 W/Hz (1: 10-3).


Voltage difference of the symbols with s1=1V, s2=-1V:
s1-s2 = +2V s2-s1 = -2V
Output waveform of rd


A long string of data bits b is used by using the round( ) and rand( ) functions
plot(d)


plot (rs)


plot(rsn)


plot(rd)


Manchester coded for b = [1 0 0 1 1 1 0 1 0 1] :

b = [1 0 0 1 1 1 0 1 0 1];
global fs fd
fs = 1000; %sampling rate is 1000Hz
fd = 100; % data rate is 100 bps
d = mh(b);
plot (d)
rs = lpchannel (d, 350);% bandwidth of 350 Hz
plot (rs)
noise = sqrt(5)*randn(1, 100);
rsn = rs + noise;
plot (rsn)
s1_s2 = [2 2 2 2 2 -2 -2 -2 -2 -2];
rd = corr(rsn, s1_s2);
plot (rd)
b=round(rand(1,1000));
d=mh(b);
plot(d)
rs=lpchannel(d,350);
plot(rs)
noise=sqrt(5)*randn(1,10000);
rsn=rs+noise;
plot(rsn)
s1_s2=[2 2 2 2 2 -2 -2 -2 -2 -2];
rd=corr(rsn,s1_s2);
plot(rd)
e=pe(b,rd)


x=[1 1.5 2 2.5 3 3.5 4];
y=[0.09 0.046 0.027 0.019 0.012 0.003 0.001];
z=[0.0786 0.0416 0.0228 0.0127 0.0072 0.0041 0.0023];

plot (x,y,'--');hold on;plot(x,z,' ');hold off
xlabel('Eb/No, dB');
ylabel('Pe');
title('Plot Pe against Eb/No');
legend('Measured' ,'Theoretical');












Measured Value for Pe:
Since the value of s1_s2 =[2 2 2 2 2 -2 -2 -2 -2 -2], so Eb is equal to
Tb . fs = 1 / (Tb) x 10 =1000

For Eb/No = 1.0
No = 0.01 / 1, noise = sqrt(5)*randn(1,10000);
>>b=round(rand(1,1000));
>>d=mh(b);
>>rs=lpchannel(d,350);
>>noise=sqrt(5)*randn(1,10000);
>>rsn=rs+noise;
>>rd=corr(rsn,s1_s2);
>>e=pe(b,rd)
>>e=0.090

For Eb/No = 1.5
No = 0.01 / 1.5 , noise = sqrt(3.33)*randn(1,10000);
>>b=round(rand(1,1000));
>>d=mh(b);
>>rs=lpchannel(d,350);
>>noise=sqrt(3.33)*randn(1,10000);
>>rsn=rs+noise;
>>rd=corr(rsn,s1_s2);
>>e=pe(b,rd)
>>e=0.046

For Eb/No = 2.0
No = 0.01 / 2 , noise = sqrt(2.5)*randn(1,10000);
>>b=round(rand(1,1000));
>>d=mh(b);
>>rs=lpchannel(d,350);
>>noise=sqrt(2.5)*randn(1,10000);
>>rsn=rs+noise;
>>rd=corr(rsn,s1_s2);
>>e=pe(b,rd)
>>e=0.027

For Eb/No = 2.5
No = 0.01 / 2.5, noise = sqrt(2)*randn(1,10000);
>>b=round(rand(1,1000));
>>d=mh(b);
>>rs=lpchannel(d,350);
>>noise=sqrt(2)*randn(1,10000);
>>rsn=rs+noise;
>>rd=corr(rsn,s1_s2);
>>e=pe(b,rd)
>>e=0.019


For Eb/No = 3.0
No =0.01 / 3, noise = sqrt(1.67)*randn(1,10000);
>>b=round(rand(1,1000));
>>d=mh(b);
>>rs=lpchannel(d,350);
>>noise=sqrt(1.67)*randn(1,10000);
>>rsn=rs+noise;
>>rd=corr(rsn,s1_s2);
>>e=pe(b,rd)
>>e=0.012

For Eb/No = 3.5
No =0.01 / 3.5, noise = sqrt(1.43)*randn(1,10000);
>>b=round(rand(1,1000));
>>d=mh(b);
>>rs=lpchannel(d,350);
>>noise=sqrt(1.43)*randn(1,10000);
>>rsn=rs+noise;
>>rd=corr(rsn,s1_s2);
>>e=pe(b,rd)
>>e=0.003

For Eb/No = 4.0
No =0.01 / 4, noise = sqrt(1.25)*randn(1,10000);
>>b=round(rand(1,1000));
>>d=mh(b);
>>rs=lpchannel(d,350);
>>noise=sqrt(1.25)*randn(1,10000);
>>rsn=rs+noise;
>>rd=corr(rsn,s1_s2);
>>e=pe(b,rd)
>>e=0.001

Theoretical Value of Pe

Pe = Q ( )

For Eb/No = 1.0
>> z = Q(sqrt(2))
z =0.0786
For Eb/No = 1.5
>> z = Q(sqrt(4))
z = 0.0416
For Eb/No = 2.0
>> z = Q(sqrt(4))
z = 0.0228
For Eb/No = 2.5
>> z = Q(sqrt(5))
z =0.0127
For Eb/No = 3.0
>> z = Q(sqrt(6))
z = 0.0072
For Eb/No = 3.5
>> z = Q(sqrt(7))
z =0.0041
For Eb/No = 4.0
>> z = Q(sqrt(8))
z =0.0023



Table for Pe(measured) and Pe(Theoretical):
ratio| Pe(measured)| Pe(Theoretical)
1.0 |0.090 | 0.0786
1.5 |0.046 | 0.0416
2.0 |0.027 | 0.0228
2.5 |0.019 | 0.0127
3.0 |0.012 | 0.0072
3.5 |0.003 | 0.0041
4.0 |0.001 | 0.0023




Comments:
The experimental approach indicates that the bit error rate depend on the ratio of interference to desired signal power for the weak interference, irrespective of different interference conditions. The theoretical approach proposes the estimation of bit error rate based on the amplitude probability density function of interference signal components. The difference between theoretical and experimental of probability error is not so much and this is maybe cause by the noise that generated by random bits of data and differences computer will generated difference bits of data.


Appendix:
function [d] = mh(b)
% mh modulation of binary data string b
% Requires global fd: data rate fd, and fs: sampling rate

global fs fd;
d=[];
for k = 1 : length(b)
if (b(k)==1)
d = [d ones(1, fs./(2*fd))];
d = [d -ones(1, fs./(2*fd))];
else
d = [d -ones(1, fs./(2*fd))];
d = [d ones(1, fs./(2*fd))];
end
end

function [op] = lpchannel(s,bw)
% low pass channel with gain 1.0 and bandwidth bw
% input signal is s, requires global fs, fd

global fs fd;
datapts = length(s);
res = fs/datapts;
passband = bw/res;
response = [ones(1,passband), zeros(1,datapts-2.*passband), ones(1,passband)];
ipspec = fft(s);
opspec = ipspec.*response;
op = real(ifft(opspec));

function [rd] = corr(rs, s1_s2)
% correlator receiver matched to s1 - s2
% received waveform is rs

rd = [];
bitlength = length(s1_s2);
for k = 1 : length(rs)/bitlength
store = 0;
for l = 1 : bitlength
op = rs((k-1)*bitlength+l)*s1_s2(l);
store = store + op;
end
if (store>0)
rd = [rd 1];
else
rd = [rd 0];
end
end



function [e] = pe(sd, rd)
% compare sent and received data and calculate Pe]
% sent data is sd, received data is rd

datalength = length(sd);
biterror = 0;
for k = 1:datalength
if (sd(k)~=rd(k))
biterror = biterror + 1;
end
end
e = biterror/datalength;

function r=Q(x)
% Obtaining value of Q function using the built-in erfc function

r = 0.5*erfc(x/sqrt(2));