KEMBAR78
Computer Control I - Updated9 PDF | PDF | Usb | Electrical Connector
0% found this document useful (0 votes)
39 views121 pages

Computer Control I - Updated9 PDF

Uploaded by

48xxsbbpv8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views121 pages

Computer Control I - Updated9 PDF

Uploaded by

48xxsbbpv8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

Deputyship of Education and Training Affairs ‫وكالة الشؤون التعليمية والتدريب‬

The Department of Electrical and Electronic


Engineering Technology
Instrumentation and Control Engineering Technology
(ICET)

Computer Control I - (EEE 234)


Laboratory Manual
Deputyship of Education and Training Affairs ‫وكالة الشؤون التعليمية والتدريب‬

Copyright © 2021 by the Department of Electrical and Electronic Engineering Technology


(EEET). All rights reserved. This work may not be reproduced or used without the permission
from Jubail Industrial College represented by EEET.

Jubail Industrial College


P.O. Box 10099
Jubail 31961
Kingdom of Saudi Arabia

www.jic.edu.sa
Deputyship of Education and Training Affairs ‫وكالة الشؤون التعليمية والتدريب‬

Table of Contents
1 Compiling and Running C++ Programs 1

2 Familiarization of PC for Data Acquisition and Control 1

3 Controlling LED’s With Source Current from the Parallel Port 1

4 Looping in C++ 1

5 Controlling Devices Connected to a PC 1

6 Functions in C++ 1

7 Reading the Status of Switches Connected to a PC 1

8 Controlling Devices through Switches Connected to a PC 1

9 Converting Simple Ladder Diagrams to C++ Programs 1

10 Arrays in C++.

11 References
EXPERIMENT No. 1

COMPILLING AND RUNNING C++ PROGRAMS

Learning Outcome:

After completing this experiment, the student should be able to:

1- Understand the benefits of using compilers.

2- Understand simple programs in C++. Checking errors and run it

3- Understand simple programs in C++. Checking errors and run it.

4- Observe results on computer screen for ( C++ Console ).

5- Difference between Source Code and Execution file.

6- Understand use of Conditional statements (if/else) in C++

EQUIPMENT REQUIRED:

1. A PC with Code::Blocks ide installed in it.

Introduction:

The basic principles of this section will apply to whatever Programming compiler you choose to use, the stages
are nearly always the same.

The Edit-Compile-Link-Execute Process:

Developing a program in a compiled language requires at least four steps:

1. Editing (or writing) the program

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.

Step 8: Compiling and Linking:

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.

Step 9: Check Output Executable files:

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!

Outline of a Simple C++ Program;


Test Program 1

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!

You entered a value for K =

Components of C++ Program

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.

2. Writing statements in C++

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:

• system("cls") for clearing the screen,

• 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.

3. Header files in C++

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.

Header File Descriptions and uses


iostream For input and output functions cin & cout
stdio.h uses what are called streams to operate with physical devices such as
keyboards, printers, terminals or with any other type of files supported by the
system.

conio.h header used in c programming contains functions for console

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

4. Variables and its data types in C++

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.

char They can represent a single character, such as 'A' or '$'.


Bool The Boolean type, known as bool, can only represent one of two states, true or
false.
5. Comments :

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.

Conditional statements: If else statements in C++

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.

Boolean expressions and relational operators:

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.

x==y true if x is equal to y (5 == 5 is TRUE)


x!=y true if x is not equal to y (5 != 4 is TRUE)
x>y true if x is greater than y (5 > 4 is TRUE)
x>=y true if x is greater than or equal to y ( 4 >= 4 is TRUE)
x<y true if x is less then y (4 < 5 is TRUE)
x<=y true if x is less than or equal to y (3 <= 4 is TRUE)
If you need to test more than one relational expression at a time, it is possible to combine the relational
expressions using the logical operators.

operator C++ symbol example


AND && expression1 && expression2
OR || expression1 || expression2
NOT ! !expression
Basic If Statement Syntax

The structure of an if statement is as follows:

if ( TRUE )

Execute the next statement

Here is a simple example that shows the syntax:

if ( 5 < 10 )

cout<<"Five is now less than ten, that's a big surprise";

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.

