Computer Control I - Updated9 PDF
Computer Control I - Updated9 PDF
www.jic.edu.sa
Deputyship of Education and Training Affairs وكالة الشؤون التعليمية والتدريب
Table of Contents
1 Compiling and Running C++ Programs 1
4 Looping in C++ 1
6 Functions in C++ 1
10 Arrays in C++.
11 References
EXPERIMENT No. 1
Learning Outcome:
EQUIPMENT REQUIRED:
Introduction:
The basic principles of this section will apply to whatever Programming compiler you choose to use, the stages
are nearly always the same.
2. Compiling it
3. Linking it
4. Executing it
Below are the steps explained in detail for writing C++ Programs using Code::Blocks C++ Compiler.
Codeblocks C++ Environment
Step 1:
Double click the Code::Blocks icon on the desktop or in the task bar to see the following window:
Create your own folder of (c:\ Student Day _ Group) by copying the folder shown below.
Step 2:
Click “create a new project” which appears in blue or from the file then NEW to create a new project. After
clicking a new windows will appears below:
Step 3:
Click console application, then click go, and from the new window click next to choose C++ from the new
window as shown below:
Step 4:
Type a program name for your first project then click next as shown below:
Step 5:
From the new window choose GNU GCC compiler then click finish to see the following window with the name
of your project appears at the top left of the screen:
Step 6:
Expand the project to see the file named “main.cpp”, then double click it to see a ready hello world starting
program which writing only “Hello World” on the console:
Step 7: Editing:
You write a computer program with words and symbols that are understandable to human beings. This is the
editing part of the development cycle. You type the program directly into a window on the screen and save the
resulting text as a separate file. This is often referred to as the source file. The custom is that the text of a
program is stored in a file with the extension of *. cpp
Once you created the new project, you will notice that a folder with the same name as your project name is also
created on the location you specified in the previous steps. In our case, it is on the desktop.
You cannot directly execute the source file. To run on any computer system, the source file must be translated
into binary numbers understandable to the computer's processor. This process produces an intermediate object
file - with the extension .obj, the .obj stands for Object plus some other files that your program need for proper
execution.
Go to Build Tab in Code::Blocks C++ environment and press Build (Ctrl+F9 for compiling and Linking. If
there will be errors in program, it will mention after compiling.
Why is linking necessary? The main reason is that many compiled languages come with library routines, which
can be added to your program. Theses routines are written by the manufacturer of the compiler to perform a
variety of tasks, from input/output to complicated mathematical functions. In the case of C the standard input
and output functions are contained in a library (stdio.h) so even the most basic program will require a library
function. After linking the file, extension is .exe, which are executable files. In most of the compilers compiling
and linking can be done in one-step like Code::Blocks.
Thus, the text editor produces .cpp source files, which go to the compiler, which produces .obj object files,
which go to the linker, which produces .exe executable file. You can then run by clicking Build and Run from
Build tab or just press (F9). If you get an error message, or you find that the program does not work when you
finally run it (at least not in the way you anticipated) you will have to go back to the source file - to make
changes and go through the whole development process again!
Let's use the code given below to makes up a very simple C++ program - one that simply take a value from the
keyboard and print it.
Copy this program into your C++ programming editor and compile it, then Run the program by pressing F9.
Write the result below.
Result:
Enter a value for K!
1. Function main()
Each C++ program consists of one or more functions. The function above, main (), is the only function that is
required to be present in your program. Functions may or may not return a value, although you may write a
function to return anything or nothing. In the above program, the special function main () must return an integer
value . For returning 0 we use the statement return 0.
All statements in C++ are ended with a semicolon. Statements may be grouped together with braces ("{","}").
The braces identify groups of statements that are meant to be executed as a unit. In the above program, we use:
• getch () for getting a character from the keyboard (also used to display check output on monitor screen
before program ends).
• The statement cin>>k is used for reading a statement from the keyboard.
• The statement cout << "Enter a value for K!" << endl is used for printing the string within the double
quotes and then the curser moves to the next line.
• Statement return 0: The return statement causes the main function to finish.
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with
expressions but indications for the compiler's preprocessor. In this case the directive #include <iostream.h> tells
the preprocessor to include the iostream.h standard file. This specific file (iostream.h) includes the declarations
of the basic standard input-output library in C++, and it is included because its functionality is going to be used
later in the program. We generally include following header files in C++ programs.
conio.h input/output. Some of the most commonly used functions of conio.h are clrscr,
getch, getche, kbhit etc.
Most of the mathematical functions are placed, such as abs, labs, sqrt(),div, and
math.h
ldiv
dos.h header file of c language contains functions for handling interrupts,
producing sound, date and time functions like Sleep, sound, nosound, gettime,
dos.h and getdate, Sleep.
windows.h
windows.h is a Windows-specific header file for the C/C++ programming
language which contains declarations for all of the functions in the Windows
Variable in C++ is a portion of memory to store a value. Please note that whenever we are using variables in
C++, we have to declare the variable before its use. For example the statement int k; inform the compiler that
we are going to use a variable named k as an integer.
Variable data
Use of data types
types
Int They can store a whole number value, such as 7 or 1024. They exist in a
variety of sizes, and can be either signed or unsigned, depending on whether
they support negative values or not.
Float They can represent real values, such as 3.14 or 0.01, with different levels of
precision, depending on which of the three floating-point types is used.
Comments are parts of the source code disregarded by the compiler. They simply do nothing. Their purpose is
only to allow the programmer to insert notes or descriptions embedded within the source code.
C++ supports two ways to insert comments:
1 // line comment
2 /* block comment */
The first of them, known as line comment, discards everything from where the pair of slash signs (//) is found
up to the end of that same line. The second one, known as block comment, discards everything between the /*
characters and the first appearance of the */ characters, with the possibility of including more than one line.
The ability to control the flow of your program, letting it make decisions on what code to execute, is valuable to
the programmer. The “if” statement allows you to control if a program enters a section of code or not based on
whether a given condition is true or false.
In C++, the testing of conditions is done with the use of Boolean expressions, which yield values that are either
true or false. The simplest and most common way to construct such an expression is to use the so-called
relational operators.
if ( TRUE )
if ( 5 < 10 )
Here, we are just evaluating the statement, "is five less than ten", to see if it is true or not; with any luck, it is
not! If you want, you can write your own full program including iostream and put this in the main function and
run it to test.
To have more than one statement execute after an “if” statement that evaluates to true, use braces like done with
the body of a function. Anything inside braces is called a compound statement, or a block.
For example:
if ( TRUE ) {
It is recommended always putting braces following if statements. If it is done, remember to put them in when
want more than one statement to be executed, and make the body of the if statement more visually clear.
Else
Sometimes when the condition in an “if” statement evaluates to false, it would be nice to execute some code
instead of the code executed when the statement evaluates to true. The "else" statement effectively says that
whatever code after it (whether a single line or code between brackets) is executed if the “if” statement is
FALSE.
else {
Else If
Another use of else is when there are multiple conditional statements that may all evaluate to true, yet you want
only one if statement's body to execute. You can use an "else if" statement following an if statement and its
body; that way, if the first statement is true, the "else if" will be ignored, but if the if statement is false, it will
then check the condition for the else if statement. If the if statement was true the else statement will not be
checked. It is possible to use numerous else if statements to ensure that only one block of code is executed.
if ( <condition 1> ) {
else {
EXAMPLE
Evaluate expressions:
1) !( 1 || 0 ) ANSWER: 0
EXERCISES:
1) What output you expect from the program given below. Enter the following program in C++ compiler
and verify the output.
Output:
2) Execute the C++ program to find the square root of a number.
Output:
3) Execute the program given below and observe the output.
Output:
4) The following program is used to implement the sign function. Check the output for positive values,
negative values and zero.
Output:
5) Write a program to enter an integer and print if it is greater or less than 100.
Output:
6) Write a program to check a given number is a multiple of 9. Execute the program.( Ref. Project 8 and
8b)
Another Method:
7) Write a program to print the multiple of a given number. Execute the program.(Ref. Project 9)
8) Write a program to three integers and output the smallest and biggest integers using IF & ELSE/IF
statements. Execute the program and show to instructor.(Ref. Project 10)
EXPERIMENT (2)
FAMILIARIZATION OF PC FOR DATA ACQUISITION
AND CONTROL
Learning Outcome:
USB provides a sufficiently fast serial data transfer mechanism for data communications, however it is also
possible to obtain power through the connector and this has further added to the popularity of USB as many
small computer peripherals may be powered via this. From memory and disk drives to other applications such
as small fans and coffee cup warmers, the USB port on computers can be used for a variety of tasks.
USB evolution
Summary of USB Versions and Performance
Details
USB Version
Low speed: 1.5 Mbps
USB 1
Full speed: 12 Mbps
USB 2 'High Speed' rate of 480 Mbps
USB 3 Raw data transfer rates of 4.8 Gbit/s
As a result there are seven USB connector types: Type A, Type B, Mini-A, Mini-B, Micro-A, Micro-B and Micro-
AB. Types A and B have 4 pins within the connector, Mini and Micro A and B connectors have five pins.
The USB Type A plug is the male version of the connector. What might be referred to as the socket, is the female
connector or receptacle, although it is often referred to as the port.
The female connector or receptacle is the type found on the host, e.g. computer, etc., whereas the male will be
seen on items like flash memories, mouse connector, keyboard connector, etc.
There is some color-coding on these connectors in terms of their capabilities. USB 3.0 Type A connectors are
often, but not always, the colored blue. USB 2.0 Type A and USB 1.1 Type A connectors are often black, but this
is not always the case.
A second connector type known as the Type B was often used for smaller peripherals. This had slightly
different pin out arrangement.
The connectors used for USB are designed to enable the power and ground connections to be made first
applying power to the device before the signal lines are connected. This prevents the possibility of the signal
lines being connected first with the possibility of power being drawn through them that could cause damage to
the device.
• Interrupt: The USB protocol defines an interrupt message. This is often used by devices sending small
amounts of data, e.g. mice or keyboards. It is a polled message from the host which has to request specific
data of the remote device
• Bulk: This USB protocol message is used by devices like printers for which much larger amounts of data
are required. In this form of data transfer, variable length blocks of data are sent or requested by the Host. The
maximum length is 64-byte for full speed Devices or 512 bytes for high speed ones. The data integrity is
verified using cyclic redundancy checking, CRC and an acknowledgement is sent. This USB data transfer
mechanism is not used by time critical peripherals because it utilizes bandwidth not used by the other
mechanisms.
• Isochronous: This form of data transfer is used to stream real time data and is used for applications like live
audio channels, etc. It does not use and data checking, as there is not time to resend any data packets with
errors - lost data can be accommodated better than the delays incurred by resending data. Packet sizes can be
up to 1024 bytes.
Interfacing Software:
DAC System can be programmed using any high level programming language such as C++, VB, VC or Turbo
Pascal (Delphi). Earlier it was being programmed in DOS, but with the advances in computer Technologies with
windows taking over DOS. We started developing the windows based controller software which uses the same
instructions used in PLC programming and more visualized as in DCS (Distributed Control System).
To interface the system by any programming language, you must order the DLL file.
PC and Microcontroller software uses assembly to interact with each other. The PC sends commands through the
serial port to the microcontroller and receives data from it. The microcontroller is connected to the final process
which will be controlled.
The PC handshakes the Microcontroller using assembly to communicate properly. While the user uses the high-
level languages or the system controller software to save time and to learn more about latest programming, data
acquisition and control techniques.
NOTE:
All communication routines are contained in a Dynamic Link Library (DLL). You may write custom Windows
(98SE, 2000, Me, XP, Vista) applications in Delphi, Visual Basic, C++ Builder or any other 32-bit Windows
application development tool that supports calls to a DLL.
Copy the (K8055D.dll) file to c:\windows.
• Programmed PIC16C745-IP
One-Time-Programmable (OTP) Devices the availability of OTP devices is especially useful for customers who
need the flexibility for frequent code updates and small volume applications. The OTP devices, packaged in
plastic packages, permit the user to program them once. In addition to the program memory, the
configuration bits must also be programmed.
Programmed PIC16C745-IP
• ULN2803
The ULN2803A device is a high-voltage, high-current
Darlington transistor array. The device consists of eight npn
Darlington pairs that feature high-voltage outputs with
common-cathode clamp diodes for switching inductive loads.
The collector-current rating of each Darlington pair is 500
mA. The Darlington pairs may be connected in parallel for
higher current capability.
ULN2803A
Applications include relay drivers, hammer drivers, lamp drivers, display
drivers (LED and gas discharge), line drivers, and logic buffers. The ULN2803A device has a 2.7-kΩ series
base resistor for each Darlington pair for operation directly with TTL or 5-V CMOS devices.
Description
The USB Experiment Interface Board Kit allows you to get hands on experience developing USB interfaces.
The interface board has 5 digital input channels and 8 digital output channels. In addition, there are two
analogue inputs and two analogue outputs with 8 bit resolution.
The number of inputs/outputs can be further expanded by connecting more (up to a maximum of four) cards to
the PC's USB connectors. All communication routines are contained in a Dynamic Link Library (DLL). You
may write custom Windows (98SE, 2000, Me, XP) applications in Delphi, Visual Basic, C++ Builder or any
other 32-bit Windows application development tool that supports calls to a DLL.
.
USB Interface
Card
o 5 digital inputs (0= ground, 1= open) (on board test buttons provided)
o 2 analog outputs (0 to 5V), output resistance 1K5
o 2 analog inputs with attenuation and amplification option
o PWM 0 to 100% open collector outputs max 100mA / 40V
Note: (on board LED indication)
e- …………………. PWM.
3. Write a program to print the multiple of a given number. Execute the program.(Ref. Proj 11)
Learning Outcome:
• PC Interfacing Card.
• Borland C++ Program.
INTRODUCTION:
o 5 digital inputs (0= ground, 1= open) (on board test buttons provided)
o 2 analog outputs (0 to 5V), output resistance 1K5
o 2 analog inputs with attenuation and amplification option
o PWM 0 to 100% open collector outputs max 100mA / 40V
Note: (on board LED indication)
o general conversion time: 20ms per command
o power supply through USB: Approx.= 70mA
o DLL file (DACS_SYTS.dll) is included
hardware diagram
• Output Schematic Diagram
+5V
Out8
470R
Out7
USB 470R
+5V 1 TX
2
GND 3 RX
Out6
470R
Out5
C1 +5V 470R
30PF
40
12MHz U1
Out4
X1 31 39 470R
VC C
EA/VP P0.0 38
19 P0.1 37
C2 X1 P0.2 36
P0.3 35
18 P0.4 34
30PF
X2 P0.5
Out3
33 470R
P0.6 32
9 P0.7
U2
RESET
P2.0
21 P2.0 P2.01 B1 OC1
18
P2.1
22 P2.1 P2.12 B2 OC2
17
12 23 P2.2 P2.23 B3 16
+5V 13 INT0 P2.2 24 P2.3 P2.34 B4
OC3 15 Out2 470R
14 INT1 P2.3 25 P2.4 P2.45 B5
OC4 14
15 T0 P2.4 26 P2.5 P2.56 B6
OC5 13
T1 P2.5 OC6
P2.6
27 P2.6 P2.67 B7 OC7
12
R28
1 28 P2.7 P2.78 B8 11
2 P1.0 P2.7 9 OC8 10
3 P1.1 GND DCK
Out1
100R C3 17 470R
10uF/16V 4 P1.2 RD 16 ULN2803
OUTPUT
5 P1.3 WR 29
SW1 6 P1.4 PSEN 30
7 P1.5 ALE/P 11 TX
VSS
8 P1.6 TXD 10
P1.7 RXD
PUSH SWITCH RX
20
8.2K
MICRO-CONTROLLER
Sleep Function: Suspends execution for interval (milliseconds). With a call to Sleep, the current program is
suspended from execution for the time specified by the argument milliseconds. While using sleep call we have to
include a file named windows.h. The Sleep function is a built in function and you can have the details of this
function as shown below.
Note
goto statement
A goto statement provides an unconditional jump from the goto to a labeled statement in the same function.
goto label;
..
label: statement;
Function exit( );
The exit( ) function also ends a program before its normal termination. The format is
exit(value);
Using exit(1); returns a value of 1 to the IDE indicating that an error must have occurred. This process is often
used for error trapping.
EXERCISES:
1) Write a C++ program to count in binary showing that on the LEDs for a delay of half second between each count: (
Ref. Project 1h)
2) Write a program to blink LED1 then LED2 and so on, by using:(Ref. Project 2h)
WriteAllDigital();
3) Modify the previous program to blink LEDs in successive means that : blink LED1 then blink LED2 while
clearing LED1 using:(Ref. Project 3h)
WriteAllDigital();
Only.
SetDigitalChannel(k); / ClearDigitalChannel(k);
………………………………………………………………………………………………………………………
……
………………………………………………………………………………………………………………………
……
Which set of functions is used for (Analogue) output, and which set of functions is used for digital output?
………………………………………………………………………………………………………………………
……
6) Write a complete C++ program to read a number from the screen and send it on the LED’s. The program
will ask user whether he wants to repeat. If user press “y”, it will repeat, any other key otherwise will exit
the program Use goto, if/else to execute program.
Review Questions:
1. A Compiler is used for converting High Level Language to __________________ Level Language.
_________________
5. In a C++ program to suspend execution for a period of 1 sec we use the instruction
___________________.
6. The command _________________ can be used for reading a value to a variable m from the keyboard.
7. The command ___________________ can be used for writing the value of a variable m on the monitor.
8. The command _______________________ can be used for displaying your name on the monitor.
Learning Outcome:
3. Understand the use of for loop, while loop and do while loop.
EQUIPMENT REQUIRED:
Introduction:
Loops are used to repeat a block of code. Being able to have your program repeatedly execute a block of code is
one of the most basic but useful tasks in programming -- many programs or websites that produce extremely
complex output (such as a message board) are really only executing a single task many times. (They may be
executing a small number of tasks, but in principle, to produce a list of messages only requires repeating the
operation of reading in some data and displaying it.) Now, think about what this means: a loop lets you write a
very simple statement to produce a significantly greater result simply by repetition.
1. 'for' loop
2. 'while' loop
3. 'do while' loop
The variable initialization allows either declaring a variable and giving it a value or giving a value to an already
existing variable. Second, the condition tells the program that while the conditional expression is true, the loop
should continue to repeat itself. The variable update section is the easiest way for a “for” loop to handle
changing of the variable. It is possible to do things like x++, x = x + 10, or even x = random ( 5 ), and if really
wanted to, could call other functions that do nothing to the variable but still have a useful effect on the code.
Notice that a semicolon separates each of these sections, that is important. Also note that every single one of the
sections may be empty, though the semicolons still have to be there. If the condition is empty, it is evaluated as
true and the loop repeat until something else it stops.
Example: (Ref. Project 4_1)
This program is a very simple example of a for loop. x is set to zero, while x is less than 10 it calls cout<< x <<endl; and it
adds 1 to x until the condition is met. Keep in mind also that the variable is incremented after the code in the loop is run
for the first time.
2. While loops:
The true represents a Boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). It can
be any combination of Boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the
code while x equals five or while v equals 7. Notice that a while loop is the same as a for loop without the
initialization and update sections. However, an empty condition is not legal for a while loop as it is with for
loop.
3. Do while loops :
Do while loops are useful for things that want to loop at least once.
do {
} while (condition);
Notice that the condition is tested at the end of the block instead of the beginning, so the block will be executed
at least once. If the condition is true, we jump back to the beginning of the block and execute it again. A do
while loop is a reversed while loop. A while loop says "Loop while the condition is true, and execute this block
of code", a do while loop says "Execute this block of code, and loop while the condition is true".
EXERCISES
1. Write a program which writes ABC three (3) times using while loop. (Ref. Project 4_4)
Run the program and write the Result.
Output:
2. What will be the output of the following program? (Ref. Project 4_5)
Run the program and write the Result.
Output:
3. What will be the output of the following program : (Ref. Project 4_6)
Run the program and write the Result.
Output:
4. Write a program to print the numbers 5 4 3 2 and 1 in separate lines. (Ref. Project 4_7)
Program:
5. Write a program to generate the following output continuously until the key board is pressed using while (!
kbhit ()). (Ref. Project 4_8)
D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D2 D1 D0
1 Sec
Delay
Gnd
Gnd
Step(2) Step(1)
1 Sec
Delay
Program:
7) Write a complete Borland C++ program to read a number from the screen and flash it on the LED’s three
times. The program will ask user whether he wants to repeat. If user press “y”, it will repeat, any other key
otherwise will exit the program after flashing all led’s three times. Execute the program. Use goto, if/else
and loops to execute program. (Ref. Project 4_9)
Program:
Review Questions:
1. Enter the following program and observe the output. (Ref. Project 4_10)
Output:
1 3 5 7 9
2. What output you are expecting for the following program? (Ref. Project 4_11)
Output:
1. Enter the following program and observe the output? (Ref. Project 4_12)
2.
Output:
3. In the above program change the line int count=1; to int count =3; then what will be the output?
Output:
1. 5. What will the output be of the following program. (Ref. Project 4_13)
Output:
EXPERIMENT (5)
CONNECTED TO A PC
Learning Outcome:
INTRODUCTION:
In many programs, the values of variables need to be tested, and depending on the result, different statements
need to be executed. This facility can be used to select among alternative courses of action.
Instead of using multiple if/else statements C++ also provides a special control structure, switch.
For a variable x the switch(x) statement tests whether x is equal to the constant values x1, x2, x3, etc. and takes
appropriate action. The default option is the action to be taken if the variable does not have any of the values
listed.
Structure
switch( x )
{
case x1:
statements1;
break;
case x2:
statements2;
break;
case x3:
statements3;
break;
default:
statements4;
break;
}
The break statement causes the program to proceed to the first statement after the switch structure. Note that the
switch control structure is different to the others in that braces are not required around multiple statements.
The following example uses the switch statement to produce a simple calculator, which branches depending on
the value of the operator being typed in. The operator is read and stored as a character value (char). The values of
char variables are specified by enclosing them between single quotes. The program is terminated (return -1) if
two numbers are not input or the simple arithmetic operator is not legal. The return value of -1 instead of 0 signals
that an error took place.
EXERCISES:
FAN HEATER
(Channel 1) (Channel 2)
PRESS 2 TO MAKE FAN OFF & HTR OFF OFF(0) OFF (0)
PRESS ANY NUMBER >2 TO MAKE ON(1) ON(1)
BOTH ON
FAN HEATER
SELECTION
(ON/ OFF) (ON/ OFF)
4. Rewrite the program developed in exercise 2 using else-if multiple selection. (Ref. Project 5_3)
Program:
EXPERIMENT (6)
Learning Outcome:
INTRODUCTION TO FUNCTIONS:
A function should have a unique name - By using the name, the program can execute the statements contained
in the function, a process known as calling the function. A function can be called from the main program as well
as within another function.
A function performs a specific task - Task is a discrete job that the program must perform as part of its overall
operation, such as sending a line of text to the printer, sorting an array into numerical order, or calculating a cube
root, etc.
A function is independent - A function can perform its task without interference from or interfering with other
parts of the program. The main program, main() IS also a function..
A function may receive values from the calling program (caller) - Calling program can pass values to function
for processing.
A function may return a value to the calling program - When the program calls a function, the statements it
contains are executed. These statements may pass something back to the calling program.
Let try a simple program example that using a simple user defined function.
Example;
Compile and Run the following program that demonstrates a simple cube function:
Result:
The following statement is calling cube () function, bringing along the value assigned to the input variable.
Answer = cube(input)
Calling function
The function’s return value is cube
assigned to the variable,
answer
When this statement is executed, program jump to the cube () function definition.
After finished the execution, the cube() function returns to the calling code, where in this case, returning and
then assigning the return value, x_cubed to an answer variable.
When a program calls a function, executions passed to the function and then back to the calling program’s code.
Function can be called as many times as needed as shown for function2 () in the above figure, and can be called
in any order if it has been declared (as a prototype) and defined.
A Function Definition is the actual function body, which contains the code that will be executed as shown below
for our previous example:
int cube(int x)
{
// local scope (to this function) variable, only effective in this function 'body'
int x_cubed;
x_cubed = x * x * x;
return x_cubed;
First line of a function definition is called the function header, should be identical to the function prototype,
except without the semicolon.
Function return
type if any
It is easier to write a structured program - Complex programming problems or program are broken into a number
of smaller, simpler tasks. Every task can be assigned to a different programmer and/or function.
It is easier to debug a structured program - If the program has a bug (something that causes it to work improperly),
a structured design makes it easier to isolate the problem to a specific section of code.
Reusability - Repeated tasks or routines can be accomplished using functions. This can overcome the redundancy
of code writing, for same tasks or routines, it can be reused, no need to rewrite the code, or at least only need a
little modification.
Example:
PROGRAM
2. Compile and Run the program given below:
Program example:
Learning Outcome:
EXERCISES:
1. Write a program to read the data from P.B. (byte/decimal from all digital input channels) and compare the
value with a set point of 10. If the value is greater than 10 print “The value ….. is greater than 10” otherwise
print “The Input …….. is less than or equal to 10”. Also flash data on leds. The program runs continuously
till the key board is pressed.
2. Write a program to read the data from the P.B. on different input channels.(Ref. project7_2)
• If it will be from first channel, will blink leds from left to right 8 times,
• if from channel 2, will blink from right to left 8 times
• if from channel 3, will blink two sets (left and right sides) of LEDs alternately 8 times.
• If from channel 4, blink all of 8 LEDs 8 times
• If from channel 5, program terminates
Use functions for each case.
3. Write a program to read the input (Byte / Decimal) from the USB card, the program will print the decimal and
the equivalent binary on specific locations on the screen using gotoxy function.(Ref. project7_3)
Example:
Hint: The positions of decimal and binary values will be as depicted below. Use ReadDigitalChannel () and
ReadAllDigital () with gotoxy.
PROGRAM:
Binary value↑
EXPERIMENT (8)
Learning Outcome:
For electronic applications, we need to switch or control high voltages or high currents. In these cases, we may
use electromagnetic or solid state relays. For example, it can be used to control home appliances using low power
electronic circuits.
An electromagnetic relay is a switch, which is used to switch High Voltage or Current using Low power circuits.
It magnetically isolates low power circuits from high power circuits. It is activated by energizing a electromagnet,
coil wounded on a soft iron core.
A relay should not be directly connected to a microcontroller; it needs a driving circuit due to the following
reasons.
• A microcontroller will not able to supply current required for the proper working of a relay.
• The maximum current that A89C51 microcontroller can source or sink is 15mA while a relay needs about
50 – 100mA current.
• A relay is activated by energizing its coil.
• Microcontroller may stop working by the negative voltages produced in the relay due to its back emf .
To drive a relay, we can use a Transistor to use as an amplifier. When the microcontroller port pin goes high, the
base current flows, which in turn switches the transistor ON. The relay gets enough current through the 12v supply
to switch the secondary circuit ON.
Q1
BC107
POWER +24V R15
1 LED1 680R CON3
2
3 COM 1
NC 2
GND +5V D1
1N4148
NO 3
RELAY
SENSOR2 LED1
10K
680R
USB_POWER
Q1
BC107
SENSOR3 LED1
+5V
10K
USB CARD
680R
+24V
R15
LED1 680R CON3
Q1 COM 1
SENSORS CON
1 SENSOR1 BC107 NC 2
2 SENSOR2 D1 NO 3
3 SENSOR3 1N4148
4 SENSOR4 GND RELAY
5 SENSOR5
6
+5V
SENSOR4 LED1
10K
I1
GND 680R I2
I3
+24V Q1
BC107
I4 220V Pump
I5 Out2
110 Lamp
GND Out1
+5V
SENSOR5 LED1
10K
680R
Q1
BC107
Connection on boards for Relay Interfacing
Interface one switch and relay from application boards to input and output channels of USB card and show
controlling Relay with switch using ReadDigitalChannel () & SetDigitalChannel (). (Ref. project8_1)
EXERCISE 2:
A heater and a fan are connected to the outputs and two switches (Switch 1 & Switch 2 at input channels 1 & 2)
are connected to inputs to control the devices as shown in the table.
I1 I0
TABLE -1
Based on the above table, find the data bytes to turn on or turn off the heater & fan and fill the values in the
table given below.
Heater OFF, 0 0 0 0 0 0
Fan ON
Heater ON, 0 0 0 0 0 0
Fan OFF
Heater OFF, 0 0 0 0 0 0
Fan OFF
Heater ON, 0 0 0 0 0 0
Fan ON
TABLE – II
Draw a flow chart to make output (O1 and O0 ) ON and OFF based on the value of I1 and I0 as shown in the
table –I.
FLOW CHART
PROGRAM :
Write complete C++ program based on the above flow chart using ReadDigitalChannel () and
SetDigitalChannel () commands. (Ref. project8_2)
PROGRAM 2
Also write complete C++ program using ReadAllDigital () and WriteAllDigital () commands. (Ref.
project8_3)
Use below commands to mask all other input channels except Channel 1 & 2.
Int c, v;
c=ReadAllDigital ();
v=c&3;
EXERCISE 3:
Modify the above program to read the data from the input switch and compare the value with a set point of 10. If
the value is greater than 10, blink all LEDs otherwise make all LEDs OFF.
EXERCISE 4:
Modify the above program to read the data from the switch, and then display the value on the LEDs.
EXPERIMENT (9)
Learning Outcome:
EQUIPMENT REQUIRED
INTRODUCTION:
Note: Ask teacher how to use Array and its elements. It will be discussed in detail in next chapter. Here array
with five elements is used: i[5]= { i[0] i[1] i[2] i[3] i[4]}
Y = (I0 | (I1&I2))&(I3)
This interfacing card has the feature to read each input separately, but what would the case be if this feature is
not available. This means that you have to read the full (Byte) and then isolate each bit.
To implement the ladder diagram, first read the 5 binary input from the switch to a variable ‘b’ as shown below.
b= ReadAllDigital();
switchinput(b);
gotoxy(40,13);
printf("%d",i[4]);
gotoxy(44,13);
printf("%d",i[3]);
gotoxy(48,13);
printf("%d",i[2]);
gotoxy(52,13);
printf("%d",i[1]);
gotoxy(56,13);
printf("%d",i[0]);
return 0;
From the above program it is clear that if the LSB is 1 then i[0] will be 1 otherwise i[0] will be 0 because of the
statement: if((val&1)==1) i[0]=1; else i[0]=0;
The same logic is applicable to other bits also.
For example:
if the MSB is 1 then i[4] will be 1 otherwise i[4] will be 0 because of the statement: if((val&16)==16) i[4]=1;
else i[4]=0;
The gotoxy and printf statements are used display the 5 bits of the switch.
EXERCISE 1:
Study and execute the program given below to implement the logic expression represented by the ladder diagram
mentioned in the first page of this experiment. Display the five switch values on the monitor. (Ref project9_1)
Run the program and fill the table given below for various inputs.
Output:
INPUT OUTPUT
I3 I2 I1 I0 O1
EXERCISE 2:
Write the C++ expression for implementing the following ladder diagrams using if else statement.
1.
I1 I2
o 1
2.
I0 I1
o 2
I2
3.
I0
o
3
I1
Draw the ladder diagram represented by the following Borland C++ code. Assume “a” is an array of 5 elements.
SetDigitalChannel(1);
else
ClearDigitalChannel(1);
SetDigitalChannel(1),
else
ClearDigitalChannel(1);
}
3. If ((((a[0]&a[4])|(a[2]&a[1]))&a[3])==1)
{
SetDigitalChannel(1),
else
ClearDigitalChannel(1);
EXERCISE 4:
Write and execute a C++ program to implement the following ladder diagram.
Led
Off
Output
(0→7)
I1 I2 I0
O2
Switch
INPUTS
Open
(0→7) I3 I4 P.C.
Buzzer Buzzer
Off
Fig (4)
Led
On
Output
(0→7)
I1 I2 I0
O2
Switch
Closed INPUTS
Fig (4)
EXPERIMENT (10)
ARRAYS IN C++
Learning Outcome:
INTRODUCTION:
An array is a series of elements of the same type placed in contiguous memory locations that can be individually
That means that, for example, we can store 5 values of type integer in an array without having to declare 5 different
variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the
same type, integer for example, with a unique identifier.
For example, an array to contain 5 integer values of type int called billy could be represented like this:
Where each blank panel represents an element of the array, that in this case are integer values of type int. These
elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length.
Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is:
where type is a valid type (like int, float...), name is a valid identifier and the elements field (which is always
enclosed in square brackets []), specifies how many of these elements the array has to contain.
Therefore, in order to declare an array called billy as the one shown in the above diagram it is as simple as:
The elements field within brackets [] which represents the number of elements the array is going to hold, must be
a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before
execution. In order to create arrays with a variable length dynamic memory is needed, which is explained later in
these tutorials.
When we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing
the values in braces { }. For example:
int billy [5] = { 16, 2, 77, 40, 12071 };
The amount of values between braces { } must not be larger than the number of elements that we declare for the
array between square brackets [ ]. For example, in the example of array billy we have declared that it has 5
elements and in the list of initial values within braces { } we have specified 5 values, one for each element.
When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets
empty [ ]. In this case, the compiler will assume a size for the array that matches the number of values included
between braces { }:
After this declaration, array billy would be 5 ints long, since we have provided 5 initialization values.
In any point of a program in which an array is visible, we can access the value of any of its elements individually
as if it was a normal variable, thus being able to both read and modify its value. The format is as simple as:
name[index]
Following the previous examples in which billy had 5 elements and each of those elements was of type int, the
name which we can use to refer to each element is the following:
For example, to store the value 75 in the third element of billy, we could write the following statement:
billy[2] = 75;
and, for example, to pass the value of the third element of billy to a variable called a, we could write:
a = billy[2];
Therefore, the expression billy[2] is for all purposes like a variable of type int.
billy[0] = a;
billy[a] = 75;
b = billy [a+2];
EXERCISE 1:
Study the program given below. What output you expect from the program.
Write and execute a C++ program to read 10 integer values from the keyboard and print their Sum and Average.
(Ref project10_2):
EXERCISE 3:
1. Read the values for m (the slope) and b (the offset) from the keyboard.
2. Create an array X containing values between -10 and +10.
3. For each element in X, calculate Y using the formula Y = mX+ b.
Study the program and observe the output. (Ref. project10_3)
Output:
EXERCISE 4:
Write and execute a C++ program to read 10 integer values from the keyboard and print the biggest number.
(Ref. project10_4)
EXERCISE 5:
Write and execute a C++ program that activates the eight LEDs on the DAQ board according to the pattern in the
array x: (Ref. project10_5)
x = {1,1,0,0,1,0,1,0}
Alternatively, we can program it without the need to convert from binary to decimal using SetDigitalChannel ()
and ClearDigitalChannel (): (Ref. project10_6)
EXERCISES:
1. Write a C++ program for the user to enter 10 numbers and put them into an array, and then sort the
numbers in ascending order putting them into a new array.
2. Write a C++ program for the user to enter 10 numbers and put them into an array, and then sort the
numbers in ascending order putting them into a new array.
3. Write a C++ program for the user to enter 10 numbers and put them into an array, and then swap the first
five numbers with the last five numbers, putting them into a new array.
11.References
Mitchell, J.A., Thomson, M., & Coyne, R.P. (2017). A guide to citation. London, England: My Publisher
Williams, S.T. (Ed.). (2015). Referencing: A guide to citation rules (3rd ed.). New York, NY: My
Publisher
In the following example, B.N. Troy is the author of the chapter and S.T. Williams is the editor.
Troy, B.N. (2015). APA citation rules. In S.T, Williams (Ed.). A guide to citation rules (2nd ed., pp. 50-
95). New York, NY: Publishers.
Mitchell, J.A. (2017). Citation: Why is it so important? Mendeley Journal, 67(2), 81-95