CMP201- Programming Expertise in C Reference Book (1)
CMP201- Programming Expertise in C Reference Book (1)
C Programming Introduction
In this lecture you will understand:
Why one should learn C
What is meant by constants, variables and keywords
Rules for building variables and constants
How many keywords are there in C
What happens in memory when a variable is created
2 C Programming Introduction Programming Expertise In C
Why C?
There are at least four good reasons to learn C:
(a) C is simple.
(b) C is easy to understand since it is extremely small and contains only 32 keywords.
(c) Programs written in C execute faster than the programs written in most other languages.
(d) Languages like C++, C# or Java use C syntax.
(e) Operating System like Unix, Linux or Windows are written in C.
(f) Moreover, gaming frameworks and even mobile devices use C.
(g) Communication with the hardware is easily possible using C, which was earlier possible only
using assembly language.
Where C Stands
Languages can be categorized as Low-Level Languages (LLL) and High-Level Languages (HLL).
The LLLs (Assembly Languages) offer better machine efficiency since they understand the machine
better and are able to exploit its capabilities more effectively. Also, these languages have all the
features and instructions to interact with the hardware. The HLLs offer better programming efficiency
since they have been designed to make programming easier. Moreover, all high-level languages don’t
have facilities and instructions to interact with the hardware. C is a good mix of both. Being a high-
level language it offers better efficiency as well as has all the features to interact with the hardware.
Hence, C is also called a Middle-Level Language.
In The Beginning…
Learning C language is similar to learning English language. Instead of words and numbers of
English, in C we build constants, variables and keywords. These in turn are used to form a
statement or an instruction. A group of such instructions forms a program.
C Constants
There are two types of constants viz. Primary and Secondary. Each of them further contains several
types as shown in the slide. In this lecture we would focus our attention only on Primary constants.
Programming Expertise In C C Programming Introduction 3
Integer Constants
Integer constants are numbers without decimal point or fractional part in them. While building an
integer constant the rules shown in the slide should be followed. The valid range of integer constants
is –32768 to 32768. If we are to program an application which needs to tackle constants
bigger/smaller than the range offered by integer constant we should use real constants.
Real Constants
The real constant must contain a decimal point. It can be positive or negative. No comma or spaces
are allowed and the valid range is -3.4 x 1038 to +3.4 x 1038.
Character Constants
Character constants are the constants enclosed within single quotes pointed to left. Character
constants are single character wide. More than one character is not allowed within single quotes.
C Variables
All computer languages follow one cardinal rule: A particular type of constant can be stored in the
same type of variable. Hence those many types of variables exist, as the number of types of constants.
Variables
Since variables are containers that hold constants in them the number of types of variables must be
the same as the number of types of constants.
It is necessary to identify the types of variables so that the computer can decide what value and
operations can be allowed on that variable.
C Keywords
In C there are 32 keywords. Keywords are words having predefined meaning in the language. For
example, when we say int i it means that we are trying to define i to be an integer type. In this
statement, int is a keyword and its meaning stands predefined. The terms Keywords and Reserved
words are used interchangeably. int, char and float are keywords. The keywords should never be
used as variable names. So, the statement int float is invalid.
However, integer, character and real are not keywords. Hence they cannot be used to declare variable
types and can be used as variable names.
Programming Expertise In C Hardware Interaction – II 205
Hardware Interaction - II
In this lecture you will understand:
Serial communication using null modem
How parallel port works
How to communicate with parallel port programmatically
How speaker works
How to play tunes using ports
206 Hardware Interaction – II Programming Expertise In C
Serial Communication
A common use of the “serial-port” device is to connect two computers together for transfer of data. In
this case pins other than transmit or receive are looped back (connected) to the other pins. Looping
back is something like fooling the computer to believe that it is actually connected to some serial
device. The slide shows the pins of connector for a null modem cable, which uses loop back
technique.
The “serial-port” device is commonly used by software developers to connect two computers for
testing new software. One computer runs the software while the other records the information sent by
the software. This method is often known as debugging, it helps the developers in finding errors in
their program. The cable used for connecting the two computers is known as Null Modem cable,
Debug-cable, COM port to COM port cable or simply Serial cable.
The communication is called serial communication because only 1 bit gets transmitted at a time. The
looping back of pins makes the computer think that a modem (null-modem) is actually connected to
it. All COM ports are serial - some are 9 pin some are 25 pin male connectors. All parallel ports are
25-pin female connectors.
Server
In the program given in the slide, first we have called bioscom( ) function. The first parameter passed
to this function specifies port number. The value 0 used here, specifies the communication port
COM1. The meaning of the values used in place of second parameter is given in the slide. The second
parameter specifies the port number where operation is to be performed. The last parameter is used to
check whether data has been transmitted in an error free manner. We are not using parity hence we
have specified a value of 0. In the first call to bioscom( ), we have use 0x80 i.e. 1200 baud.
Then a while loop runs, in which we have again called bioscom( ) function to know the status. We
have checked whether status retrieved indicates data is ready at communication port. If it is then we
have called bioscom( ) twice, one to receive data and the other to send character ch (received through
getche( ) ). The loop continues till we have not pressed ESC key.
Client
In the program given in the slide, we have called bioscom( ) with same values as discussed in the
earlier slide. Then a while loop runs till a key is not hit. In this loop, we have called bioscom( ) to
send a data. The same function is called again to know the status of communication port. If the status
is ready, then we have called bioscom( ) again to receive data. Before collecting the data received in
ch we have anded (using bitwise & operator) it with 0x007F. This is because, when we send a
character to bioscom( ) it splits it into bits, adds a stop bit and then sends it bit by bit. Data read is 16
bit. Of this, lower 7 bits contain the actual data. Rest of the bits contains command completion flags
like time-out, bit lost etc.
Lastly, the data received is displayed. Client continues receive values till a key is not hit on the client.
Once hit client terminates so server-sending values has no meaning. Hence server loop (i.e. in the
server program discussed in earlier slide) is terminated by hitting Esc key.
Each parallel port device consists of three device registers—data, status and control. These registers
are mapped in the I/O address space and hence have port addresses. The port addresses for the three
registers are in sequential order. That is, if the data register is at address 0x408, the corresponding
status register is at 0x408 + 1 and the control register at 0x408 + 2.
The parallel port device registers are mapped to a 25 pin female connector that is present on the
backside of the CPU box. The 25 pins of the connector are mapped onto the three device registers.
The pins are the device register’s interface with the outside world.
The ground pins (18 to 25) remain at a constant voltage of 0 volts. Ground pins provide the zero
reference voltage for the connected peripherals. That is, these pins are used by the computer and the
peripheral device to agree on a common 0 volts signal. All communication between the computer and
peripheral device will be with respect to this 0 volts signal.
Data pins (2 to 9) are true logic pins. The data port pins are the actual data carriers of the parallel port
device. Whatever data we wish to send to the peripheral device is transmitted via these pins.
Program
Let us now put our knowledge of parallel port programming to work with a simple Seven Segment
(7-segment) display. Here we would connect the 7-segment display to the PC parallel port and then
display numbers from 0 – 9 on it using a loop.
The 7-Segment Display has totally 10 pins—5 at the top and 5 at the bottom. Of the 5 pins on either
end the center pin is the common ground. The balance 8 pins can be connected to the 8 data lines
from the parallel port connector through 8 resistances each of 560 Ohms as shown in figure given in
the slide. The ground pins of the 7-segment display are connected to pin number 25.
Each bit of the data register is responsible for glowing one segment of the display. With this
information available at our disposal we can easily manage to display different digits on a 7-segment
display.
The program given in the slide shows how this can be achieved. In this program we have first
constructed an array of characters. The array contains values for forming the digit by glowing suitable
208 Hardware Interaction – II Programming Expertise In C
segments of the 7-segment display. These values are obtained by performing bitwise OR operations
on individual segment values.
Slide Number 7
The program then uses a while loop within which we have called the standard library function
outportb( ). To outportb( ) we have passed two parameters, first one is the port address of the data
register and the second one is the actual value we want to write to the port. The condition if ( i == 10
) is used to reset the array index once it reaches 10.
On execution the program will display digits from 0 to 9 in a cyclic manner, with each digit being
displayed for exactly 1 second (1000 milliseconds).
Working of Speaker
The speaker is made to vibrate by the electrical impulses sent to it by the PC. These vibrations set the
air particles around the vibrating source in motion. As the particles bump into one another a sound is
produced. The figure given in the slide shows the working of a speaker.
The cylindrical bar (surrounded by the white coil) is actually a soft iron core. When the coil around
the core receives a pulse the soft iron core temporarily becomes a magnet. This temporary magnet
interacts with the permanent magnet. This interaction causes the diaphragm to be pushed forward.
When the pulse dies the magnetism is lost and the diaphragm returns back to its original position.
When this happens frequently we hear a sound. There are two parameters that govern the sound that
the speaker produces-frequency of the sound and its duration.
Speaker Operation
The sound frequency is controlled by the 8253 programmable Timer chip, whereas the duration has to
be controlled programmatically.
The timer chip produces signals at a default frequency of 1.19318 MHz (119318 x 10 6 cycles per
second) through a clock present inside the timer chip. This frequency can be changed
programmatically.
The timer chip provides three independent channels. Through these channels signals can be sent to
separate devices. The speaker uses the signal coming from channel number 2. The timer chip can
operate in six different modes, each mode deciding the nature of the signal produced. For example,
while working in mode number 3 it always generates a square wave output.
We can communicate with the timer chip through any of the four I/O ports with addresses 64 through
67, which we shall discuss in next slide.
Speaker Circuit
This slide explains the working model of the speaker circuit.
CS, OUT2, CLOCK shown in the yellow block are the pins present on the chip. CS stands for Chip
Select. Its purpose is to enable/disable the chip.
There are 3 channels in 8253—OUT1, OUT2 and OUT3. The channel is a fancy term for number of
inputs or outputs. The OUT2 channel indicates that we are using second channel. Each channel can
independently drive a device.
The Pulse is sent through channel2 to OUT2 and is sent to the speaker. To manage time interval PIT
needs a clock frequency. The quartz crystal generates a base frequency of 1.19318 Mhz. The 8253
chip itself cannot generate the frequency but depends upon an external crystal to generate the
frequency. Generated frequency from the crystal is fed to the clock pin of the 8253 IC.
Programming Expertise In C Hardware Interaction – II 209
The 8253 chip features a port 66 (also called the count port) to supply a numeric value (count) via
software. The 8253 will wait till the specified count before sending another pulse to the speaker. The
count keeps on getting decremented. When it becomes 0 a pulse is sent to the speaker.
The 8253 chip also features a control port (address 67) via which the operational mode (one of the 6
modes) of the chip can be decided. The 8255 chip is connected to 8253 and to the speaker. The 8255
chip can be used to turn on/off the speaker. This can be achieved via port 97 of the 8255 chip.
8253 – Port 67
We can communicate with the timer chip through any of the four I/O ports with addresses 64 through
67. The timer can be configured to mode number 3, channel number 2. This can be done by writing a
8-bit data to port number 67. The value of this 8-bit data is decided as shown in the slide.
The Control byte is a special 8-bit value send to the control port of the 8253 chip. The value sent
signifies the configuration as well as operational mode of the chip. The value we are interested in
sending to the port turns out to be 182 (10110110). This is because to drive the speaker we have to
select values as show below:
(1) Channel 2—speaker is physically connected to channel 2 of 8253.
(2) As the count specified is 16-bit & count port is only 8-bit we chose to write the value 8-bit at a
time low byte followed by high byte.
(3) Operational mode 3 is used to generate square wave pulses.
(4) Finally the count to be specified is in binary rather than BCD binary coded decimal.
Playing Tunes
The program given in the slide plays tunes.
Here, the values in float array n specifies frequency of a note to play. We are using union p since we
have to send an int to outportb( ) and outportb( ) can send only a byte at a time. Then we have sent
the value 182 (we have already discussed the meaning of bits of this value in earlier slide) to the
control port 67 using outportb( ) function. Next, using the inportb( ) function we have read the
status of speaker from port 97.
To turn on the speaker we have called outportb( ) function. Using this function we can turn on/off
the speaker. Since, we want to turn on the speaker, we must set the lower 2 bits of the value present at
port number 97 to 1, without disturbing the other bits. This we have achieved by using bitwise OR
operator.
To control the pitch of the speaker we should provide a frequency number to the timer and then turn
on the speaker for the duration of the beep. The frequency number is actually a counter value that
tells the PC how many of cycles to wait before sending another pulse. A smaller count value will
cause the pulses to be sent quicker, resulting in a higher pitch. The count value can be calculated by
the following formula:
count = 1193280 / n[ i ] ;
where, n[i] is the frequency of the note that we wish to play.
We have played the notes by calculating the count value for the frequency and sending it to the port
66 through outportb( ). This is repeated for all the frequency values of n[] through a for loop.
Lastly we have turned off the speaker by calling outportb( ) function where we have sent status to
port 97.
Programming Expertise In C Windows – II 215
Windows - II
In this lecture you will understand:
Creating a window
216 Windows – II Programming Expertise In C
Window Elements
The slide shows various elements of a window.
Creating A Window
To actually create a window we need to call the API function CreateWindow( ). This function
requires several parameters including the window class. Windows insists that a window class should
be registered with it before we attempt to create windows of that type. Once a window class is
registered we can create several windows of that type. Each of these windows would enjoy the same
properties that have been registered through the window class. There are several predefined window
classes. Some of these are BUTTON, EDIT LISTBOX, etc. Our program has created one such
window using the predefined BUTTON class.
The second parameter passed to CreateWindow( ) indicates the text that is going to appear on the
button surface. The third parameter specifies the window style. WS_OVERLAPPEDWINDOW is a
commonly used style. The next four parameters specify the window’s initial position and size—the x
and y screen coordinates of the window’s top left corner and the window’s width and height in pixels.
The next three parameters specify the handles to the parent window, the menu and the application
instance respectively. The last parameter is the pointer to the window-creation data.
Note that CreateWindow( ) merely creates the window in memory. We still are to display it on the
screen. This can be done using the ShowWindow( ) API function. CreateWindow( ) returns handle
of the created window. Our program uses this handle to refer to the window while calling
ShowWindow( ). The second parameter passed to ShowWindow( ) signifies whether the window
would appear minimized, maximized or normal. If the value of this parameter is
SW_SHOWNORMAL we get a normal sized window, if it is SW_SHOWMINIMIZED we get a
minimized window and if it is SW_SHOWMINIMIZED we get a maximized window. We have
passed nCmdShow as the second parameter. This variable contains SW_SHOWNORMAL by
default. Hence our program displays a normal sized window. The WS_OVERLAPPEDWINDOW
style is a collection of the following styles:
On executing this program a window and a message box appears on the screen as shown in the slide.
The window and the message box disappear as soon as we click on OK. This is because on doing so
execution of WinMain( ) comes to an end and moreover we have made no provision to interact with
the window.
You can try to remove the call to MessageBox( ) and see the result. You would observe that no
sooner does the window appear it disappears. Thus a call to MessageBox( ) serves the similar
purpose as getch( ) does in sequential programming.
More Windows
In the previous slide we learnt to create a window let us now try to create several windows on the
screen. This can be done using CreateWindow( ) and ShowWindow( ) function with in the for loop.
Note that each window created in this program is assigned a different handle. You may experiment a
bit by changing the name of the window class to EDIT and see the result.