More than one statements with “if” statement - True

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 ) {

Execute all statements inside the braces

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.

It can look like this:


if ( TRUE ) {

// Execute these statements if TRUE

else {

// Execute these statements if FALSE

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> ) {

// Execute these statements if <condition 1> is TRUE

else if ( < condition 2> ) {

// Execute these statements if < condition 2> is TRUE and

// <condition 1> is FALSE

else {

// Execute these statements if all conditions FALSE

Let's look at a simple program to try out.

EXAMPLE
Evaluate expressions:

1) !( 1 || 0 ) ANSWER: 0

2) !( 1 || 1 && 0 ) ANSWER: 0 (AND is evaluated before OR)

3) !( ( 1 || 0 ) && 0 ) ANSWER: 1 (Parenthesis are useful)

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)

NOTE: The Result should be as follow.


Solution:

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:

After completing this experiment, the student should be able to:


1. Serial and USB ports.
2. USB Interfacing Card / Schematic & Mask Diagram.
3. USB Interfacing Card / IC's.
4. USB Interfacing Card Drivers and configuration.
EQUIPMENT REQUIRED:
• USB INTERFACING CARD
• INTERFACING CARD DRIVERS & SOFTWARE
USB: Universal Serial Bus

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

USB connector types


As the concept of USB has developed, so too have the connectors. Data transfer speeds have risen, and the
requirement for smaller connectors has increased.

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.

1. USB type A connector outlines


A USB cable can have one of two forms of connector in the original system. These are designated the "A" and
"B" connectors. The connections to the connectors are given below:

Type A USB connector pin out

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.

2. USB type B connector outlines

A second connector type known as the Type B was often used for smaller peripherals. This had slightly
different pin out arrangement.

Type B USB connector pin out

USB Type A & B pin outs / connections


The basic USB pin outs for the connectors are given in the table below. Apart from the USB connector pin outs,
the table also gives the wire colors used within the cables.

Type A & B USB connector pin assignments


Pin Wire color Signal Names
Vbus
1 Red
4.75 - 5.25 V
2 White Data -
3 Green Data +
4 Black Ground
Shell Drain wire Shield

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.

USB Signaling and data transfer basics


There are four basic types of data transaction that can be made within USB.
• Control: This type of data transaction within the overall USB protocol is used by the host to send commands
or query parameters. The packet lengths are defined within the protocol as 8 bytes for Low speed, 8-64 bytes
for Full, and 64 bytes for High Speed devices.

• 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.

DACS (Data Acquisition Computer Control System)


is a general purpose PC control system covers the important information’s and instructions used and the latest
technological system.

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.

USB Interface Card Schematic Diagram


USB Interface Card Card Mask Diagram
USB Interface Card IC's

• 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.

USB Interface Card

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

USB Interfacing Card Features:

o Diagnostic / Test Software:


o separate output / input test
o clear all / set all function
o analog output set sliders
o analog input bar-graph indication

Minimum System Requirements:

o Pentium class CPU


o USB1.0 or higher connection
o Windows 98SE or higher (Win NT excluded)
o CD ROM player and mouse
USB Interfacing Specifications:

o 8 digital open collector output switches (max. 50V/100mA)

Note: (on board LED indication provided)

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 (K8055D.dll) is included
Review Questions:

1. USB stand for _________________________________________________.

2. The USB interfacing Card contains:

a- ………………… Digital Output.

b- ………………… Digital input.

c- …………………. Analogue Input.

d- …………………. Analogue output.

e- …………………. PWM.

3. Write a program to print the multiple of a given number. Execute the program.(Ref. Proj 11)

NOTE: The Result should be as follow.


Solution:
EXPERIMENT (3)

CONTROLLING OUTPUT LED’s USING THE

USB INTERFACING CARD

Learning Outcome:

After completing this experiment, the student should be able to:

1. Understand the output block diagram of the USB Card.


2. Understanding the DLL and calling DLL functions.
3. Using the function SetDigitalChannel () to activate output LED’s.
4. Using the function ClearDigitalChannel () to deactivate output LED’s.
5. Using the function WriteAllDigital () to activate output LED’s.
6. Using the function ClearAllDigital () to deactivate output LED’s.
7. How to build up a delay using for loops and Sleep function.
8. Exercising the output programming using Borland C++.
EQUIPMENT REQUIRED:

• PC Interfacing Card.
• Borland C++ Program.

INTRODUCTION:

The USB Interfacing Specifications:

o 8 digital open collector output switches (max. 50V/100mA)


Note (on board LED indication provided)

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.

void Sleep (unsigned milliseconds)

for(long int i=1; i<=2000000000;i++)

Note

Use Sleep (500) to generate 0.5 second and so on.

goto statement

A goto statement provides an unconditional jump from the goto to a labeled statement in the same function.

The syntax of a goto statement in C++ is:

goto label;

..

label: statement;

Function exit( );

The exit( ) function also ends a program before its normal termination. The format is

exit(value);

where value is an integer variable or value. Header File: cstdlib.


Exit function ends the program. The Exit Code is returned to the operating system, similar to returning a value to
int main.

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.

Example: (Ref. Proj 12)

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.

4) Rewrite program in 2) using ( Ref. Project 4h)

SetDigitalChannel(k); / ClearDigitalChannel(k);

5) Rewrite program in 3) using :( Ref. Project 5h)

SetDigitalChannel (k); / ClearDigitalChannel (k);


What are your observations about the two programs?

………………………………………………………………………………………………………………………
……

What is the different between the two sets of functions?

………………………………………………………………………………………………………………………
……

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.

2. _________________Level language consists of only 1 and 0.

3. The DLL file contains _________________ and the output function is

_________________

4. Sleep (200); suspends execution for a period = ____________________Sec.

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.

9. The USB Port contains _____________________ lines.

10. system (“cls”) is used for ___________________.


EXPERIMENT (4)

LOOPING IN Borland C++

Learning Outcome:

After completing this experiment, the student should be able to:

1. Understand the use of LOOPS in C++ programs.

2. Write simple C++ programs using LOOPS.

3. Understand the use of for loop, while loop and do while loop.

4. Compile and Run C++ Program.

5. To debug simple C++ Program containing loops..

EQUIPMENT REQUIRED:

• A PC with Code::Blocks ide installed in it.

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.

Loops in C++ are mainly of three types:

1. 'for' loop
2. 'while' loop
3. 'do while' loop

1. FOR - for loops are the most useful type.

The syntax for a for loop is

for ( variable initialization; condition; variable update ) {

Code to execute while the condition is true

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:

While loops are very simple.

The basic structure is:


while (condition) {Code to execute while the condition is true}

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.

Example: (Ref. Project 4_2)


This was another simple example, but it is longer than the above FOR loop. The easiest way to think of the loop
is that when it reaches the brace at the end it jumps back up to the beginning of the loop, which checks the
condition again and decides whether to repeat the block another time, or stop and move to the next statement
after the block.

3. Do while loops :

Do while loops are useful for things that want to loop at least once.

The structure is:

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".

Example: (Ref. Project 4_3)


Keep in mind that you must include a trailing semi-colon after the while in the above example. A common error
is to forget that a do while loop must be terminated with a semicolon (the other loops should not be terminated
with a semicolon, adding to the confusion). Notice that this loop will executeonce, because it automatically
executes before checking the condition.

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)

D5, D1 & D0 ON D5 & D6 ON

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)

CONTROLLING SENSORS AND ACTUATORS

CONNECTED TO A PC
Learning Outcome:

After completing this experiment, the student should be able to:

1. To understand and use different type of selection statements.


2. To understand how to use selection statements for making menu driven programs.
3. Use selection statements in control applications.
4. Understand how to use digital signals for controlling devices connected to a PC.
5. Understand how to interface the electrical devices to a USB.
EQUIPMENT REQUIRED:

• A PC with Code::Blocks ide installed in it.


• USB Interfacing Card.

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.

SWITCH selection control statement:

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:

1. Compile and run the following program: (Ref. Project 5_1)


2. A heater and a fan are to be controlled through PC and they are controlled from the keyboard using the
following Menu. Write a C++ program using switch case statement to generate ON/OFF signals to control
the devices connected to channel 1(Bit 0) (Control circuit for Heater) and channel 2(Bit 1) (Control circuit for
Fan) Of the USB DAQ.
MENU ( USB DAQ OUTPUTS )

FAN HEATER

(Channel 1) (Channel 2)

PRESS 0 TO MAKE FAN OFF & HTR ON OFF(0) ON (1)

PRESS 1 TO MAKE FAN ON & HTR OFF ON (1) OFF(0)

PRESS 2 TO MAKE FAN OFF & HTR OFF OFF(0) OFF (0)
PRESS ANY NUMBER >2 TO MAKE ON(1) ON(1)
BOTH ON

3. Program: (Ref. Project 5_2)

Write program using WriteAllDigital () and ClearAllDigital ()]


Run the program and complete the following table.

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)

CONTROLLING INPUTS USING THE

USB INTERFACING CARD & FUNCTIONS USING Borland C++

Learning Outcome:

After completing this experiment, the student should be able to:

1. To understand and use functions in C++.


2. To understand structured programming.
3. Using the function ReadDigitalChannel() to read digital inputs (Bit).
4. Using the function ReadAllDigital() to read all digital inputs (Byte).
5. Use functions in data acquisition and control applications.
6. Understand the mechanism of passing values to functions.
7. Appreciate the use of functions in the development of large programs.
EQUIPMENT REQUIRED:

• A PC with Code::Blocks ide installed in it.


• USB Interfacing Card

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.

How a Function Works


A C / C++ program does not execute the statements in a function until the function is called by another part of
the program. When C / C++ function is called, the program can send information to the function in the form of
one or more what is called arguments although it is not a mandatory. Argument is a program data needed by the
function to perform its task. When the function finished its processing, program returns to the same location that
called the function.

The following figure illustrates a function call.


Arrow Means

→ Calling function with data (argument) if any

← Return to the next statement or execution with data if any

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;

// do the volume calculation

x_cubed = x * x * x;

// return a result to caller

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

Type function_name ( parameter1, parameter2,. . . .

Function’s name Function’s name

General function form of function header


Although the argument variable names (x in this case) were optional in the prototype, they must be included in
the function header. Function body, containing the statements, which the function will perform, should begin with
an opening brace and end with a closing brace. If the function returns data type is anything other than void (nothing
to be returned), a return statement should be included, returning a value matching the return data type (int in this
case).
Structured Programming:
Functions and structured programming are closely related. Structured programming definition: In which
individual program tasks are performed by independent sections of program code. Normally, the reasons for using
structured programming may be:

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:

Write, Compile and Run the Program given below:

Please note the following points regarding the program given.

1. Difference between arguments and Parameters.


2. Use of Predefined functions in the C library.
3. Each time a function is called, the different arguments are passed to the function’s parameter.
4. The first function call is as shown below:
result=C2F(temperature) ----------→ float C2F(float x)
The, second function call is as shown below:

result=F2C(temperature) ----------→ float F2C(float x)


EXERCISES:
1. Write a program that flashes Led three times according to a entered number. The program keeps asking you if you
like to repeat before ending. If you type “y” it will repeat, if you type any other character, it will stop after flashing all
Leds three times. Use functions.

PROGRAM
2. Compile and Run the program given below:
Program example:

// demonstrate the difference between arguments and parameters

// using predefined functions in the C standard library


Output:
EXPERIMENT (7)

CONTROLLING THE OUTPUT ACTUATORS CONNECTED TO A PC

Learning Outcome:

After completing this experiment, the student should be able to:

1. To understand the programming techniques for processing digital signals.


2. To understand the method used for displaying the processed data on the display.
EQUIPMENT REQUIRED:

• A PC with Borland C++ installed in it.


• USB Interfacing Card.

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:

(Decimal Value = 9 , Equivalent Binary Value = 0 1 0 0 1)

Hint: The positions of decimal and binary values will be as depicted below. Use ReadDigitalChannel () and
ReadAllDigital () with gotoxy.

PROGRAM:

Column position on monitor


Row 5 12 14 16 18 20
position
10 Decimal Equivalent D4 D3 D2 D1 D0

Binary value↑
EXPERIMENT (8)

CONTROLLING INPUT SENSORS CONNECTED TO A PC

Learning Outcome:

After completing this experiment, the student should be able to:

1. To understand how to make decisions based on the switch input.


2. To understand how to program the PC to control devices based on the sensors input.
3. To understand the interfacing techniques of sensors & output devices.
EQUIPMENT REQUIRED

• A PC with Borland C++ installed in it.


• USB Interfacing Card.

HIGH VOLT INTERFACING:

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.

Transistor Driver circuit for relays


ULN2003 IC Driver circuit for relays
( HIGH VOLT INTERFACING )
Power_2 +5V
Power_1
SENSOR1 LED1
10K
680R +24V

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

Connections for Opto-coupler Interfacing


EXERCISE 1:

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.

INPUT CONDITIONS REQUIRED OUTPUTS

Switch 2 Switch 1 FAN HEATER

/Channel 2 /Channel 1 on PO1 on PO0

I1 I0

Off ( 0) Off ( 0 ) Off (0) On (1)

Off (0) On (1) On (1) Off (0)

On(1) Off (0 ) Off (0) Off (0)


On(1) On(1) On(1) On(1)

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.

Output (bit) Data in


Required
Decimal
condition O7 O6 O5 O4 O3 O2 O1 O0 system

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)

CONVERTING SIMPLE LADDER DIAGRAMS TO


Borland C++ PROGRAMS

Learning Outcome:

After completing this experiment, the student should be able to:

1. To create programs to implement a given ladder diagram.

2. To understand how to write the switch input values to an array.

3. To understand how to control the word using PC’s.

EQUIPMENT REQUIRED

• A PC with Borland C++ installed in it.


• USB Interfacing Card.

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]}

Consider the ladder diagram you learnt in PLC course.


Then the output can be written as

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();

Pass the value of (b) to a user defined function to do the following.

1. Isolate each bit of b.


2. Store each bit of b in different elements of an array.
3. Display the bit values at convenient location of the monitor.
Let the function name be switchinput(int val). Then this function can be called as shown below.

switchinput(b);

The switchinput function can be written as shown below:

switchinput (int val)


{

if((val&1)==1) i[0]=1; else i[0]=0;

if((val&2)==2) i[1]=1; else i[1]=0;

if((val&4)==4) i[2]=1; else i[2]=0;

if((val&8)==8) i[3]=1; else i[3]=0;

if((val&16)==16) i[4]=1; else i[4]=0;

//Printing the input value on monitor screen.

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

Answer for Exercise 2:


EXERCISE 3:

Draw the ladder diagram represented by the following Borland C++ code. Assume “a” is an array of 5 elements.

1. If (( ( a[0] | ( a[1] & a[3] ) )&(a[2]) )==1)


{

SetDigitalChannel(1);

else

ClearDigitalChannel(1);

2. If (( ( a[4] | ( a[3] & a[2] ) )&(a[1]) )==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

(0→7) I3 I4 Buzzer P.C.


Buzzer
On

Fig (4)
EXPERIMENT (10)

ARRAYS IN C++

Learning Outcome:

After completing this experiment, the student should be able to:

1. To understand how to create arrays.


2. To understand how to program for reading data to array elements.
3. To understand how to develop program for manipulating data using arrays.
EQUIPMENT REQUIRED

• A PC with Borland C++ installed in it.


• USB Interfacing Card.

INTRODUCTION:

An array is a series of elements of the same type placed in contiguous memory locations that can be individually

referenced by adding an index to a unique identifier.

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:

type name [elements];

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:

int billy [5];

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.

Initializing and accessing the array elements.

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 };

This declaration would have created an array like this:

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 { }:

int billy [] = { 16, 2, 77, 40, 12071 };

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.

Some other valid operations with arrays:

billy[0] = a;

billy[a] = 75;

b = billy [a+2];
EXERCISE 1:

Study the program given below. What output you expect from the program.

Execute the program and observe the output. (Ref. project10_1)


EXERCISE 2:

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:

The following program is used to:

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

Please, follow one referencing style (for example APA).

Book referencing examples:

Mitchell, J.A., Thomson, M., & Coyne, R.P. (2017). A guide to citation. London, England: My Publisher

Edited book example:

Williams, S.T. (Ed.). (2015). Referencing: A guide to citation rules (3rd ed.). New York, NY: My
Publisher

Edited book chapter example:

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.

Journal Article Examples:

Mitchell, J.A. (2017). Citation: Why is it so important? Mendeley Journal, 67(2), 81-95

You might also like