Você está na página 1de 116

For all those who keep their Aims high and

keep on struggling…
ACKNOWLEGEMENTS

First and foremost, I bow deeply and sincerely in front of Allah Almighty,
the most beneficent and the most merciful, Who enabled me to tackle the
assigned project.

It is indeed a great honor for me to express my indebtedness to my


Advisor Professor M.Zahir Khan who guided me through all the project term
and his devotion and commitment enabled me to accomplish the task assigned
to me.

I would like to acknowledge the faculty in general and all my instructors in


particular for bringing me up to the point where I can undertake a project
independently. They imparted me the power of knowledge, which is a base for
not only this project, but also for the future tasks I might have to undertake.
Chapter - 1

Introduction

1
1.1 Introduction
The idea behind the project is to make microcontroller communicate with
computer situated anywhere in the world but connected to the Internet. To
achieve this goal we need one server connected to the Internet and the client can
access to that server from anywhere in the world by typing the address of the
server in any Internet browser (web page solution) or by typing the IP address of
the server to get connected to it. When the client is connected to the server he
can send the data to it and the server will do the required operation according to
the data it received from the client. The server is further connected to the
microcontroller through serial port. Thus any data received by the server from the
client is just forwarded to the microcontroller by the server. Such a program is
burnt in microcontroller that enables microcontroller to receive data from server
through serial port. When microcontroller receives data from the server it further
sends it to its Port-0. The microcontroller is interfaced with the load through solid-
state relay. When the input to the solid state relay is high it makes the load
connected to the supply and thus the circuit is complete the load gets connected
to the supply while when the input form the microcontroller is made low the solid
state relay act as open circuit and thus the load is disconnected from the supply.

1.2 The problem


Initially I went for making software that can be used for the communication
between client and server and also between server and microcontroller thus all
we need is that software to be run on server and then the same software is used
by the client for communication with server. But the problem in this method was
later recognized that we will need the software to be with us in disk etc all the
time so that we can run it from other computers that don’t have the software thus
I worked to solve this problem also.

1.3 Solution

In this project I developed the software program that allows user to


communicate with the server by simply using its address, which is fixed and
doesn't change with the location of the server. The client or user just need the
Internet browser and type the address of the server to send data to it.

1.4 Objective and our achievement


Main task of the project was to develop software in visual basic (VB) to
make communication between two PCs (client and server) possible and build a

2
hardware that is connected to server, which is controlled by the client. When the
control command is sent through the network the hardware is accessed through
the serial port. This hardware contains the microcontroller and the solid-state
relays connected to the load.
In this project I have been succeeded to send data from the client to
server. The server further sends the data it received from the client to the
microcontroller. The microcontroller is programmed to receive the data and
transfer it to its Port0 where the solid-state relays are connected.
Further I also succeeded to build a website using HTML and ASP (active
server page) which do the same but is easy to use because then we don’t need
to remember the IP address of the server which can be variable but we need to
know the address of server website which is easy to remember. The website help
to transfer specific data that the user (browsing that website) want to send to the
server. Further the server transfer the data it received to the microcontroller
through serial port using software running on it.
In this way it can be said that I have done the project in two ways i.e.
through software method (VB6) and through using website (ASP and HTML).

Server

internet

Client
M.C

Relay and load

1.5 Conclusion

Many applications can be developed by this system primarily in field of


remote monitoring and controlling. For example remote monitoring of Weather
Station, Oil Storage, Home Automation, etc. We can build this system with low
cost and easy to install.
As the system is independent of location of client and server so it can be
installed anywhere provided the Internet facility is available. Thus we can install
this system anywhere. Also we don't need any person to monitor the situation on
server side once the system is installed and running smoothly (no electricity
problem etc).

3
Chapter - 1

Introduction

1
1.1 Introduction
The idea behind the project is to make microcontroller communicate with
computer situated anywhere in the world but connected to the Internet. To
achieve this goal we need one server connected to the Internet and the client can
access to that server from anywhere in the world by typing the address of the
server in any Internet browser (web page solution) or by typing the IP address of
the server to get connected to it. When the client is connected to the server he
can send the data to it and the server will do the required operation according to
the data it received from the client. The server is further connected to the
microcontroller through serial port. Thus any data received by the server from the
client is just forwarded to the microcontroller by the server. Such a program is
burnt in microcontroller that enables microcontroller to receive data from server
through serial port. When microcontroller receives data from the server it further
sends it to its Port-0. The microcontroller is interfaced with the load through solid-
state relay. When the input to the solid state relay is high it makes the load
connected to the supply and thus the circuit is complete the load gets connected
to the supply while when the input form the microcontroller is made low the solid
state relay act as open circuit and thus the load is disconnected from the supply.

1.2 The problem


Initially I went for making software that can be used for the communication
between client and server and also between server and microcontroller thus all
we need is that software to be run on server and then the same software is used
by the client for communication with server. But the problem in this method was
later recognized that we will need the software to be with us in disk etc all the
time so that we can run it from other computers that don’t have the software thus
I worked to solve this problem also.

1.3 Solution

In this project I developed the software program that allows user to


communicate with the server by simply using its address, which is fixed and
doesn't change with the location of the server. The client or user just need the
Internet browser and type the address of the server to send data to it.

1.4 Objective and our achievement


Main task of the project was to develop software in visual basic (VB) to
make communication between two PCs (client and server) possible and build a

2
hardware that is connected to server, which is controlled by the client. When the
control command is sent through the network the hardware is accessed through
the serial port. This hardware contains the microcontroller and the solid-state
relays connected to the load.
In this project I have been succeeded to send data from the client to
server. The server further sends the data it received from the client to the
microcontroller. The microcontroller is programmed to receive the data and
transfer it to its Port0 where the solid-state relays are connected.
Further I also succeeded to build a website using HTML and ASP (active
server page) which do the same but is easy to use because then we don’t need
to remember the IP address of the server which can be variable but we need to
know the address of server website which is easy to remember. The website help
to transfer specific data that the user (browsing that website) want to send to the
server. Further the server transfer the data it received to the microcontroller
through serial port using software running on it.
In this way it can be said that I have done the project in two ways i.e.
through software method (VB6) and through using website (ASP and HTML).

Server

internet

Client
M.C

Relay and load

1.5 Conclusion

Many applications can be developed by this system primarily in field of


remote monitoring and controlling. For example remote monitoring of Weather
Station, Oil Storage, Home Automation, etc. We can build this system with low
cost and easy to install.
As the system is independent of location of client and server so it can be
installed anywhere provided the Internet facility is available. Thus we can install
this system anywhere. Also we don't need any person to monitor the situation on
server side once the system is installed and running smoothly (no electricity
problem etc).

3
Chapter-2

Micro-controller 8051

4
2.1 INTRODUCTION:
Although computers have been with us only for a few decades, their impact
has been profound as they are used in a variety of applications ranging from
simple entertainment purposes to their use in industry and up to guiding missiles
in military applications. Now the stage has reached where it is hard to imagine
the present world of science without the use of computers.
In 1971 INTEL CORPORATION introduced the 8080, the first microprocessor
and since then a lot of achievements have been made in this field. A device
similar to microprocessor is microcontroller, which is actually a dedicated
microprocessor. It can be very efficiently used in the industry for control
purposes. Thus eliminating the need of more expensive computers in such
applications.
Whereas a microprocessor is a single chip CPU a microcontroller contains in
a single IC a CPU and much of the remaining circuitry of microcomputer system.
Microprocessors are commonly used as CPU in the microcomputer systems.
This is what they are designed for. Microcontrollers on the other hand are suited
to control of I/O devices in designs requiring a minimum component count,
whereas microprocessors are suited to processing information in computer
systems.

2.2 Pins Description OF 8051


The general layout of 8051 is shown in the figure (next page):
8051 is a 40-pin device. Out of these 40 pins, 24 are used for I/O purposes.
Pin#20 is connected to ground and pin#40 to Vcc (supply). An 11.059 MHz crystal
is connected between pin#18 and pin#19.
The device has four ports, which are as follows:

2.2.1 Ports:

™ Port 0 is a dual-purpose port on pins 32-39 of the 8051 IC. It can


be used as a general purpose I/O port or for large designs it
becomes a multiplexed address data bus.

™ Port 1 is a dedicated I/O port on pins 1-8. These pins are available
for interfacing to external devices as required

5
The Pin diagram of 8051

6
™ Port 2 on pins 21-28 is a dual-purpose port serving as general purpose
I/O or as the high byte of address bus if external code memory or more
than 256 bytes of external data memory are used.

™ Port 3 is a dual-purpose port on pins 10-17 and like other ports it can be
used for input and output. Port 3 is used for some of the most important
functions given below.

P3.0 RXD B0H Receive data for serial port.


P3.1 TXD B1H Transmit data for serial port.
P3.2 INT0 B2H External interrupt 0.
P3.3 INT1 B3H External interrupt 1.
P3.4 TO B4H Timer/Counter 0 External input.
P3.5 T1 B5H Timer/counter1 External input.
P3.6 WR B6H External data memory write strobe.
P3.7 RD B7H External data memory read strobe.

Note: To use port 0 as input and output ports, each pin must be connected
to 1kohm pull-up resistor externally. Other ports don’t need the pull-up
resisters because they have them internally.

2.2.2 Control Signals.


The 8051 have four dedicated bus control signals. These are as follows.
™ PSEN (program store enable): When we want to use external ROM
then PSEN should be connected to the OE (output enable) pin of the
ROM. If PSEN is low means instructions are fetched from external
ROM and when PSEN is high, means instructions are taken from
internal ROM.
™ ALE (address latch enable): ALE is used for demultiplexing the
address data bus. It pulses at a rate of 1/6th of on chip oscillator
frequency and can be used as general-purpose clock for the rest of
system.
™ EA (external access): When EA signal is high it mean no external
ROM is connected to 8051 microcontroller & when EA pin is grounded
it mean no external ROM is connected. Note that when external ROM
is used internal ROM of 8051 microcontroller will not work.
™ RST (RESET): This input on pin 9 is the master reset for the 8051
microcontroller. On the resetting of microcontroller the program counter
will reset to 0000 and all the values in microcontroller registers will be
lost e.g. Accumulator register will reset to 0000.

2.2.3 On chip oscillator


The 8051 features an on chip oscillator that is typically driven by a crystal
connected to pins 18 and 19. The crystal oscillator also needs two capacitors of
30pF value. One side of each capacitor is connected to the ground.

7
Usually the frequency of crystal oscillator is 11.059 MHz.

2.2.4 Power Connections:


The 8051 operate from a single +5 volts supply. The Vcc connection is on
pin#40 and the ground or Vss connection on pin #20.

2.3 Memory organization


8051 implements a separate memory space for programs and data. Both
code and data may be internally stored or expanded to external memory.
The internal memory consists of On-chip ROM and On-chip data RAM. The
On-chip RAM contains a rich arrangement of general-purpose storage, bit
addressable storage, register banks and special function registers (SFR). The
registers and I/O ports are memory mapped.

2.3.1 General purpose RAM


It has 80 bytes of general purpose from addresses 30H – 7FH. Any location
can be accessed freely using direct of indirect addressing modes.

2.3.2 Bit addressable RAM


The 8051 contains 210 bit addressable locations of which 128 are at byte
addresses 20H –2FH. This is a powerful feature of most Microcontrollers. Bits
can be set, cleared, ANDed, ORed.

2.3.3 Register banks


The bottom 32 locations (00H-1FH) of internal memory contain register
banks. The 32 bits are divided into four banks of registers in which each bank
has 8 registers (R0 to R7).

2.3.4 Special function registers (SFR)


These are configured as a part of on chip RAM. Therefore each register also has
an address. There are 21 SFRs at the top of the internal RAM from addresses
80H – FFH.
The various SFRs used commonly are:
Accumulator
Program status word
B Register.
Stack pointer.
Data pointer.
Port registers.
Timer registers.
Serial port registers.
Interrupt registers.
Power control registers.

8
RAM
7F

GENERAL PURPOSE RAM

30
B 2F 7F 7E 7D 7C 7B 7A 79 78
I 2E 77 76 75 74 73 72 71 70
T 2D 6F 6E 6D 6C 6B 6A 69 68
2C 67 66 65 64 63 62 61 60
A 2B 5F 5E 5D 5C 5B 5A 59 58
D 2A 57 56 55 54 53 52 51 50
D 29 4F 4E 4D 4C 4B 4A 49 48
R 28 47 46 45 44 43 42 41 40
E 27 3F 3E 3D 3C 3B 3A 39 38
S 26 37 36 35 34 33 32 31 30
S 25 2F 2E 2D 2C 2B 2A 29 28
A 24 27 26 25 24 23 22 21 20
B 23 1F 1E 1D 1C 1B 1A 19 18
L 22 17 16 15 14 13 12 11 10
E 21 0F 0E 0D 0C 0B 0A 09 08
20 07 06 05 04 03 02 01 00
1F
REGISTER BANK 3
18
17
REGISTER BANK 2
10
0F
REGISTER BANK 1
08
07
REGISTER BANK 0 ( DEFAULT )
00

Memory organization of 8051

9
special function registers
FF
F0 F7 F6 F5 F4 F3 F2 F1 F0 B
E0 E7 E6 E5 E4 E3 E2 E1 E0 ACC
D0 D7 D6 D5 D4 D3 D2 D1 D0 PSW

B8 - - - BC BB BA B9 B8 IP
B
Y B0 B7 B6 B5 B4 B3 B2 B1 B0 P3
T
E A8 AF - - AC AB AA A9 A8 IE

A0 A7 A6 A5 A4 A3 A2 A1 A0 P2
A
D 99 NOT BIT ADDRESSABLE SBUF
D 98 9F 9E 9D 9C 9B 9A 99 98 SCON
R
E 90 97 96 95 94 93 92 91 90 P1
S
S 8D NOT BIT ADDRESSABLE TH1
E 8C NOT BIT ADDRESSABLE TH0
S 8B NOT BIT ADDRESSABLE TL1
8A NOT BIT ADDRESSABLE TL0
89 NOT BIT ADDRESSABLE TMOD
88 8F 8E 8D 8C 8B 8A 89 88 TCON
87 NOT BIT ADDRESSABLE PCON
83 NOT BIT ADDRESSABLE DPH
82 NOT BIT ADDRESSABLE DPL
81 NOT BIT ADDRESSABLE SP
80 87 86 85 84 83 82 81 80 P0

Memory organization of 8051

10
2.4 Timers in 8051 microcontroller
Timers are used in virtually all control-oriented applications, and the 8051
timers are no exception. There are two 16-bit timers each has four modes of
operation.

2.4.1 Importance of timers


The timers are used basically for.
™ Interval timing: In interval timing operation, a timer is programmed to
overflow at a regular interval and set the timer overflow flag. The flag is
used to synchronize the, program to perform an action such as, checking
the state of I/p or sending data to o/p.
™ Event counting: Event counting is used to determine the number of
occurrence of an event. An event is any external stimulus that provides a
1-to-0 transition to a pin on the 8051 IC
™ Baud rate generation for the built-in serial port: The 8051 transfers
and receives data serially at many different baud rates. The baud rate is in
the 8051 is programmable. This is done with the help of timer1. The rate
of data transfer in serial communication is expressed in bps (bits per
seconds). Baud rate is the modem terminology and is defined as the
number of signal changes per second. In modems there is an occasion
when a single change of signal transfers several bits of data. As far as the
conductor wire is concerned the bit rate and baud rate are equal.

2.4.2 Timer Registers


The 8051 timers are accessed using six special function register SFRS
™ The first one is timer mode register (TMOD). The TMOD register
contains two groups of four bits that sets the operating mode for timer 0
and timer 1. TMOD is not bit-addressable, nor does it do needs to be.
Generally it is loaded initially at the beginning of program through software
to initialize (set) the timers (or timer) mode.

TMOD Register
GATE C/T M1 M0 GATE C/T M1 M0

Explanation of different bits of TMOD register


GATE Timers in 8051 can be started by method of software and hardware. To
start or stop the timer by software when GATE=0 otherwise timer is
stopped or started by external source when GATE=1
C/T This bit is used to decide if timer is used as counter or timer. When
C/T=0 means timer is used in timer mode & C/T=1 mean counter mode.
M1 The two bits are used to set the mode of the timer. There are 4 modes of
M0 timers in 8051 microcontroller.

11
Mode M0 M1 Operation mode
0 0 0 13 bit timer mode
1 0 1 16 bit timer mode
2 1 0 8 bit auto reload timer/counter
3 1 1 Split timer mode

Note: The upper four bits of TMOD register are used for Timer-1 and the
lower four bits are used for Timer-0

™ The second SFR used for timer operations is TCON (timer control)
register. TCON register is 8-bit register but some of its bits are used in
timer operations.
TCON register
TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0

TR1 and TR0 are bits used for starting and stopping the timer-1 and timer-0 by
software method.
TF1 and TF0 are flag bits for timer1 and timer0 and are set when the timer count
reach to its limit.

™ Timer 0 is a 16-bit register. The 16-bit register of timer 0 is accessed as


low byte and high byte. The low byte is called TL0 and the upper byte is
called TH0. These registers are used like any other register such as A, B
etc.
™ Timer 1 register is also 16 bits register and split in to two bytes, referred
as TL1 and TH1. These register are accessible same as Timer0 registers
.
2.4.3 8-bit Auto-Reload Mode (timer mode 2)
This mode has many applications, including setting the baud rate in serial
communication. Mode 2 is an 8-bit timer however it has auto-reload
capability. In auto-reload the higher byte of timer is loaded with initial count
and a copy of it is given to lower byte of that timer. The following are the
characteristics of Mode 2 operation.
™ It is 8-bit timer thus it allow only values of 00 to FFH to be loaded into
the higher byte of timer’s register.
™ After higher byte of 16-bit timer is loaded with 8-bit value, the 8051
give a copy of it to lower byte of timer register. Then the timer must be
started. This is done by making the TR0=1 of TCON register for timer0
used in mode 2 (similarly making TR1=1 of TCON register for timer1
used in mode 2). The instruction to do so is SETB TR0.
™ After the timer is started the timer starts counting by increasing the
contents of the lower bytes of timer register. It counts until it reaches
FFH. When it reaches to FFH then it roll back to initial value that was
set in higher byte of the timer register. Mover over it also set the TF0
(or TF1) flag of TCON register. Thus normally the TF flag for the

12
particular timer is always monitored to check if the required time has
passed or not.

2.5 8051 Serial communication

Computers can transfer data in two ways: parallel and serial.


™ In parallel data transfer, often 8 or more lines (wire conductors) are used
to transfer data to a device that is only a few feet away. E.g. printers and
hard disks are connected to computer using parallel method.
™ In serial communication the data is sent one bit at a time in contrast to
parallel communication in which data is sent a byte or more a time. Serial
communication is slow but to transfer data many meters away serial data
transfer is used.

2.5.1 Basics of serial communication


Serial data communication uses two methods: synchronous and synchronous
™ The synchronous method transfers a block of data at a time.
™ The asynchronous serial communication transfer single byte at a time.
It is possible to write software to use either of these methods, but the
programs can be tedious and long. For this reason there is special IC chip made
by manufacturers for serial communication named as UART (universal
asynchronous receiver-transmitter) and USART (universal synchronous-
asynchronous receiver-transmitter). The 8051 has built-in UART chip.

2.5.2 RS232 Standards


To allow compatibility among data communication equipment made by
various manufacturers an interfacing standard called RS232 was set by the EIA.
This standard is used in PCs and other electronic equipments, but RS232 is not
TTL compatible. In RS232 logic 1 is represented by –3 to –25V while the logic 0
is represented by +3 to +25V making –3 to +3V undefined. Thus to connect any
RS232 to microcontroller we use voltage converters such as MAX232 to convert
the TTL logic levels to RS232 voltage levels and vice versa.
The RS232 cables are commonly referred to as DB25 connectors having 25
pins but as not all pins are used in PCs thus IBM introduced the DB9 connectors
having 9 pins used in PCs.

2.5.3 Baud Rate in 8051


The 8051 can communicate using different baud rates. In 8051 baud rates are
programmable i.e. they can be changed using timer 1 in mode 2. The value to be
inserted in TH1 of timer register for different baud rates is given in the table
below.
Baud rate TH1 (decimal)
9600 -3
4800 -6
2400 -12

13
2.5.4 8051 connection to RS232
The 8051 have two pins that are used specifically for transferring and receiving
data serially. These pins are TXD (pin 11 or p3.1) and RXD (pin 10 or p3.0) used
for transmission and reception of data (respectively) serially. These pins are TTL
compatible; therefore, they require a line driver (MAX232) to make them RS232
compatible.

2.5.5 SBUF Register


SBUF (serial buffer) register is 8 bit register used only for serial communication in
8051 microcontroller. For a byte of data to be transmitted through T/R line, it
must be placed in SBUF register. Similarly when 8051 microcontroller receives
the 8 bit data it is placed in the SBUF register by it. SBUF can be accessed like
any other register.

2.5.6 SCON Register


SCON (serial control) is 8 bit register used to program the start bit, stop bit, and
the data bits of the data framing among other things. The following shows the
various bits of SCON register.
SCON register
SM0 SM1 SM2 REN TB8 RB8 T1 R1

Bits of SCON register and their functions


SM0 SCON.7 Serial port mode specifier
SM1 SCON.6 Serial port mode specifier
SM2 SCON.5 Used for multiprocessing communication (normally 0)
REN SCON.4 If we want to both transfer and receive data, REN =1
If REN=0 mean 8051 can only send data thus data
reception is blocked
TB8 SCON.3 Not used
RB8 SCON.2 Not used
TI SCON.1 When 8051 finishes the transfer of 8-bit character, it
raised TI (transmit interrupt) flag to indicate that it is
ready to transmit other byte.
RI SCON.0 When 8051 receive data serially, it get rid of start and stop
bit (transmitted along with data) and place the byte of data
receive in the SBUF register. Then it raises the TI
(receive interrupt) flag to indicate that the byte is
received and should be picked up from SBUF register.

Different modes of serial communication


SM0 SM1 Mode
0 0 Serial mode 0
0 1 Serial mode 1, 8bit data, 1 start bit, 1 stop bit
1 0 Serial mode 2
1 1 Serial mode 3

14
2.5.7 Programming the 8051 to transfer data serially
To program 8051 to transfer data/receive data serially the following steps
must be taken out.
™ The TMOD (timer mode) register is loaded with 20H indicating the use of
timer1 in mode 2 (8-bit auto reload) to set the baud rate.
™ The TH1 (higher byte of timer1) is loaded with appropriate value to set the
baud rate.
™ SCON register is loaded with value 50H indicating serial mode1 where 8-
bits are framed with 1stop and 1 start bit.
™ TR1 bit is set to start the timer.
™ TI bit is cleared for transferring data serially while RI bit is cleared to
receive data serially by instruction e.g. CLR TI and similarly CLR RI
™ If data is transmitted serially then it is placed in SBUF register and then
the TI flag is monitored to see it the data transmission is completed or not.
While to receive data serially the RI flag is monitored to see if the entire
character is received yet or not and as it get set it mean all the data has
arrived in SBUF register thus should be moved from it for appropriate
operation.

2.6 8051 training kit


The Intel MCS-51 series of microcontroller is widely recognized as a standard
for incorporation into wide range of product from automatic washing machines,
automatic vending machines, digital weighing machines, welding machines,
microwave ovens and robot control cards to programmable logic controllers
(PLCs). Their simplicity makes them ideal for where it is necessary to quickly
build up a control system. The 8051 microcontroller is versatile and easily
programmable. It finds extensive applications in automation because of its simple
architecture and built in I/O capabilities. The use of this controller considerably
reduces the chip count. Because of the same reason this controller is also
considered as a good teaching model for the learning a teaching platform in the
Institutions.
Microcontroller Training & Development Kit has been designed specifically for
studying the functionality of MCS-51 microcontroller through experimentation and
exercises.
The Kit is aimed to train a wide range of users from beginners to technicians,
students, hardware designers and experienced engineers. The board is a
dynamic learning platform specifically designed keeping in view the requirements
of both small scale and large-scale projects. The Kit has been designed with
features, which make it ideal as a first step educational tool, as well as an
advanced and power full development tool in a minimum possible time.

15
The salient features of the board are as under:
™ On Board Regulated Power Supply
™ 8 bit A/D Module for Real Time Data Acquisition
™ RS232 Interface
™ Expandable (can be interfaced with other devices and hardware) and
Flexible
™ Output Devices includes:
™ 8 x LEDs
™ 4 x Seven Segment Displays
™ 2 x 20 Line LCD
™ 3 x status LEDs
™ Power Supply
™ Condition monitoring
™ Relay status
™ 1 x Triac (for AC load)
™ 1 x Darlington (for DC load)
™ 1x DPDT 12 V DC Relay
™ Buzzer
™ ZIF Socket for Microcontroller
™ 5 x Momentary Switches
™ Prototype Area (Plated Through Hole on 0.1” x 0.1” Grid
™ All ICs mounted on bases

16
Summary

In this chapter we examined the hardware features of the 8051


Microcontroller. We specially examined the 8051 on chip timers
and the on chip serial port that operates in several modes over
wide range of frequencies.

References

¾ The 8051 Microcontroller and Embedded systems


By Mohammad Ali Mazidi
Janice Gillespie Mazidi
¾ The 8051 Microcontroller (3rd Edition)
By I. Scott Mackenzie

17
Chapter – 3A

Software of the project


(Using Visual Basic)

18
3a.1 Introduction
There is much excitement over the Internet and the World Wide Web.
The Internet ties the “information world” together. The web makes the Internet
easy to use and gives it the flair and sizzle of multimedia. Some organizations
see the Internet and the web as crucial to their information systems strategies.
Visual basic provides several built-in networking capabilities that make it easy
to develop Internet and web based program and applications. Visual basic
can enable the programs to search the world for information and to
collaborate with programs running on other computers worldwide or just within
an organization. Visual basic can even enable the applications running on the
same computer to communicate with on another.
Networking is massive and complex topic. Visual basic provides a rich
complement of networking capabilities and will likely be used as an
implementation vehicle in computer networking courses. Visual basic offers
socket based communication that enable applications to view networking as
streams of bytes similar to file input/output - a program can read from a socket
or write to a socket as simple as reading from a file or writing to a file. Socket
connections are similar to a telephone calls - the telephone handset
represents the socket. The mouthpiece of the telephone is the output stream
and the earpiece of the telephone is the input stream. The call (i.e. connection)
terminates until one of the participants in the conversation terminates the call
by hanging up the phone. We show how to create and manipulate sockets.
With socket-based networking a process establishes a connection to another
process. While the connection is in place, data flows between the processes
in continuous streams. Sockets are said to provide a connection-oriented
service. The protocol used for transmission is the popular TCP-transmission
control protocol. Sockets and TCP protocol will be the most desirable for the
vast majority of Visual Basic programmers.
Our project focuses on both sides of client/server relationship. The
client requests that some action be performed and the server performs the
action returning the result (if any) to the client. The client first attempts to
establish a connection to the server. The server can accept or deny the
connection. If the connection is accepted, then the client and server
communicate through sockets in much the same manner as if they were doing
file I/O. When the communication connection is no longer needed, the client
and server each close the connection.

3a.2 Visual basic Internet controls


Visual basic provides several networking controls to facilitate
development of network-oriented applications. Each of them is summarized in
table below.
Control Description
WebBrowser Enables applications to provide web browsing, local
control document viewing and file downloading capabilities. This
control provides applications with many features of the
Internet explorer.

19
InternetTransfer Enables applications to use Hyper Text Transfer
control Protocol (HTTP) and File Transfer Protocol (FTP) for
internet based applications. An application using this
control can retrieve files from and send files to any site
that uses one to these protocols.
Winsock control Enable client server application programming using
either User Datagram Protocol (UDP) or Transmission
Control Protocol (TCP)

We will discuss the Winsock control only because it is related to out project.

3a.3 Winsock control


The Winsock control operates at the lowest level of all the Internet controls,
allowing client/server applications to communicate using both Transmission
Control Protocol (TCP) and User Datagram Protocol (UDP). Winsock
control is used in the project for attaining the first and major phase of the
project i.e. communication between two computers connected to each other
through Internet. This phase is shown in the figure.

Server

internet

Client

Communication with TCP is similar to a telephone conversation - there


must be a connection between the client and server before they can
communicate. TCP is commonly referred to as a connection-based or
connection oriented protocol. Communication with UDP is similar to sending
letters in the mail. A packet- called datagram- is created, addressed and sent
over the network. There is no direct connection between the origin and
destination. UDP is commonly referred to as connectionless protocol.
TCP protocol is normally used when large amount of data are transmitted
between a server and a client and when reliability us imperative (i.e. the bytes
of information must get to their destination with acknowledgment of their
receipt). The connection maintained between the server and the client
ensures data integrity. UDP is typically used when small amount of data are
sent or data are sent intermittently.

3a.3.1 Establishing a Simple Server (Using TCP Protocol)

Establishing a simple server in Visual Basic requires several steps.


Step 1 is to add a Winsock control to the form. To use Internet Transfer
control it must first be added to the toolbox by selecting components from the
project menu to display the components dialog box. In the dialog box, scroll
down and select the option Microsoft Winsock control 6.0. When selected
properly a small check mark appears in the box to the left of the option. Click

20
the ok button when you are done to dismiss the dialog box. The icon for the
Winsock control will be at the bottom of the toolbox.
In step 2, the server must be set up to listen for connection from clients on a
specific port number as specified by Winsock control’s local port property.
Each client will ask to connect to the server on this port. Port numbers are
positive integer values up to 65535. Typically, port numbers below 1024 are
reserved for system services. The command that registers with Winsock
controls “tcpserver” an available port number on local machine is
serverclient.LocalPort = Val(txtsport.Text)

Where txtsport.text can be any value defining the port number and is entered
by the user.
NOTE: “serverclient” is the name given to the Winsock control and LocalPort is
the name of one of its property. The serverclient means the one Winsock control
is used by the software for both client and server operation.

Each client connection is managed with a Winsock control. In step 3, once the
tcpserver port number is established, the server must be told to listen
indefinitely for an attempt by client to connect. This is accomplished with a call
to Winsock control’s Listen method using the command
Call serverclient.Listen

When a connection request is received while the server us listening, event


procedure ConnectionRequest executes i.e. the control shift to the line
Private Sub serverclient_ConnectionRequest(ByVal requestID As Long)

Step 4 is to accept the request for connection from the client – typically
performed in the connectionrequest event procedure. This is accomplished by
Winsock control’s Accept method as in the command below
Call serverclient.Accept(requestID)

Where RequestID is received as an argument to event procedure


ConnectionRequest and simply passed to the Accept method. Once this
method is called, there is connection between the server and the client
through which the stream of data can be passed.

Step 5 is the processing phase in which the server and the client
communicate through the connection. When data arrives at the server, the
Winsock control’s DataArrival event procedure executes i.e.
Private Sub serverclient_DataArrival(ByVal bytesTotal As Long)

And the statement


Call serverclient.GetData(message)

retrieves string-based information from the client and stores it in the string
message. Also two optional arguments can be used to specify the type of
data received and the maximum length of the data to receive. Data is sent to
the client using the SendData method e.g. the statement
Call serverclient.SendData(code)

21
Sends the string code to the client (where code is the number set by server
and the client should know it).

In step 6 when the transmission is complete and the client closes the
connection the Winsock control’s Close event procedure executes i.e.
Private Sub serverclient_Close()

At this point the sever connection should be closed with the statement like
Call serverclient.Close

The server application can be told to listen for a new client connection by
invoking the Listen method on the Winsock object (as discussed above).

3a.3.2 Establishing a Simple client (Using TCP Protocol)

Establishing a simple client in Visual Basic requires several steps.


Step1 is to add Winsock control to the form. To use the Internet Transfer
control it must be added to the toolbox by same way as discussed above. But
in our software the client and server uses one Winsock control that is given a
name serverclient thus there is no need for adding the second Winsock
control. Thus software can be used as server as well as client but not at a
same time as client and server. When the software is used as client the server
side disables and similarly when software is used as server the client side
disables.
In step 2 the client side Winsock object must be told the server to which to
connect and the port number on that server. This is accomplished with the
statements
serverclient.RemoteHost = txtip.Text
serverclient.RemotePort = Val(txtcport.Text)

The value to the RemoteHost property of the serverclient Winsock object is


a string (i.e. txtip.text is the value in the text box with name txtip) indicating
either the name of the server (e.g. www.microsoft.com or localhost) or the
Internet IP address for the server (e.g. 127.168.68.3 or for the local host the
address is 127.0.0.1). There is an option that if a user doesn’t enter the IP
address then it will be considered by default as 127.0.0.1 i.e. localhost
address. The statements are
If serverclient.RemoteHost = "" Then
serverclient.RemoteHost = "localhost"
End If

Note that the server name localhost normally represents the local machine
thus enable the programmer to check the working of its software without
having Internet connected by running both client and server software and
communicating with the localhost i.e. with itself.
The other statement written above in which serverclient property
RemotePort is used and is assigned a value that is taken from the textbox
having the name txtcport. The value assigned to the property RemotePort of
the serverclient Winsock object must match the port number on which the

22
sever application is listening; otherwise no connection can be established
between the client and server.
In step 3 the connection to the server is established using a call to the
Winsock object’s Connect method as in statement
Call serverclient.Connect

If the connection attempt is successful a connection is established and the


client can now communicate with the server otherwise a run time error occurs
and the Winsock objects Error event procedure executes i.e.
Private Sub serverclient_Error(ByVal Number As Integer, Description As
String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As
String, ByVal HelpContext As Long, CancelDisplay As Boolean)

Step 4 is the processing phase in which the client and server communicate
through the connection established. As with the server, when data arrives at
the client the Winsock control’s DataArrival event procedure executes.
But more important is the client sending data to the server. Data is sent to the
server using the SendData method. For example the statement
Call serverclient.SendData(PinNumber)

Sends the string PinNumber to the server i.e. the certain code that sets the
pins of microcontroller on or off.
In step 5 when the transmission is complete and the server closes the
connection the Winsock control’s Close event procedure executes. At this
point the client connection should be closed with the statement like
Call serverclient.Close

If server doesn’t closes the connection the client should still invoke the close
method to close its side of the connection.

3a.4 Serial Port Interfacing Using Visual Basic

Serial Interfacing is one of the most commonly used mediums for data
acquisition and control using computers. In this section we will learn how to
interface the serial port using Visual Basic Programming. Serial Interfacing
provides an easier way of data acquisition and control using computers. An
IBM compatible PC usually is equipped with 2 serial ports and one parallel
port for external communication. A serial port sends and receives data bit by
bit compared to the parallel port in which data is received and transmitted in
multiple bits. A serial port started out as an interface between Data Terminal
Equipment (such as a monitor) and data communication equipment (such as
a modem). Nowadays the applications of serial ports have increased as
manufacturers started using serial ports for a lot of applications e.g.
programmers use it to interface additional devices like the printer or another
computer for serial communication between the computer.

The serial port programming was difficult to do specific tasks because


earlier it was being programmed in DOS but with advances in computer
technology with Windows taking over the DOS, there needed to be ways to
have a serial interface with the computer and Visual Basic seems to provide a

23
relatively easy way of interfacing the serial port and hence we use it more
often now-a-days. Visual Basic uses the Microsoft Comm. Control 6.0
component for serial interfacing. In our project we have also used the MS
Comm. component for serial communication between microcontroller and the
server computer as shown in the figure below.

Server Serial communication


Between server and
microcontroller

M.C

Relay and load

Step 1 is to add a MS Comm. control to the form. For serial


communication it must first be added to the toolbox by selecting components
from the project menu to display the components dialog box. In the dialog
box, scroll down and select the option Microsoft Comm. control 6.0. When
selected properly a small check mark appears in the box to the left of the
option. Click the ok button when you are done to dismiss the dialog box. The
telephone icon for the MS Comm. control will be at the bottom of the toolbox.
Double click on it to select it and it is displayed on the form. The Properties of
the MS Comm1 are changed in the properties windows.
Then the code for the serial communication will have the first part as to
select the port and baud rate for the serial communication of the Comm. port.
This is done by the code below.
serial.CommPort = 1
serial.Settings = "1200,N,8,1"

The first command will select the port 1 for communication while the second
command will set the baud rate of 1200 along with 8bit data transfer.
To open the serial port for serial communication the commands will be
serial.PortOpen = True

To send the data from the server to the microcontroller the command is
serial.Output = Chr$(PinNumber)

24
3a.5 Complete software

The screen shots and the code of the software (in visual basics) that
enables the client and server to communicate with each other and also
allows server to send data to microcontroller is given below. The
working of the software will be discussed later.

Screen shot of design mode

Screen shot of code window

25
Property window of Property window of
Winsock control Ms Comm. control

3a.5.1 Code of the program

The code of the program is written in the code window and is written below.
To understand this code basic knowledge of computer language and visual
basic is must.

Dim optionselect As Integer 'for selecting different options


Dim txt As Long

Private Sub cbopinnumber_Click()

'**********************************
'best part of the program
Dim tobinary As Integer
Dim digit(7) As Integer
tobinary = cbopinnumber.ListIndex
For p = 0 To 7
digit(p) = tobinary Mod 2

26
If digit(p) = 0 Then
cmdled(p).BackColor = vbWhite
Else
cmdled(p).BackColor = vbRed
End If
tobinary = tobinary \ 2
Next p

'**********************************
End Sub

Private Sub cmdconnect_Click()

Select Case cmdconnect.Caption


Case Is = "Connect"
serverclient.RemoteHost = txtip.Text

If serverclient.RemoteHost = "" Then


serverclient.RemoteHost = "localhost"
End If

serverclient.RemotePort = Val(txtcport.Text)

Call serverclient.Connect

cmdserver.Enabled = False
cmdconnect.Caption = "Disconnect"
cmdsend.Enabled = True

Case Is = "Disconnect"

Call serverclient.Close
cmdconnect.Caption = "Connect"
cmdserver.Enabled = True
cmdsend.Enabled = False

End Select

End Sub

Private Sub cmdlisten_Click()

Select Case cmdlisten.Caption


Case Is = "Listen"
serverclient.LocalPort = Val(txtsport.Text)
Call serverclient.Listen

cmdclient.Enabled = False
cmdlisten.Caption = "Close"

27
'***************************************************

Case Is = "Close"
serverclient.Close
cmdlisten.Caption = "Listen"
cmdclient.Enabled = True

End Select

End Sub

Private Sub Form_Load()


'***************************************************
'tcpclient is selected
optionselect = 1
'***************************************************
txt = 0

Dim pins As Long 'for the pin numbers in cbopinnumber


'add the pin numbers 0 to 255 to cbopinnumber
For pins = 0 To 255
cbopinnumber.AddItem CStr(pins)
Next pins
'default to pin 0 being selected
cbopinnumber.ListIndex = 0
'***************************************************

Dim i As Integer 'to make all led white


For i = 0 To 7
cmdled(i).BackColor = vbWhite
Next i
'***************************************************

frconnect.Height = 1815
frconnect.Width = 3615
frconnect.Left = 5400
frconnect.Top = 480

frsendrec.Visible = True
frsendrec.Height = 1815
frsendrec.Width = 4935
frsendrec.Left = 360
frsendrec.Top = 480

frcode.Visible = True
frcode.Height = 2895
frcode.Width = 3615
frcode.Left = 5400
frcode.Top = 2400

28
frinout.Height = 2895
frinout.Width = 4935
frinout.Left = 360
frinout.Top = 2400
txtinout.Height = 2535
txtinout.Width = 4695
txtinout.Left = 120
txtinout.Top = 240
'***************************************************
Dim name As Integer
For name = 1 To 2
cboname.AddItem CStr(name)
Next name

End Sub

Private Sub cmdclient_Click()

'***************************************************
'to select the option of tcpclient
optionselect = 1
'***************************************************

frmain.Caption = "Client"
frserstatus.Visible = False
frserialsetting.Visible = False

cmdsend.Visible = True
frsendrec.Caption = "Send"
frsendrec.Visible = True
frsendrec.Height = 1815
frsendrec.Width = 4935
frsendrec.Left = 360
frsendrec.Top = 480

frconnect.Visible = True
frconnect.Height = 1815
frconnect.Width = 3615
frconnect.Left = 5400
frconnect.Top = 480

frcode.Visible = True
frcode.Height = 2895
frcode.Width = 3615
frcode.Left = 5400
frcode.Top = 2400

frinout.Visible = True
frinout.Caption = "Data Sent"
frinout.Height = 2895

29
frinout.Width = 4935
frinout.Left = 360
frinout.Top = 2400
txtinout.Height = 2535
txtinout.Width = 4695
txtinout.Left = 120
txtinout.Top = 240
'***************************************************

Select Case cmdconnect.Caption


Case Is = "Connect"
cmdsend.Enabled = False
Case Is = "Disconnect"
cmdsend.Enabled = True
End Select

End Sub

Private Sub cmdexit_Click()

End

End Sub

Private Sub cmdhelp_Click()

frmain.Caption = "Help"

frconnect.Visible = False
frsendrec.Visible = False
frcode.Visible = False
frserialsetting.Visible = False
frserstatus.Visible = False

frinout.Visible = False

End Sub

Private Sub cmdled_Click(Index As Integer)

'*************************************************
If cmdled(Index).BackColor = vbWhite Then
cmdled(Index).BackColor = vbRed
ElseIf cmdled(Index).BackColor = vbRed Then
cmdled(Index).BackColor = vbWhite
End If

30
'*************************************************
'the best code in programe
Dim bit(7) As Integer
Dim todigit As Integer
For p = 0 To 7
If cmdled(p).BackColor = vbWhite Then
bit(p) = 0
Else
bit(p) = 1
End If
Next p
todigit = bit(7) * 2 ^ 7 + bit(6) * 2 ^ 6 + bit(5) * 2 ^ 5 + bit(4) * 2 ^ 4 + bit(3) * 2 ^
3 + bit(2) * 2 ^ 2 + bit(1) * 2 ^ 1 + bit(0) * 2 ^ 0
cbopinnumber.ListIndex = todigit

'*************************************************
End Sub

Private Sub cmdopen_Click()

Dim name As Integer


Dim baud As Integer

Select Case cmdopen.Caption


Case Is = "Open"

name = cboname.ListIndex

Select Case name


Case Is = -1
serial.CommPort = 1
Case Is = 1
serial.CommPort = 2
End Select

baud = cbobaudrate.ListIndex

Select Case baud


Case Is = -1
serial.Settings = "1200,N,8,1"
Case Is = 1
serial.Settings = "2400,N,8,1"
Case Is = 2
serial.Settings = "4800,N,8,1"
Case Is = 3
serial.Settings = "9600,N,8,1"
End Select

'disable DTR(data tranmission)

31
serial.DTREnable = False
'open the port
serial.PortOpen = True

cmdopen.Caption = "Close"
cmdsend.Enabled = True

Case Is = "Close"
serial.PortOpen = False
cmdopen.Caption = "Open"
cmdsend.Enabled = False

End Select

End Sub

Private Sub cmdsend_Click()


Dim PinNumber As Long
PinNumber = cbopinnumber.ListIndex
'**********************************
Select Case optionselect

'tcpclient
Case Is = 1
'Call serverclient.SendData("Client >>> " & cbopinnumber.ListIndex)
Call serverclient.SendData(PinNumber)

txtinout.Text = txtinout.Text & cbopinnumber.ListIndex & vbCrLf & vbCrLf


txtinout.SelStart = Len(txtinout.Text)

'serial communication
Case Is = 3

'send out data


serial.Output = Chr$(PinNumber)
End Select

'**********************************

End Sub

Private Sub cmdserial_Click()

'to select serial communication optioin


optionselect = 3

Select Case cmdopen.Caption


Case Is = "Open"

32
cmdsend.Enabled = False
Case Is = "Close"
cmdsend.Enabled = True
End Select

frmain.Caption = "Serial communication"

frcode.Visible = True
frcode.Height = 2895
frcode.Width = 3615
frcode.Left = 5400
frcode.Top = 2400

frsendrec.Visible = True
frsendrec.Caption = "Send"
cmdsend.Visible = True

frconnect.Visible = False

frserstatus.Visible = False

frserialsetting.Visible = True
frserialsetting.Height = 1815
frserialsetting.Width = 3615
frserialsetting.Left = 5400
frserialsetting.Top = 480

frinout.Visible = True
frinout.Caption = "Sent Data"

'***********************************

Dim baud As Integer


For baud = 0 To 3
cbobaudrate.AddItem CStr((2 ^ baud) * 1200)
Next baud

End Sub

Private Sub cmdserver_Click()

'to select the tcpserver option


optionselect = 2

frmain.Caption = "Server"
frconnect.Visible = False

33
frsendrec.Visible = True
frsendrec.Caption = "Recieved"
cmdsend.Visible = False

frserstatus.Visible = True
frserstatus.Height = 1815
frserstatus.Width = 3615
frserstatus.Left = 5400
frserstatus.Top = 480

frcode.Visible = True
frcode.Height = 2895
frcode.Width = 3615
frcode.Left = 5400
frcode.Top = 2400

frserialsetting.Visible = False

frinout.Visible = True
frinout.Caption = "Recieved Data"
'***************************************

End Sub

Private Sub cmdstatus_Click()

frmain.Caption = "Status"

frconnect.Visible = False
frsendrec.Visible = False
frcode.Visible = False
frserialsetting.Visible = False
frserstatus.Visible = False

frinout.Visible = False

'to tell the status of microcontroller by recieving data from microcontroller


'to tell status of server and client (their ip adresses ,ports# etc)

End Sub

Private Sub Form_Terminate()

'close the connection


Call serverclient.Close

End Sub

34
Private Sub serverclient_Close()

Select Case optionselect

Case Is = 1
'client side
cmdsend.Enabled = False
Call serverclient.Close
txtinout.Text = txtinout.Text & "server closed connection. " & vbCrLf
txtinout.SelStart = Len(txtinout.Text)

cmdconnect.Caption = "Connect"
cmdsend.Enabled = False
cmdserver.Enabled = True

Case Is = 2
'server side
cmdsend.Enabled = False
Call serverclient.Close
txtinout.Text = txtinout.Text & "client closed connection. " & vbCrLf & vbCrLf
txtinout.SelStart = Len(txtinout.Text)
Call serverclient.Listen

cmdlisten.Caption = "Listen"
cmdclient.Enabled = True

End Select

End Sub

Private Sub serverclient_Connect()

cmdsend.Enabled = True
txtinout.Text = "connected to ip adress :" & serverclient.RemoteHostIP &
vbCrLf & "port # " & serverclient.RemotePort & vbCrLf & vbCrLf

End Sub

Private Sub serverclient_ConnectionRequest(ByVal requestID As Long)


'**************************************
If serverclient.State <> sckClosed Then
Call serverclient.Close
End If

'**************************************
cmdsend.Enabled = True
Call serverclient.Accept(requestID)
txtinout.Text = "connection from ip address : " & serverclient.RemoteHostIP &

35
vbCrLf & " port# : " & serverclient.RemotePort & vbCrLf & vbCrLf

'**************************************
End Sub

Private Sub serverclient_DataArrival(ByVal bytesTotal As Long)

Dim message As Long


Dim code As Long

Call serverclient.GetData(message)

If optionselect = 2 Then
Select Case message
Case Is = 2000
code = Val(Text2(0).Text)
Call serverclient.SendData(code)
Case Is = 2100
code = Val(Text2(1).Text)
Call serverclient.SendData(code)
Case Is = 2200
code = Val(Text2(2).Text)
Call serverclient.SendData(code)
Case Is = 3000
code = Val(Text3(0).Text)
Call serverclient.SendData(code)

Case Is = 3100
code = Val(Text3(1).Text)
Call serverclient.SendData(code)

Case Is = 3200
code = Val(Text3(2).Text)
Call serverclient.SendData(code)
Case Else
txtinout.Text = txtinout.Text & message & vbCrLf & vbCrLf
txtinout.SelStart = Len(txtinout.Text)
cbopinnumber.ListIndex = message
serial.Output = Chr$(message)
End Select

ElseIf optionselect = 1 Then


Select Case txt
Case Is = 2000
Text2(0).Text = message
Case Is = 2100
Text2(1).Text = message
Case Is = 2200
Text2(2).Text = message
Case Is = 3000

36
Text3(0).Text = message
Case Is = 3100
Text3(1).Text = message
Case Is = 3200
Text3(2).Text = message
End Select

End If

End Sub

Private Sub serverclient_Error(ByVal Number As Integer, Description As


String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As
String, ByVal HelpContext As Long, CancelDisplay As Boolean)

Dim result As Integer

Select Case optionselect


Case Is = 1 'client
result = MsgBox(Source & ":" & Description, vbOKOnly, "TCP/IP Error")

Case Is = 2 'server
result = MsgBox(Source & ":" & Description, vbOKOnly, "TCP/IP error")

End Select

End Sub

Private Sub Text2_Click(Index As Integer)

If optionselect = 1 Then

Select Case Index


Case Is = 0
txt = 2000
Call serverclient.SendData(txt)
Case Is = 1
txt = 2100
Call serverclient.SendData(txt)
Case Is = 2
txt = 2200
Call serverclient.SendData(txt)
End Select

End If

End Sub

37
Private Sub Text3_Click(Index As Integer)

If optionselect = 1 Then

Select Case Index


Case Is = 0
txt = 3000
Call serverclient.SendData(txt)
Case Is = 1
txt = 3100
Call serverclient.SendData(txt)
Case Is = 2
txt = 3200
Call serverclient.SendData(txt)
End Select

End If

End Sub

3a.5.2 Screen shots of the software in running mode(server side)

When software is started it will start as client but we first click the serial
communication button to open the port.

38
When the serial port is open by clicking the open button then the server can send the
data by itself to the microcontroller but for client to send data to microcontroller the
server should also open itself for communication with client which is done by clicking
the TCP server button as in fig below.

39
The server is listening on port 5000 from the client.

3a.5.3 Screen shoots of the software in running mode (client side)

The figure above shows the client using the software. After typing the IP address of
the server and port number the client clicked the connect button and the button
caption changed to disconnect while the client got connected to server. Now the client
can send the data to the server by selection the correct code from the combo box and
clicking the send button as shown below in which the code 12 is send to the server.

40
The server will receive the data as shown in the following figure.

Note in the figure that combo box as well as the received data frame shows the
received data.

The other feature of the software is the code frame in which different type of loads is
given different code. If the server changes the code of the any load (e.g. light) then the
client can know the new code by simply clicking the textbox as shown in the figures
below in which the server has changed the code of the light from 12 to 20.

41
Code of light changed by server.

Note that the code on client side changed by clicking the textbox.

3a.5.4 Captions and names of different command buttons

The following are the name of different command buttons along with their
captions that will help in understanding the code of the program. The caption
means the text written on the buttons.

42
Caption Name Caption Name
TCP client cmdclient Exit Cmdexit
TCP server cmdserver Send cmdsend
Serial Communication cmdserial Listen cmdlisten
Open cmdopen Connect Cmdconnect
-(In send frame above the cmdled Used to show graphically the picture
send command button) of the signal send

3a.5.5 Names of textboxes and their corresponding functions

Name Function Name Function


textinout To display the data send txtsport Where the port number is
by client and received by written by server to listen
server from client side
txtip Where IP address of text2 Where the code of the
server is written by client electric loads is written to
ON the load
txtcport Where the port number is text3 Where the code of the
written by client to electric loads is written to
communicate with server OFF the load

3a.5.6 Name of the combo boxes and their functions

Name Function
cbopinnumber Used to select data from 0 to 255 to send to microcontroller
cboname Used to select the com port from 0 to 1
cbobaudrate Used to select the baud rate out of available options

Summary

In this chapter we examined the software of the project that


was programmed in visual basic. We also discussed the different
controls of VB which can help us in the project (i.e. Winsock
control and MS Comm. control. The code of the project along with
screen shoots are also given that will help in understanding the
project.

43
References

Visual Basic 6 How to program


By Deitel & Deital
T.R. Nieto

44
Chapter – 3B

Software of the project


(Using HTML & ASP)

44
3b.1 Introduction
Active Server Page ASP is used in World Wide Web Hypertext Markup
Language (HTML) documents to enhance the functionality of a web page displayed
in a web browser (e.g. Internet Explorer) and used on Microsoft’s Internet
Information Server (IIS) to enhance the functionality of server-side applications. Let
us first discuss HTML to facilitate in understanding the software of the project done
in HTML and ASP.

3b.1.1 Introduction to HTML & Microsoft Front Page

The basic documents of World Wide Web are called Pages and are written in
HTML. Pages can either be part of a web, or they can stand-alone. An HTML
document consists of text that specifies the content of a web page to be displayed
and the format in which to display it. Most of the formatting is specified by using the
pairs of tags of the form <TAGNAME> and </TAGNAME> that indicate the start and
end of the format in the document e.g. the tags <HTML> and </HTML> are normally
used at the beginning and end of an HTML document to specify where the HTML
formatting begins and ends respectively. The code of HTML file is written in and text
editor like notepad and is saved with extension html e.g. demo.html is an HTML file.
Writing code in HTML for web page designing is hard and require
professional to do it thus Microsoft introduces software called FrontPage, which is
used for web designing. We do not need to know HTML to use Microsoft FrontPage.
While we edit pages as in any Microsoft Office software (e.g. MS Word or Power
Point — typing and formatting text, and adding graphics, tables, and other page
elements —) FrontPage adds the HTML tags in the background i.e. FrontPage do
the coding for us by itself. Our page is displayed, as it would appear in a Web
browser. However, we can also do the HTML coding in FrontPage if we want to by
switching to HTML tab in page view.
To help in creating professional-looking and well-designed web pages,
FrontPage provides several page templates so we can quickly create pages with a
variety of layouts and functions. For example, we can use a FrontPage template to
create a two-column page or a page with a search form. We can also use one of
several themes to create pages with a consistent design. A theme contains unified
design elements with a color scheme, including fonts, graphics, backgrounds,
navigation bars, horizontal lines, and other page elements.
If someone prefers to design and lay out pages himself, he can start with a
blank page.
Some of the features of FrontPage are.
™ Use frames, tables, or absolute positioning to precisely position text and
graphics on a page.
™ Add page elements, such as text, graphics, page banners, tables, forms,
hyperlinks, banner ads, marquees, hover buttons, time stamps, hit counters.
™ Format text by applying styles or using style sheets.
™ Animate page elements and set page transitions for lively pages.
™ Set the background color, picture, or sound.
™ Create your own page templates.

45
3b.1.2 Introduction to ASP
ASP stands for Active Server Pages. ASP is a program that runs inside IIS.
An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file are
executed on the server. An ASP file is just the same as an HTML file but has the file
extension ".asp". There is different between HTML and ASP file i.e. when a browser
(on client side) requests an HTML file, the server returns the file while when a
browser requests an ASP file, IIS passes the request to the ASP engine. The ASP
engine reads the ASP file, line by line, and executes the scripts in the file. Finally,
the ASP file is returned to the browser as plain HTML thus provides security since
your ASP code cannot be viewed from the browser. ASP also responds to user
queries or data submitted from HTML forms. An ASP file normally contains HTML
tags, just like an HTML file. However, an ASP file can also contain server scripts,
surrounded by the delimiters <% and %>. Server scripts are executed on the
server, and can contain any expressions, statements, procedures, or operators valid
for the scripting language you prefer to use.
To get further information on ASP see the whole chapter dedicated to ASP

3b.2 Software of the project


Microsoft FrontPage is used in designing the web page. The different figures
below give some idea of how to design web page in FrontPage.

46
The previous figure shows the page view when the normal tab is selected. In figure
we can see that the web page is designed by inserting
™ The background color using page properties
™ Marquee with behavior as scroll and the text
CON TROLLIN G OF DEVICES THROU GH INT ERN E T U S ING 8 051
MIC ROCONT ROL L ER
™ Horizontal lines of yellow color
™ Form with one line textbox
™ And the normal text as shown in figure above with some as hyperlinks e.g.
the text thesis is hyperlink to MS Word file, which has all the thesis of the
project.
Note that the send data button is inserted along with one line textbox and is of input type
“submit” they are not the push buttons i.e. of input type “button”.

The figure below shows the page view when the HTML tab is selected and we can
see the HTML coding of the web page that was easily designed in FrontPage.

After the designing of the web page we include the ASP code in it. This is done by
writing the ASP code in HTML code but ASP code is enclosed in <% ------ %> tab
indicating that it is ASP code. The whole code thus will have ASP code written in
HTML code and is give as follow.

47
3b.2.1 HTML and ASP code of the web page

<HTML>

<HEAD>

<TITLE>
"FINAL YEAR PROJECT"
</TITLE>

</HEAD>

<BODY bgcolor="#99CCFF">
<p align="center">
<marquee style="font-size: 14pt; color: #FFFFFF; font-weight: bold; background-color:
#0000FF" scrolldelay="60" bgcolor="#FFFFFF" align="middle"
scrollamount="3">CONTROLLING
OF DEVICES THROUGH INTERNET USING 8051 MICROCONTROLLER</marquee>

&nbsp;
<p align="center"><font face="Comic Sans MS"><span style="text-transform:
uppercase"><font size="1"><u>software
( in VB )</u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<u>Thesis</u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<u>
presentations</u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<u>help</u></font>&nbsp;</span></font></p>
<hr color="#FFFF00">
<p align="center"><font face="Comic Sans MS"><span style="text-transform:
uppercase">&nbsp;&nbsp;</span></font>&nbsp;&nbsp;&nbsp;&nbsp;
<FORM METHOD="POST">
<p align="center">
ENTER CORRECT CODE TO ON/OFF THE LOAD
<p align="center">
&nbsp;
<INPUT TYPE="TEXT" NAME="FNAME" SIZE="20"/>
<INPUT TYPE="SUBMIT" VALUE="SEND DATA"/>

</FORM>
<p>&nbsp;</p>
<hr color="#FFFF00">

<%
DIM NUM
NUM=REQUEST.FORM("FNAME")

RESPONSE.WRITE("<p align=center>YOU HAVE SEND "& NUM)


dim fs,txt
set fs=Server.CreateObject("Scripting.FileSystemObject")
Set txt = fs.OpenTextFile("C:\input.txt", 2, True)

48
txt.Write NUM
SET fs=NOTHING
SET txt=NOTHING
%>

</BODY>
</HTML>

After writing the code the program is saved in C:\Inetpub\wwwroot\project with any
name but having “.asp” extension.
Now the file can be opened for checking using web browser by typing the address
as http://localhost/PROJECT/FINAL.ASP then the page will appear will appear as
follow.

When we type any number in the text box and click SEND DATA button then the
above software will first create and then send that number in to the text file
C:\input.txt file.
In following figure the user has sent the number 12 and then the textbox is cleaned
while the message come on the screen “YOU HAVE SEND 12 “

49
After loading the website on the Internet the server will receive the data from the
client who will type the address of the site and then typing the correct code. But
there is still one thing left. The data received by server is in the text file input.txt so
we have to transfer it to the microcontroller which is done by using a software made
in VB and the procedures is same as discussed in previous chapter.

The code of the software is as under.


Private Sub Form_Load()

serial.CommPort = 1
serial.Settings = "4800,N,8,1"
'disable DTR(data tranmission)
serial.DTREnable = False
'open the port
serial.PortOpen = True

End Sub

Private Sub Text1_Change()

Dim message As Integer


Dim txt As String
txt = Text1.Text
message = Val(Text1.Text)

50
If txt <> "" Then
If message >= 0 Then
If message <= 15 Then
serial.Output = Chr$(message)
End If
End If
End If

End Sub

Private Sub Timer1_Timer()


Call checkfile
End Sub

Private Sub checkfile()


rt.LoadFile ("c:\input.txt")
Text1.Text = rt.Text
End Sub

The pictures of the software in design and running modes are as follow.

51
In above figure nothing is visible as there is no need to be.
The following is the brief explanation of the software for serial communication.
The timer with the name Timer1 is used to check the input.txt file after each 100
milliseconds. The MS Comm. control with name serial is used to send data serially
to microcontroller. The RichTextBox with name rt is used to take data from the
input.txt file. It can be selected similarly as MS Comm. control. The textbox with
name Text1 is used to take the data from RichTextBox so that it can be send to
microcontroller. Note that as soon as text in textbox is changed it is sent to
microcontroller.

52
Summary

In this chapter we examined the software of the project that was


programmed mainly in HTML & ASP while the serial communication with
microcontroller was done in visual basic. We also discussed the
Microsoft FrontPage and how it makes our work easy while doing the
web page designing. The code of the project along with screen shoots
are also given that will help in understanding the project.

References

¾ Microsoft FrontPage Help file

¾ http://www.w3schools.com/asp/default.asp

¾ Visual Basic 6 How to program


By Deitel & Deital
T.R. Nieto

53
Chapter - 4

Hardware of the Project

54
4.1 Introduction

Up to now we talked in detail about how to make communication possible


between client and server. But we haven’t talked much about the communication
between server and microcontroller. As we know that client and server are
connected with each other through Internet by telephone line or any other way
and we designed software for making their communication possible. Similarly the
server and the microcontroller are connected to each other through a cable (DB9
Connecter) using serial communication and software is designed for serial
communication between microcontroller and server. But microcontroller is a chip
with 40 pins and how can we make microcontroller compatible with computer is
the big task.
In this chapter we will discuss what should be done on server side
particularly concentrating on hardware so that the server can communicate with
microcontroller serially. Also we will discuss how to connect the home appliances
with microcontroller so that they are being controlled by microcontroller signals,
which are basically the client signals.

4.2 Serial communication with microcontroller


As we know that 8051 microcontroller is a 40-pin device but it has two pins
that are used specifically for transferring and receiving data serially. These pins
are TXD (pin 11 or p3.1) and RXD (pin 10 or p3.0) used for transmission and
reception of data (respectively) serially. These pins will be used for serial
communication.
Serial data communication uses two methods: synchronous and
synchronous
™ The synchronous method transfers a block of data at a time.
™ The asynchronous serial communication transfer single byte at a time.
It is possible to write software to use either of these methods, but the
programs can be tedious and long. For this reason there is special IC chip made
by manufacturers for serial communication named as UART (universal
asynchronous receiver-transmitter) and USART (universal synchronous-
asynchronous receiver-transmitter). The 8051 has built-in UART chip.

To allow compatibility among data communication equipment made by


various manufacturers an interfacing standard called RS232 was set by the EIA.
This standard is used in PCs and other electronic equipments, but RS232 is not
TTL compatible. In RS232 logic 1 is represented by –3 to –25V while the logic 0
is represented by +3 to +25V making –3 to +3V undefined. Thus to connect any
RS232 to microcontroller we use voltage converters such as MAX232 to convert
the TTL logic levels to RS232 voltage levels and vice versa. Other advantage of
MAX232 chip is that it uses a +5 volt power source, which is the same as the
source voltage for the 8051.The MAX232 has two sets of line drivers for
transferring and receiving data, i.e. pins 10 and 11 are used for transmitting and
pins 9 and 12 are used for reception of data. Only one set is used for 8051 and

55
the other set is left unused. E.g. pins 9 and 10 are used with TXD and RXD of
8051 and second set is left unused in figure below. The capacitors widely used
are of 22-microfarad value.
The RS232 cables are commonly referred to as DB25 connectors having 25
pins but as not all pins are used in PCs thus IBM introduced the DB9 connectors
having 9 pins used in PCs.

4.2.1 Circuit diagram for serial communication


VCC

16
U3
8 1
C6
RS232 7
5 3
9 C5
4 2 4
8 MAX232 C4
3 5
7
2 TXD 10
6 RXD 9 6
1
Microcontroller C3
15
side or TTL side

Schematic circuit of RS232

4.2.2 Programming microcontroller for receiving data serially


After the above circuit formed and connected to microcontroller then the
microcontroller can receive and transmit data serially from the computer i.e.
server but the microcontroller has to be programmed to do that which is done
using the assembly language. The program is then written inside the
microcontroller chip using the burner. The steps of the program and the program
are given below.

In the program below the following steps have been taken:

1. The TMOD register is loaded with the value 20H=00100000, indication the
use of timer 1 in mode 2 (8bit auto reload) to set the baud rate
2. TH1 is loaded with –6 decimal (i.e. 4800 baud rate while assuming the
XTAL=11.0596).
3. The SCON register is loaded with the value 50H=01010000, indication
serial mode 1, where 8-bit data is framed with start and stop bits. Also by
this way RxD is enabled.
4. TR1 is set to 1 to start timer 1.

56
5. CLR TI command is used to clear SCON.1 flag (flag for transmission).
6. Character to be transmitted is written in SBUF register and received are
also put by microcontroller in SBUF register
7. TI flag is monitored by JNB TI,label to see if character is transferred.
8. To start next character we go to step five again.

The program is shown below:


; Program for serial communication
; 4800 baud rate

MOV P0,#00H
MOV TMOD,#20H ;TIMER1, MODE 2 (AUTO RELOAD)
MOV TH1,#-6 ;4800 BAUD RATE
MOV SCON,#50H ;8-BIT, 1 STOP, REN (RECIEVE ENABLE)
SETB TR1 ;START TIMER 1

;;;;;;;;; receive from PC ;;;;;;;;

HERE: JNB RI,HERE ; WAIT FOR DATA TO COME


MOV A,SBUF ;SAVE INCOMMING BYTE IN A REGISTER
MOV P0,A ;SEND TO PORT 0
CLR RI ;GET READY TO RECEIVE NEXT BYTE
SJMP HERE ;JUMP TO LABEL “HERE”
END

4.3 Power Supply circuit for microcontroller


The microcontroller needs Adapter of the following electrical rating and is the
main source of supply:
Input: 220 V AC
Output: 20 V DC
The output of the adapter is connected to the “AC IN “ jack on the board, which
has the capability to get AC input or DC input. In case of AC input the AC is
converted to DC through a on board rectifier “BRIDGE" and filter circuit
comprising capacitors “ C1, C2, C3 “. If adapter is not available DC input (20 V
DC) can also be applied to the connector “DC IN” on board through a bench top
power supply.
After applying the proper rated input to the board, it is passed through on board
voltage regulators U1 (7812) and U2 (7805) for 12 VDC and 5 VDC respectively.
These voltages are used for proper functioning of the board. LED0 will glow up if
board supply is proper.

The following diagrams show the circuit that is essential in any microcontroller.

57
DC IN

DC IN 12V
2
1
U1 U2

1 3 1 3 VCC
V V V V
I OU IN OUT
+
AC1 + GND + GND +

AC IN +
C0 2 C1 2 C2
1
BRIDGE
2

AC2

4.4 Reset circuit for microcontroller


There can be two types of resets i.e. Automatic Reset and manual Reset.
Automatic reset is obtained when power is applied to the board, which provides
Vcc to the RST pin of the controller through 10µF capacitor and to GND through
10KΩ resistor, providing the Vcc rise time does not exceed 1ms.Manual Reset is
activated using a switch “ RESET “. The schematic of Reset circuit is shown in
Figure.
VCC VCC
C10

R7 RESET

R6
Reset

58
4.5 Relays
Relays are extremely useful when we have a need to control a large
amount of current and/or voltage with a small electrical signal. The relay coil,
which produces the magnetic field, may only consume fractions of a watt of
power, while the contacts closed or opened by that magnetic field may be able to
conduct hundreds of times that amount of power to a load. In effect, a relay acts
as a binary (on or off) amplifier.

In the figure shown, the relay's coil is energized by the low-voltage (12 VDC)
source, while the single-pole, single-throw (SPST) contact interrupts the high-
voltage (480 VAC) circuit. It is quite likely that the current required to energize the
relay coil will be hundreds of times less than the current rating of the contact.
Typical relay coil currents are well below 1 amp, while typical contact ratings for
industrial relays are at least 10 amps.
One relay coil/armature assembly may be used to actuate more than one set of
contacts. Those contacts may be normally open, normally closed, or any
combination of the two. As with switches, the "normal" state of a relay's contacts
is that state when the coil is de-energized, just as you would find the relay sitting
on a shelf, not connected to any circuit.
Relay contacts may be open-air pads of metal alloy, mercury tubes, or even
magnetic reeds, just as with other types of switches. The choice of contacts in a
relay depends on the same factors, which dictate contact choice in other types of
switches. Open-air contacts are the best for high-current applications, but their
tendency to corrode and spark may cause problems in some industrial
environments. Mercury and reed contacts are sparkless and won't corrode, but
they tend to be limited in current-carrying capacity.

59
Shown here is small relay that take up to 12V dc to control the 220 V ac voltages:

Aside from the ability to allow a relatively small electric signal to switch a
relatively large electric signal, relays also offer electrical isolation between coil
and contact circuits. This means that the coil circuit and contact circuit(s) is
electrically insulated from one another. One circuit may be DC and the other AC
(such as in the example circuit shown earlier), and/or they may be at completely
different voltage levels, across the connections or from connections to ground.
In our project the input to the relay is taken from the pin of microcontroller and
thus the relay is made ON/OFF and hence the load is controlled.

60
Summary

In this chapter we examined the hardware of the project specially


the hardware related to serial communication between
microcontroller and server. We have also discussed briefly about
relays that are used to switch on and off the load. Some circuit
diagrams for making microcontroller kit are also given along with
explanation.

References

¾ The 8051 Microcontroller and Embedded systems


By Mohammad Ali Mazidi
Janice Gillespie Mazidi

¾ The 8051 Microcontroller (3rd Edition)


By I. Scott Mackenzie

¾ http://www.ibiblio.org/obp/electricCircuits/Digital/DIGI_5.html

Or Lessons in electric circuits volume iv – digital


By Tony R.kuphaldt

61
Notes for:

Visual Basic 6.0


1 What is Visual Basic?
Visual Basic is a tool that allows us to develop Windows (Graphic User
Interface - GUI) applications. The applications have a familiar appearance to the
user.
Visual Basic is event-driven; meaning code remains idle until called upon to
respond to some event (button pressing, menu selection...). An event processor
governs Visual Basic. Nothing happens until an event is detected. Once an
event is detected, the code corresponding to that event (event procedure) is
executed. Program control is then returned to the event processor.

1.1 Some Features of Visual Basic


™ Full set of objects - you 'draw' the application
™ Lots of icons and pictures for your use
™ Response to mouse and keyboard actions
™ Clipboard and printer access
™ Full array of mathematical, string handling, and graphics functions
™ Can handle fixed and dynamic variable and control arrays
™ Sequential and random access file support
™ Useful debugger and error-handling facilities
™ Powerful database access tools
™ ActiveX support
™ Package & Deployment Wizard makes distributing your applications
simple

1.2 Structure of a Visual Basic Application


VB Application (Project) is made up of:
™ Forms - Windows that we create for user interface
™ Controls - Graphical features drawn on forms to allow user
interaction (text boxes, labels, scroll bars, command buttons, etc.)
(Forms and Controls are objects.)
™ Properties - Every characteristic of a form or control is specified by
a property. Example properties include names, captions, size,
color, position, and contents. Visual Basic applies default
properties. We can change properties at design time or run time.
™ Methods - Built-in procedure that can be invoked to impart some
action to a particular object.
™ Event Procedures - Code related to some object. This is the code
that is executed when a certain event occurs.
™ General Procedures - Code not related to objects. This code must
be invoked by the application.
™ Modules - Collection of general procedures, variable declarations,
and constant definitions used by application.

1
2 Steps in Developing Application
There are three primary steps involved in building a Visual Basic application:

1) Draw the user interface


2) Assign properties to controls
3) Attach code to controls
We’ll look at each step.

2.1 Drawing the User Interface and Setting Properties


Visual Basic operates in three modes.

™ Design mode - used to build application


™ Run mode - used to run the application
™ Break mode - application halted and debugger is available

We focus here on the design mode.

Six windows appear when we start Visual Basic.

™ The Main Window consists of the title bar, menu bar, and toolbar.
The title bar indicates the project name, the current Visual Basic
operating mode, and the current form. The menu bar has drop-down
menus from which you control the operation of the Visual Basic
environment. The toolbar has buttons that provide shortcuts to some
of the menu options. The main window also shows the location of the
current form relative to the upper left corner of the screen and the
width and length of the current form.

™ The Form Window is central to developing Visual Basic applications.


It is where you draw your application.

2
™ The Toolbox is the selection menu for controls used in your
application.

Pointer Picture Box


Label Text Box
Frame Command Button
Check Box Option Button
Combo Box List Box
Horizontal Scroll Vertical Scroll Bar
Timer Drive List Box
Directory List Box File List Box
Shapes Lines
Image Box Data Tool
Object Linking

™ The Properties Window is used to establish initial property values for


objects. The drop-down box at the top of the window lists all objects in
the current form. Two views are available: Alphabetic and
Categorized. Under this box are the available properties for the
currently selected object.

3
™ The Form Layout Window shows where (upon program execution)
your form will be displayed relative to your monitor’s screen:

™ The Project Window displays a list of all forms and modules making
up your application. You can also obtain a view of the Form or Code
windows (window containing the actual Basic coding) from the Project
window.

4
As mentioned, the user interface is ‘drawn’ in the form window. There are two
ways to place controls on a form:

1. Double-click the tool in the toolbox and it is created with a default size
on the form. You can then move it or resize it.
2. Click the tool in the toolbox, and then move the mouse pointer to the
form window. The cursor changes to a crosshair. Place the crosshair
at the upper left corner of where you want the control to be, press the
left mouse button and hold it down while dragging the cursor toward
the lower right corner. When you release the mouse button, the
control is drawn.

To move a control you have drawn, click the object in the form window and drag
it to the new location. Release the mouse button.
To resize a control, click the object so that it is select and sizing handles appear.
Use these handles to resize the object.

Click here Use sizing


to move handles to
resize

5
2.2 Assign properties to controls
Each form and control has properties assigned to it by default when we start
up a new project. There are two ways to display the properties of an object. The
first way is to click on the object (form or control) in the form window. Then, click
on the Properties Window or the Properties Window button in the tool bar. The
second way is to first click on the Properties Window. Then, select the object
from the Object box in the Properties Window. The figure below shows the
Properties Window.

The drop-down box at the top of the


Properties Window is the Object box. It
displays the name of each object in the
application as well as its type. This
display shows the Form object. The
Properties list is directly below this box.
In this list, we can scroll through the list
of properties for the selected object. We
may select a property by clicking on it.
We can change the properties by typing
a new value or choosing from a list of
predefined settings (available as a drop
down list). Properties can be viewed in
two ways: Alphabetic and
Categorized.

A very important property for each


object is its name. The name is used by
Visual Basic to refer to a particular
object in code.
Object names can be up to 40
characters long, must start with a letter
must contain only letters, numbers, and
the underscore (_) character. Names
are used in setting properties at run time
and also in establishing procedure names for object events.

2.3 Attach code to controls


We’re now ready to attach code to our application. As objects are added to the
form, Visual Basic automatically builds a framework of all event procedures. We
simply add code to the event procedures we want our application to respond to.
Attaching code to control is the programming side of the visual basics and
requires good programming skills. Thus we will understand different
programming terminologies and techniques used in visual basic to attach code to
controls after drawing user interface and setting properties (we will mainly focus
on attaching effective code to control).

6
3 Variables
Variables are used by Visual Basic to hold information needed by our
application. Rules used in naming variables are:

™ No more than 40 characters


™ They may include letters, numbers, and underscore (_)
™ The first character must be a letter
™ We cannot use a reserved word (word needed by Visual Basic)
Visual Basic Data Types
Data Type Suffix Range
Boolean None True or False
Integer % -32768 to 32767
Long (Integer) & -2147483648 to 2147483647
Single (Floating) ! -3.402823E38 to –1.4013E-45 (-ve)
3.402823E38 to 1.4013E-45 (+ve)
Double (Floating) # -1.798E308 to –4.940E-324 (-ve)
1.798E308 to 4.940E-324 (+ve)
Currency @
Date None
Object None
String $ 0 to 2000000000 characters
Variant None Any value within the range above

3.1 Variable Declaration


There are three ways for a variable to be typed (declared):
1. Default
2. Implicit
3. Explicit

™ If variables are not implicitly or explicitly typed, they are assigned the variant
type by default. The variant data type is a special type used by Visual Basic
that can contain numeric, string, or date data.

™ To implicitly type a variable, use the corresponding suffix shown above in


the data type table. For example,
TextValue$ = "This is a string"
creates a string variable, while

Amount% = 300
creates an integer variable.

7
™ There are many advantages to explicitly typing variables. Primarily, we
insure all computations are properly done, mistyped variable names are
easily spotted, and Visual Basic will take care of insuring consistency in
upper and lower case letters used in variable names. Because of these
advantages, and because it is good programming practice, we will
explicitly type all variables.

To explicitly type a variable, we must first determine its scope. There are four
levels of scope:

™ Procedure level
™ Procedure level, static
™ Form and module level
™ Global level

Within a procedure, variables are declared using the Dim statement:


Dim MyInt as Integer
Dim MyDouble as Double
Dim MyString, YourString as String
Procedure level variables declared in this manner do not retain their value once a
procedure terminates.

To make a procedure level variable retain its value upon exiting the procedure,
replace the Dim keyword with Static:
Static MyInt as Integer
Static MyDouble as Double

Form (module) level variables retain their value and are available to all
procedures within that form (module). Form (module) level variables are
declared in the declarations part of the general object in the form's (module's)
Code window. The Dim keyword is used:
Dim MyInt as Integer
Dim MyDate as Date

Global level variables retain their value and are available to all procedures within
an application. Module level variables are declared in the declarations part of
the general object of a module's code window. (It is advisable to keep all global
variables in one module.) Use the Global keyword:
Global MyInt as Integer
Global MyDate as Date

What happens if we declare a variable with the same name in two or more
places? More local variables shadow (are accessed in preference to) less local
variables. For example, if a variable MyInt is defined as Global in a module and
declared local in a routine MyRoutine, while in MyRoutine, the local value of
MyInt is accessed. Outside MyRoutine, the global value of MyInt is accessed.

8
4 Visual Basic Statements and Expressions
The simplest statement is the assignment statement. It consists of a
variable name, followed by the assignment operator (=), followed by some sort of
expression e.g.

StartTime = Now
Explorer.Caption = "Captain Spaulding"
BitCount = ByteCount * 8
Energy = Mass * LIGHTSPEED ^ 2
NetWorth = Assets - Liabilities

The assignment statement stores information.

™ If a statement is very long, it may be continued to the next line using the
continuation character, an underscore (_). Example:

Months = Log(Final * IntRate / Deposit + 1) _


/ Log(1 + IntRate)

™ Comment statements begin with the keyword Rem or a single quote ('). For
example:

Rem This is a remark


' This is also a remark
x=2*y ' another way to write a remark or comment

5 Visual Basic Operators


The simplest operators carry out arithmetic operations. These operators in
their order of precedence are:

Operator Operation
^ Exponentiation
*/ Multiplication and division
\ Integer division (truncates)
Mod Modulus
+- Addition and subtraction

To concatenate two strings, use the & symbol or the + symbol:

lblTime.Caption = "The current time is" & Format(Now, “hh:mm”)


txtSample.Text = "Hook this “ + “to this”

9
There are six comparison operators in Visual Basic:
Operator Comparison
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
= Equal to
<> Not equal to

The result of a comparison operation is a Boolean value (True or False).

Three logical operators used mostly are:

Operator Operation
Not Logical not
And Logical and
Or Logical or

The Not operator simply negates an operand.

The And operator returns a True if both operands are True. Else, it returns a
False.

The Or operator returns a True if either of its operands is True, else it returns a
False.

Logical operators follow arithmetic operators in precedence.

6 Visual Basic Functions

Visual Basic offers a rich assortment of built-in functions. Some examples


are:

Function Value Returned


Abs Absolute value of a number
Asc ASCII or ANSI code of a character
Chr Character corresponding to a given ASCII or ANSI code
Cos Cosine of an angle
Date Current date as a text string
Format Date or number converted to a text string
Left Selected left side of a text string
Len Number of characters in a text string

10
Mid Selected portion of a text string
Now Current time and date
Right Selected right end of a text string
Rnd Random number
Sin Sine of an angle
Sqr Square root of a number
Str Number converted to a text string
Time Current time as a text string
Timer Number of seconds elapsed since midnight
Val Numeric value of a given text string

Example (Stopwatch Application)


Drawing Controls
™ Start a new project. The idea of this project is to start a timer, then stop
the timer and compute the elapsed time (in seconds).
™ Place three command buttons and six labels on the form. Move and size
the controls and form so it looks something like this:

™ A convention has been established for naming Visual Basic objects. This
convention is to use a three-letter prefix (depending on the object)
followed by a name you assign. A few of the prefixes are (we’ll see more
as we progress):

Object Prefix Example


Form frm frmWatch
Command Button cmd, btn cmdExit, btnStart
Label lbl lblStart, lblEnd
Text Box txt txtTime, txtName
Menu mnu mnuExit, mnuSave
Check box chk chkChoice

11
Setting Properties
Set properties of the form, three buttons, and six labels:

Form1:
BorderStyle 1-Fixed Single
Caption Stopwatch Application
Name frmStopWatch

Command1:
Caption &Start Timing
Name cmdStart
Command2:
Caption &End Timing
Name cmdEnd

Command3:
Caption E&xit
Name cmdExit

Label1:
Caption Start Time

Label2:
Caption End Time

Label3:
Caption Elapsed Time

Label4:
BorderStyle 1-Fixed Single
Caption [Blank]
Name lblStart

Label5:
BorderStyle 1-Fixed Single
Caption [Blank]
Name lblEnd

Label6:
BorderStyle 1-Fixed Single
Caption [Blank]
Name lblElapsed

In the Caption properties of the three command buttons, notice the


ampersand (&). The ampersand precedes a button's access key. That is, in
addition to clicking on a button to invoke its event, you can also press its

12
access key (no need for a mouse). The access key is pressed in conjunction
with the Alt key. Hence, to invoke 'Begin Timing', you can either click the
button or press Alt+B. Note in the button captions on the form, the access
keys appear with an underscore (_).

Our form should now look something like this

Attaching Code
All that’s left to do is attach code to the application. We write code for every
event a response is needed for. In this application, there are three such events:
clicking on each of the command buttons.

Double-click anywhere on the form to open the code window. Or, select ‘View
Code’ from the project window.

Click the down arrow in the Object box and select the object named (general).
The Procedure box will show (declarations). Here, you declare three form level
variables:
Option Explicit
Dim StartTime As Variant
Dim EndTime As Variant
Dim ElapsedTime As Variant

The Option Explicit statement forces us to declare all variables. The other lines
establish StartTime, EndTime, and ElapsedTime as variables global within the
form.

Select the cmdStart object in the Object box. If the procedure that appears is
not the Click procedure, choose Click from the procedure box. Type the
following code which begins the timing procedure. Note the Sub and End Sub
statements are provided for you:
Sub cmdStart_Click ()

13
‘Establish and print starting time
StartTime = Now
lblStart.Caption = Format(StartTime, "hh:mm:ss")
lblEnd.Caption = ""
lblElapsed.Caption = ""
End Sub

In this procedure, once the Start Timing button is clicked, we read the current
time and print it in a label box. We also blank out the other label boxes. In the
code above (and in all code in these notes), any line beginning with a single
quote (‘) is a comment. You decide whether you want to type these lines or not.
They are not needed for proper application operation.

Now, code the cmdEnd button.


Sub cmdEnd_Click ()
‘Find the ending time, compute the elapsed time
‘Put both values in label boxes
EndTime = Now
ElapsedTime = EndTime - StartTime
lblEnd.Caption = Format(EndTime, "hh:mm:ss")
lblElapsed.Caption = Format(ElapsedTime, "hh:mm:ss")
End Sub

Here, when the End Timing button is clicked, we read the current time (End
Time), compute the elapsed time, and put both values in their corresponding
label boxes.

Finally code the cmdExit button.


Sub cmdExit_Click ()
End
End Sub

This routine simply ends the application once the Exit button is clicked.

Save and to Run your application


™ To run the application Click the Run button on the toolbar, or by pressing
<f5>.

™ When saving Visual Basic applications, you need to be concerned with


saving both the forms (.FRM) and modules (.BAS) and the project file
(.VBP). In either case, make sure you are saving in the desired directory.
The current directory is always displayed in the Save window. Use
standard Windows techniques to change the current directory.

There are four Save commands available under the File menu in Visual Basic:

14
Save [Form Name] Save the currently selected form or module with the current
name. The selected file is identified in the Project window.
Save [Form Name] As Like Save File, however you have the option to
change the file name
Save Project Saves all forms and modules in the current project using
their current names and also save the project file.
Save Project As Like Save Project, however you have the option to change
file names. When you choose this option, if you have not saved your forms or
modules, you will also be prompted to save those files. I always use this for new
projects.

7 Visual Basic Branching - If Statements


Branching statements are used to cause certain actions within a program if a
certain condition is met.

The simplest is the If/Then statement:


If Balance - Check < 0 Then Print "You are overdrawn"
Here, if and only if Balance - Check is less than zero, the statement “You are
overdrawn” is printed.

You can also have If/Then/End If blocks to allow multiple statements:


If Balance - Check < 0 Then
Print "You are overdrawn"
Print "Authorities have been notified"
End If
In this case, if Balance - Check is less than zero, two lines of information are
printed.

Or, If/Then/Else/End If blocks:


If Balance - Check < 0 Then
Print "You are overdrawn"
Print "Authorities have been notified"
Else
Balance = Balance - Check
End If
Here, the same two lines are printed if you are overdrawn (Balance - Check < 0),
but, if you are not overdrawn (Else), your new Balance is computed.

Or, we can add the ElseIf statement:


If Balance - Check < 0 Then
Print "You are overdrawn"
Print "Authorities have been notified"
ElseIf Balance - Check = 0 Then

15
Print "Whew! You barely made it"
Balance = 0
Else
Balance = Balance - Check
End If
Now, one more condition is added. If your Balance equals the Check amount
(ElseIf Balance - Check = 0), a different message appears.

In using branching statements, make sure you consider all viable possibilities in
the If/Else/End If structure. Also, be aware that each If and ElseIf in a block is
tested sequentially. The first time an If test is met, the code associated with that
condition is executed and the If block is exited. If a later condition is also True, it
will never be considered.

8 Visual Basic Looping


Looping is done with the Do/Loop format. Loops are used for operations are
to be repeated some number of times. The loop repeats until some specified
condition at the beginning or end of the loop is met.

™ Do While/Loop Example:
Counter = 1
Do While Counter <= 1000
Debug.Print Counter
Counter = Counter + 1
Loop
This loop repeats as long as (While) the variable Counter is less than or equal to
1000. Note a Do While/Loop structure will not execute even once if the While
condition is violated (False) the first time through. Also note the Debug.Print
statement. What this does is print the value Counter in the Visual Basic Debug
window.
™ Do Until/Loop Example:
Counter = 1
Do Until Counter > 1000
Debug.Print Counter
Counter = Counter + 1
Loop
This loop repeats Until the Counter variable exceeds 1000. Note a Do
Until/Loop structure will not be entered if the Until condition is already True on
the first encounter.

™ Do/Loop While Example:


Sum = 1
Do
Debug.Print Sum

16
Sum = Sum + 3
Loop While Sum <= 50
This loop repeats While the Variable Sum is less than or equal to 50. Note,
since the While check is at the end of the loop; a Do/Loop While structure is
always executed at least once.

™ Do/Loop Until Example:


Sum = 1
Do
Debug.Print Sum
Sum = Sum + 3
Loop Until Sum > 50
This loop repeats Until Sum is greater than 50. And, like the previous example, a
Do/Loop Until structure always executes at least once.

Note: Make sure to get out of a loop! Infinite loops are never nice. If you get into
one, try Ctrl+Break. That sometimes works - other times the only way out is
rebooting your machine!

The statement Exit Do will get you out of a loop and transfer program control to
the statement following the Loop statement.

9 Visual Basic Counting


Counting is accomplished using the For/Next loop e.g.
For I = 1 to 50 Step 2
A=I*2
Debug.Print A
Next I
In this example, the variable I initialize at 1 and with each iteration of the For/Next
loop variable I is incremented by 2 (Step). This looping continues until I variable
become greater than or equal to its final value (50). If Step is not included, the
default value is 1. Negative values of Step are allowed.
We can exit a For/Next loop using an Exit For statement. This will
transfer program control to the statement following the Next statement.

17
Notes for:

ACTIVE SERVER PAGE


(ASP)
1. Introduction to ASP

1.1 What is ASP?


An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file
are executed on the server
• ASP stands for Active Server Pages
• ASP is a program that runs inside IIS
• IIS stands for Internet Information Services
• IIS comes as a free component with Windows 2000
• IIS is also a part of the Windows NT 4.0 Option Pack
• The Option Pack can be downloaded from Microsoft
• PWS is a smaller - but fully functional - version of IIS
• PWS can be found on your Windows 95/98 CD

1.2 ASP Compatibility


• ASP is a Microsoft Technology
• To run IIS you must have Windows NT 4.0 or later
• To run PWS you must have Windows 95 or later
• ChiliASP is a technology that runs ASP without Windows OS
• InstantASP is another technology that runs ASP without Windows

1.3 What is an ASP File?


• An ASP file is just the same as an HTML file
• An ASP file can contain text, HTML, XML, and scripts
• Scripts in an ASP file are executed on the server
• An ASP file has the file extension ".asp"

1.4 How Does ASP Differ from HTML?


• When a browser requests an HTML file, the server returns the file
• When a browser requests an ASP file, IIS passes the request to the ASP
engine. The ASP engine reads the ASP file, line by line, and executes the
scripts in the file. Finally, the ASP file is returned to the browser as plain
HTML

1.5 What can ASP do for you?


• Dynamically edit, change or add any content of a Web page
• Respond to user queries or data submitted from HTML forms
• Access any data or databases and return the results to a browser
• Customize a Web page to make it more useful for individual users
• The advantages of using ASP instead of CGI and Perl, are those of
simplicity and speed
• Provides security since your ASP code can not be viewed from the
browser

1
• Since ASP files are returned as plain HTML, they can be viewed in any
browser
• Clever ASP programming can minimize the network traffic

2. Run ASP on Your PC


You can run ASP on your own PC without an external server. To do that,
you must install Microsoft's Personal Web Server (PWS) or Internet Information
Services (IIS) on your PC.

2.1 How to install PWS and run ASP on Windows 98


1. Open the Add-ons folder on your Windows98 CD, find the PWS folder and
run the setup.exe file.
2. An Inetpub folder will be created on your harddrive. Open it and find the
wwwroot folder.
3. Create a new folder, like "MyWeb", under wwwroot.
4. Use a text editor to write some ASP code, save the file as "test1.asp" in
the "MyWeb" folder.
5. Make sure your Web server is running - The installation program has
added a new icon on your task bar (this is the PWS symbol). Click on the
icon and press the Start button in the window that appears.
6. Open your browser and type in "http://localhost/MyWeb/test1.asp", to view
your first ASP page.

2.2 How to install IIS and run ASP on Windows 2000


1. From your Start Button, go to Settings, and Control Panel
2. In the Control Panel window select Add/Remove Programs
3. In the Add/Remove window select Add/Remove Windows Components
4. In the Wizard window check Internet Information Services, click OK
5. An Inetpub folder will be created on your harddrive
6. Open the Inetpub folder, and find a folder named wwwroot
7. Create a new folder, like "MyWeb", under wwwroot.
8. Use a text editor to write some ASP code, save the file as "test1.asp" in
the "MyWeb" folder
9. Make sure your Web server is running - The installation program has
added a new icon on your task bar (this is the IIS symbol). Click on the
icon and press the Start button in the window that appears.
10. Open your browser and type in "http://localhost/MyWeb/test1.asp", to view
your first ASP page

2.3 How to install IIS and run ASP on Windows XP Professional


Note: You cannot run ASP on Windows XP Home Edition.
1. Insert the Windows XP Professional CD-Rom into your CD-Rom Drive
2. From your Start Button, go to Settings, and Control Panel
3. In the Control Panel window select Add/Remove Programs

2
4. In the Add/Remove window select Add/Remove Windows Components
5. In the Wizard window check Internet Information Services, click OK
6. An Inetpub folder will be created on your harddrive
7. Open the Inetpub folder, and find a folder named wwwroot
8. Create a new folder, like "MyWeb", under wwwroot.
9. Use a text editor to write some ASP code, save the file as "test1.asp" in
the "MyWeb" folder
10. Make sure your Web server is running - its status can be checked by
going into the Control Panel, then Administrative Tools, and double-click
the "IIS Manager" icon
11. Open your browser and type in "http://localhost/MyWeb/test1.asp", to view
your first ASP page

2.4 How to install IIS & run ASP on Windows Server 2003 (.NET Server)
1. When you start the Windows Server 2003, you should see the Manage
Your Server wizard
2. If the wizard is not displayed, go to Administrative Tools, and select
Manage Your Server
3. In the wizard, click Add or Remove a Role, click Next
4. Select Custom Configuration, click Next
5. Select Application Server role, click Next
6. Select Enable ASP.NET, click Next
7. Now, the wizard may ask for the Server 2003 CD. Insert the CD and let it
run until it is finished, then click the Finish button
8. The wizard should now show the Application Server role installed
9. Click on Manage This Application Server to bring up the Application
Server Management Console (MMC)
10. Expand the Internet Information Services (IIS) Manager, then expand your
server, and then the Web Sites folder
11. You should see the Default Web Site, and it should not say (Stopped)
12. IIS is running!
13. In the Internet Information Services (IIS) Manager click on the Web
Service Extensions folder
14. Here you will see that Active Server Pages are Prohibited (this is the
default configuration of IIS 6)
15. Highlight Active Server Pages and click the Allow button
16. ASP is now active!

3. ASP Syntax
You cannot view the ASP source code by selecting "View source" in a
browser; you will only see the output from the ASP file, which is plain HTML. This
is because the scripts are executed on the server before the result is sent back to
the browser.

3
3.1 The Basic Syntax Rule
An ASP file normally contains HTML tags, just like an HTML file. However,
an ASP file can also contain server scripts, surrounded by the delimiters <%
and %>. Server scripts are executed on the server, and can contain any
expressions, statements, procedures, or operators valid for the scripting
language you prefer to use.
Consider the program below, which give “Hello World” as output to the
browser. The response.write command is used to write output to a browser.
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
<html>

Hello World!

3.2 ASP Variables


A variable is used to store information. If the variable is declared outside a
procedure any script in the ASP file can change it. If the variable is declared
inside a procedure, it is created and destroyed every time the procedure is
executed. Different examples shown below give different variables types.

This example below demonstrates how to declare a variable, assign a value to it,
and use the value in a text.
<html>
<body>

<%
dim name
name="Abdul Wahid"
response.write("My name is: " & name)
%>

</body>
</html>

My name is: Abdul Wahid

Arrays are used to store a series of related data items. Following example
demonstrates how to declare an array that stores names.
<html>
<body>
<%

4
Dim famname(4),i
famname(1) = "Abdul wahid"
famname(2) = "Aamir"
famname(3) = "Walid"
famname(4) = "Haddad"
For i = 1 to 4
response.write(famname(i) & "<br />")
Next
%>

</body>
</html>

Abdul wahid
Aamir
Walid
Haddad

This example below will display a different message to the user depending on the
time on the server. (Demonstration of time variable)
<html>
<body>
<%
dim h
h=hour(now())

response.write("<p>" & now())


response.write(" (Pakistan Time) </p>")
If h<12 then
response.write("Good Morning!")
else
response.write("Good day!")
end if
%>
</body>
</html>

30.05.2006 08:32:03 (Pakistan Time)


Good Morning!

Lifetime of Variables
1. A variable declared outside a procedure can be accessed and changed by
any script in the ASP file.
2. A variable declared inside a procedure is created and destroyed every
time the procedure is executed. No scripts outside the procedure can
access or change the variable.

5
3. To declare variables accessible to more than one ASP file, declare them
as session variables or application variables.
4. Session variables are used to store information about ONE single user,
and are available to all pages in one application. Typically information
stored in session variables are name, id, and preferences.
5. Application variables are also available to all pages in one application.
Application variables are used to store information about ALL users in a
specific application.

ASP Procedures
In ASP you can call a JavaScript procedure from a VBScript and vice versa.
Consider the example below in which VBScript is used to call a procedure.
In example below it is shown how to call a vbscript procedure from ASP.
<html>

<head>
<%
sub vbproc(num1,num2)
response.write(num1*num2)
end sub
%>
</head>

<body>
<p>
You can call a procedure like this:
</p>
<p>
Result: <%call vbproc(3,4)%>
</p>
<p>
Or, like this:
</p>
<p>
Result: <%vbproc 3,4%>
</p>
</body>
</html>

You can call a procedure like this:


Result: 12
Or, like this:
Result: 12

Consider the example below in which JavaScript is used to call a procedure. In


example below it is shown how to call a JavaScript procedure from ASP.

6
<%@ language="javascript" %>
<html>
<head>
<%
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
%>
</head>

<body>
<p>
Result: <%jsproc(3,4)%>
</p>
</body>

</html>

Result: 12

Differences Between VBScript and JavaScript


When calling a VBScript or a JavaScript procedure from an ASP file
written in VBScript, you can use the "call" keyword followed by the procedure
name. If a procedure requires parameters, the parameter list must be enclosed in
parentheses when using the "call" keyword. If you omit the "call" keyword, the
parameter list must not be enclosed in parentheses. If the procedure has no
parameters, the parentheses are optional.
When calling a JavaScript or a VBScript procedure from an ASP file written in
JavaScript, always use parentheses after the procedure name.

4. ASP Forms and User Input


The Request.QueryString and Request.Form commands may be used to
retrieve information from forms, e.g. user input.

Consider the example below in which it is shown that How to interact with the
user, with the Request.QueryString command, using a form with method=”get”
<html>
<body>
<form action="demo_reqquery.asp" method="get">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>

7
<%
dim fname
fname=Request.QueryString("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>

</html>

Submit
Your name:

Consider the example below in which it is shown that How to interact with the
user, with the Request.Form command, using a form with method=”post”
<html>
<body>
<form action="demo_simpleform.asp" method="post">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>

Submit
Your name:

In other example below it is shown that how to interact with the user, through
radio buttons (a form with radio buttons), with the Request.Form command.
<html>
<%
dim cars
cars=Request.Form("cars")
%>
<body>
<form action="demo_radiob.asp" method="post">

8
<p>Please select your favorite car:</p>

<input type="radio" name="cars"


<%if cars="Volvo" then Response.Write("checked")%>
value="Volvo">Volvo</input>
<br />
<input type="radio" name="cars"
<%if cars="Saab" then Response.Write("checked")%>
value="Saab">Saab</input>
<br />
<input type="radio" name="cars"
<%if cars="BMW" then Response.Write("checked")%>
value="BMW">BMW</input>
<br /><br />
<input type="submit" value="Submit" />
</form>
<%
if cars<>"" then
Response.Write("<p>Your favorite car is: " & cars & "</p>")
end if
%>
</body>
</html>

Please select your favorite car:


Volvo
Saab
BMW

Submit

User Input
The Request object may be used to retrieve user information from forms.
For example:
<form method="get" action="simpleform.asp">
First Name: <input type="text" name="fname" />
<br />
Last Name: <input type="text" name="lname" />
<br /><br />
<input type="submit" value="Submit" />
</form>

User input can be retrieved in two ways:


With Request.QueryString or Request.Form.

9
™ Request.QueryString
The Request.QueryString command is used to collect values in a form
with method="get". Information sent from a form with the GET method is
visible to everyone (it will be displayed in the browser's address bar) and has
limits on the amount of information to send.

If a user typed "Abdul" and "Wahid" in the form example above, the URL sent to
the server would look like this:
http://www.w3schools.com/simpleform.asp?fname=Abdul&lname=Wahid

Assume that the ASP file "simpleform.asp" contains the following script:
<body>
Welcome
<%
response.write(request.querystring("fname"))
response.write(" " & request.querystring("lname"))
%>
</body>

The browser will display the following in the body of the document:
Welcome Abdul Wahid

™ Request.Form
The Request.Form command is used to collect values in a form with
method="post". Information sent from a form with the POST method is
invisible to others and has no limits on the amount of information to send.
If a user typed "Abdul" and "Wahid" in the form example above, the URL sent to
the server would look like this:
http://www.w3schools.com/simpleform.asp

Assume that the ASP file "simpleform.asp" contains the following script:
<body>
Welcome
<%
response.write(request.form("fname"))
response.write(" " & request.form("lname"))
%>
</body>

The browser will display the following in the body of the document:
Welcome Abdul Wahid

10
Form Validation
User input should be validated on the browser whenever possible (by
client scripts). Browser validation is faster and you reduce the server load.
You should consider using server validation if the user input will be inserted into
a database. A good way to validate a form on the server is to post the form to
itself, instead of jumping to a different page. The user will then get the error
messages on the same page as the form. This makes it easier to discover the
error.

5. ASP Response Object


The ASP Response object is used to send output to the user from the
server. Its collections, properties, and methods are described below:

Collections
Collection Description
Cookies Sets a cookie value. If the cookie does not exist, it will be
created, and take the value that is specified

Properties
Property Description
Buffer Specifies whether to buffer the page output or not
CacheControl Sets whether a proxy server can cache the output generated
by ASP or not
Charset Appends the name of a character-set to the content-type
header in the Response object
ContentType Sets the HTTP content type for the Response object
Expires Sets how long (in minutes) a page will be cached on a
browser before it expires
ExpiresAbsolute Sets a date and time when a page cached on a browser will
expire
IsClientConnected Indicates if the client has disconnected from the server
Pics Appends a value to the PICS label response header
Status Specifies the value of the status line returned by the server

The table above can be understood by following example.


ASP IsClientConnected Property
The IsClientConnected property indicates if the client has disconnected from the
server.
Syntax
response.IsClientConnected
Example
<%

11
If response.IsClientConnected=true then
response.write("The user is still connected!")
else
response.write("The user is not connected!")
end if
%>

Methods
Method Description
AddHeader Adds a new HTTP header and a value to the HTTP
response
AppendToLog Adds a string to the end of the server log entry
BinaryWrite Writes data directly to the output without any character
conversion
Clear Clears any buffered HTML output
End Stops processing a script, and returns the current result
Flush Sends buffered HTML output immediately
Redirect Redirects the user to a different URL
Write Writes a specified string to the output

The table above can be understood by following example.


ASP Write Method
The Write method writes a specified string to the output.
Syntax
Response.Write variant

Parameter Description
Variant Required. The data to write

Examples
1
<%
name="John"
Response.Write(name)
%>

John
2
<%
Response.Write("Hello<br />World")
%>

Hello
World

12
To further understand the response object consider the following examples.
This example demonstrates how to write text with ASP. (Using write method)
<html>
<body>

<%
response.write("Hello World!")
%>

</body>
</html>

Hello World!

This example demonstrates how to combine text and HTML tags with ASP.
<html>
<body>
<%
response.write("<h2>You can use HTML tags to format the text!</h2>")
%>
<%
response.write("<p style='color:#0000ff'>This text is styled with the style attribute!
(color blue)</p>")
%>
</body>
</html>

You can use HTML tags to format the text!


This text is styled with the style attribute! (color blue)

This example demonstrates how to redirect the user to a different URL.


<%
if Request.Form("select")<>"" then
Response.Redirect(Request.Form("select"))
end if
%>

<html>
<body>

<form action="demo_redirect.asp" method="post">

<input type="radio" name="select"


value="demo_server.asp">

13
Server Example<br>

<input type="radio" name="select"


value="demo_text.asp">
Text Example<br><br>
<input type="submit" value="Go!">

</form>

</body>
</html>

Server Example
Text Example

Go!

The following example is self-explanatory. (Show a random link)


<html>
<body>

<%
randomize()
r=rnd()
if r>0.5 then
response.write("<a href='http://www.w3schools.com'>W3Schools.com!</a>")
else
response.write("<a href='http://www.refsnesdata.no'>Refsnesdata.no!</a>")
end if
%>

<p>
This example demonstrates a link, each time you load the page, it will display
one of two links: W3Schools.com! OR Refsnesdata.no! There is a 50% chance
for
each of them.
</p>

</body>
</html>

In the result below the www.refsnesdata.no is loaded


Refsnesdata.no!
This example demonstrates a link, each time you load the page, it will display

14
one of two links: W3Schools.com! OR Refsnesdata.no! There is a 50% chance
for each of them.

This example demonstrates a link, each time you load the page, it will display
one of two links: W3Schools.com! OR Refsnesdata.no! There is a 50% chance
for each of them.

This example demonstrates how to specify how many minutes a page will be
cached in a browser before it expires.
<%Response.Expires=-1%>
<html>
<body>
<p>This page will be refreshed with each access!</p>
</body>
</html>

This page will be refreshed with each access!

The following example demonstrates how to specify a date/time a page cached


in a browser will expire.
<%
Response.ExpiresAbsolute=#May 05,2001 05:30:30#
%>
<html>
<body>
<p>This page will expire on May 05, 2001 05:30:30!</p>
</body>
</html>

This page will expire on May 05, 2001 05:30:30!

This example demonstrates how to check if a user is disconnected from the


server.
<html>
<body>

<%
If Response.IsClientConnected=true then
Response.Write("The user is still connected!")
else
Response.Write("The user is not connected!")
end if
%>

15
</body>
</html>

The user is still connected!

6. ASP Request Object


When a browser asks for a page from a server, it is called a request. The
ASP Request object is used to get information from the user.
Its collections, properties, and methods are described below:

Collections
Collection Description
ClientCertificate Contains all the field values stored in the client certificate
Cookies Contains all the cookie values sent in a HTTP request
Form Contains all the form (input) values from a form that uses the
post method
QueryString Contains all the variable values in a HTTP query string
ServerVariables Contains all the server variable values

Properties
Property Description
TotalBytes Returns the total number of bytes the client sent in the body
of the request

Methods
Method Description
BinaryRead Retrieves the data sent to the server from the client as part
of a post request and stores it in a safe array

Examples below will make it clearer to further understand the Request object.
This example demonstrates how to use the values retrieved from a form. We use
the QueryString collection. The form uses the get method
<html>
<body>
<form action="demo_reqquery.asp" method="get">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.QueryString("fname")

16
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>

Submit
Your name:

This example demonstrates what the QueryString contains if several input fields
have the same name. It shows how to separate input fields with equal names
from each other. It also shows how to use the Count keyword to count the
"name" property. The form uses the get method.
<html>
<body>

<%
If Request.QueryString<>"" Then
If Request.QueryString("name")<>", " Then
name1=Request.QueryString("name")(1)
name2=Request.QueryString("name")(2)
end if
end if
%>

<form action="demo_reqquery2.asp" method="get">


First name:
<input type="text" name="name" value="<%=name1%>" />
<br />
Last name:
<input type="text" name="name" value="<%=name2%>" />
<br />
<input type="submit" value="Submit" />
</form>
<hr>
<%
If Request.QueryString<>"" Then
Response.Write("<p>")
Response.Write("The information received from the form was:")
Response.Write("</p><p>")
Response.Write("name=" & Request.QueryString("name"))
Response.Write("</p><p>")
Response.Write("The name property's count is: ")
Response.Write(Request.QueryString("name").Count)

17
Response.Write("</p><p>")
Response.Write("First name=" & name1)
Response.Write("</p><p>")
Response.Write("Last name=" & name2)
Response.Write("</p>")
end if
%>
</body>
</html>

First name:
Last name:
Submit

This example demonstrates how to use the values retrieved from a form. We use
the Form collection. The form uses the post method.
<html>
<body>
<form action="demo_simpleform.asp" method="post">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>

Submit
Your name:

This example demonstrates what the Form collection contains if several input
fields have the same name. It shows how to separate input fields with equal
names from each other. It also shows how to use the Count keyword to count
the "name" property. The form uses the post method.
<html>
<body>

<form action="demo_form2.asp" method="post">

18
First name:
<input type="text" name="name" value="Donald" />
<br />
Last name:
<input type="text" name="name" value="Duck" />
<br />
<input type="submit" value="Submit" />
</form>
<hr />

<p>The information received from the form above was:</p>


<%
If Request.Form("name")<>"" Then
Response.Write("<p>")
Response.Write("name=" & Request.Form("name"))
Response.Write("</p><p>")
Response.Write("The name property's count is: ")
Response.Write(Request.Form("name").Count)
Response.Write("</p><p>")
Response.Write("First name=" & Request.Form("name")(1))
Response.Write("</p><p>")
Response.Write("Last name=" & Request.Form("name")(2))
Response.Write("</p>")
End if
%>

</body>
</html>

The output below is when the submit button was clicked.


Donald
First name:
Duck
Last name:
Submit

The information received from the form above was:


name=Donald, Duck
The name property's count is: 2
First name=Donald
Last name=Duck

This example demonstrates how to interact with the user through checkboxes,
with the Form collection. The form uses the post method.

19
<html>
<body>
<%
fruits=Request.Form("fruits")
%>

<form action="demo_checkboxes.asp" method="post">


<p>Which of these fruits do you prefer:</p>
<input type="checkbox" name="fruits" value="Apples"
<%if instr(fruits,"Apple") then Response.Write("checked")%>>
Apple
<br>
<input type="checkbox" name="fruits" value="Oranges"
<%if instr(fruits,"Oranges") then Response.Write("checked")%>>
Orange
<br>
<input type="checkbox" name="fruits" value="Bananas"
<%if instr(fruits,"Banana") then Response.Write("checked")%>>
Banana
<br>
<input type="submit" value="Submit">
</form>
<%
if fruits<>"" then%>
<p>You like: <%Response.Write(fruits)%></p>
<%end if
%>

</body>
</html>

Which of these fruits do you prefer:


Apple
Orange
Banana
Submit

7. ASP Server Object


The ASP Server object is used to access properties and methods on the
server. Its properties and methods are described below:

20
Properties
Property Description
ScriptTimeout Sets or returns the maximum number of seconds a script
can run before it is terminated

Methods
Method Description
CreateObject Creates an instance of an object
Execute Executes an ASP file from inside another ASP file
GetLastError() Returns an ASPError object that describes the error
condition that occurred
HTMLEncode Applies HTML encoding to a specified string
MapPath Maps a specified path to a physical path
Transfer Sends (transfers) all the information created in one ASP file
to a second ASP file
URLEncode Applies URL encoding rules to a specified string

The examples below will help to understand.


The example below is to check, when was a file last modified.
<html>
<body>

<%
Set fs = Server.CreateObject("Scripting.FileSystemObject")
Set rs = fs.GetFile(Server.MapPath("demo_lastmodified.asp"))
modified = rs.DateLastModified
%>
This file was last modified on: <%response.write(modified)
Set rs = Nothing
Set fs = Nothing
%>

</body>
</html>

This file was last modified on: 02.12.2004 15:11:39

This example opens the file "Textfile.txt" for reading.


<html>
<body>

<%
Set FS = Server.CreateObject("Scripting.FileSystemObject")
Set RS = FS.OpenTextFile(Server.MapPath("text") & "\TextFile.txt",1)
While not rs.AtEndOfStream

21
Response.Write RS.ReadLine
Response.Write("<br />")
Wend
%>

<p>
<a href="text/textfile.txt"><img border="0" src="/images/btn_view_text.gif"></a>
</p>

</body>
</html>

Hello World line 1


Hello World line 2
Hello World line 3

8. ASP FileSystemObject Object


The FileSystemObject object is used to access the file system on the
server. This object can manipulate files, folders, and directory paths. It is also
possible to retrieve file system information with this object.
The following code creates a text file (c:\test.txt) and then writes some text to the
file:
<%
dim fs,fname
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile("c:\test.txt",true)
fname.WriteLine("Hello World!")
fname.Close
set fname=nothing
set fs=nothing
%>

The FileSystemObject object's properties and methods are described below:

Properties
Property Description
Drives Returns a collection of all Drive objects on the
computer

Methods
Method Description

22
BuildPath Appends a name to an existing path
CopyFile Copies one or more files from one location to another
CopyFolder Copies one or more folders from one location to
another
CreateFolder Creates a new folder
CreateTextFile Creates a text file and returns a TextStream object that
can be used to read from, or write to the file
DeleteFile Deletes one or more specified files
DeleteFolder Deletes one or more specified folders
DriveExists Checks if a specified drive exists
FileExists Checks if a specified file exists
FolderExists Checks if a specified folder exists
GetAbsolutePathName Returns the complete path from the root of the drive for
the specified path
GetBaseName Returns the base name of a specified file or folder
GetDrive Returns a Drive object corresponding to the drive in a
specified path
GetDriveName Returns the drive name of a specified path
GetExtensionName Returns the file extension name for the last component
in a specified path
GetFile Returns a File object for a specified path
GetFileName Returns the file name or folder name for the last
component in a specified path
GetFolder Returns a Folder object for a specified path
GetParentFolderName Returns the name of the parent folder of the last
component in a specified path
GetSpecialFolder Returns the path to some of Windows' special folders
GetTempName Returns a randomly generated temporary file or folder
MoveFile Moves one or more files from one location to another
MoveFolder Moves one or more folders from one location to
another
OpenTextFile Opens a file and returns a TextStream object that can
be used to access the file

ASP CreateTextFile Method


The CreateTextFile method creates a new text file in the current folder and
returns a TextStream object that can be used to read from, or write to the file.

Syntax
FileSystemObject.CreateTextFile(filename[,overwrite[,unicode]])
FolderObject.CreateTextFile(filename[,overwrite[,unicode]])

23
Parameter Description
filename Required. The name of the file to create
overwrite Optional. A Boolean value that indicates whether an existing file
can be overwritten. True indicates that the file can be overwritten
and False indicates that the file can not be overwritten. Default is
True
unicode Optional. A Boolean value that indicates whether the file is
created as a Unicode or an ASCII file. True indicates that the file
is created as a Unicode file, False indicates that the file is
created as an ASCII file. Default is False

Example for the FileSystemObject object is as follow:


<%
dim fs,tfile
set fs=Server.CreateObject("Scripting.FileSystemObject")
set tfile=fs.CreateTextFile("c:\somefile.txt")
tfile.WriteLine("Hello World!")
tfile.close
set tfile=nothing
set fs=nothing
%>

Example for the Folder object is as follow:


<%
dim fs,fo,tfile
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set fo=fs.GetFolder("c:\test")
Set tfile=fo.CreateTextFile("test.txt",false)
tfile.WriteLine("Hello World!")
tfile.Close
set tfile=nothing
set fo=nothing
set fs=nothing
%>

ASP GetFile Method


The GetFile method returns a File object for the specified path.
Syntax
FileSystemObject.GetFile(path)

Parameter Description
path Required. The path to a specific file

24
Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.GetFile("c:\test\test.htm")
Response.Write("The file was last modified on: ")
Response.Write(f.DateLastModified)
set f=nothing
set fs=nothing
%>

The file was last modified on 01/01/20 4:23:56 AM

The examples below will further understand us how to use the


FileSystemObject Object
This example demonstrates how to first create a FileSystemObject Object, and
then use the FileExists method to check if the file exists.
<html>
<body>

<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")

If (fs.FileExists("c:\winnt\cursors\3dgarro.cur"))=true Then
Response.Write("File c:\winnt\cursors\3dgarro.cur exists.")
Else
Response.Write("File c:\winnt\cursors\3dgarro.cur does not exist.")
End If

set fs=nothing
%>

</body>
</html>

File c:\winnt\cursors\3dgarro.cur exists.

This example demonstrates how to use the FolderExists method to check if a


folder exists.
<html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")

25
If fs.FolderExists("c:\temp") = true Then
Response.Write("Folder c:\temp exists.")
Else
Response.Write("Folder c:\temp does not exist.")
End If

set fs=nothing
%>

</body>
</html>

Output will be (if the required folder exits).


Folder c:\temp exists.

This example demonstrates how to use the DriveExists method to check if a


drive exists.
<html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")

if fs.driveexists("c:") = true then


Response.Write("Drive c: exists.")
Else
Response.Write("Drive c: does not exist.")
End If

Response.write("<br>")

if fs.driveexists("g:") = true then


Response.Write("Drive g: exists.")
Else
Response.Write("Drive g: does not exist.")
End If

set fs=nothing
%>

</body>
</html>

Drive c: exists.
Drive g: does not exist.

26
9. ASP TextStream Object
The TextStream object is used to access the contents of a text file.
The following code creates a text file (c:\test.txt) and then writes some text to the
file (the variable f is an instance of the TextStream object):
<%
dim fs, f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("c:\test.txt",true)
f.WriteLine("Hello World!")
f.Close
set f=nothing
set fs=nothing
%>

To create an instance of the TextStream object you can use the CreateTextFile
or OpenTextFile methods of the FileSystemObject object, or you can use the
OpenAsTextStream method of the File object.
The TextStream object's properties and methods are described below:

Properties
Property Description
AtEndOfLine Returns true if the file pointer is positioned immediately
before the end-of-line marker in a TextStream file, and false
if not
AtEndOfStream Returns true if the file pointer is at the end of a TextStream
file, and false if not
Column Returns the column number of the current character position
in an input stream
Line Returns the current line number in a TextStream file

Methods
Method Description
Close Closes an open TextStream file
Read Reads a specified number of characters from a TextStream
file and returns the result
ReadAll Reads an entire TextStream file and returns the result
ReadLine Reads one line from a TextStream file and returns the result
Skip Skips a specified number of characters when reading a
TextStream file
SkipLine Skips the next line when reading a TextStream file
Write Writes a specified text to a TextStream file
WriteLine Writes a specified text and a new-line character to a

27
TextStream file
WriteBlankLines Writes a specified number of new-line character to a
TextStream file

The example below demonstrates how to use the OpenTextFile method of the
FileSystemObject (explained earlier) to create a TextStream Object. The
ReadAll method of the TextStream Object reads from the opened text file.
<html>
<body>
<p>This is the text in the text file:</p>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")

Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
Response.Write(f.ReadAll)
f.Close

Set f=Nothing
Set fs=Nothing
%>
</body>
</html>

This is the text in the text file:


Hello! How are you today?

This example demonstrates how to only read a part of a TextStream file.


<html>
<body>
<p>This is the first five characters from the text file:</p>

<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")

Set f=fs.OpenTextFile(Server.MapPath("testread.txt"), 1)
Response.Write(f.Read(5))
f.Close

Set f=Nothing
Set fs=Nothing
%>

</body>
</html>

28
Output of the program is:
This is the first five characters from the text file:
Hello

10. ASP File Object


The File object is used to return information about a specified file.The File
object is used to return information about a specified file.
To work with the properties and methods of the File object, you will have
to create an instance of the File object through the FileSystemObject object.
First; create a FileSystemObject object and then instantiate the File object
through the GetFile method of the FileSystemObject object or through the Files
property of the Folder object.
The following code uses the GetFile method of the FileSystemObject object to
instantiate the File object and the DateCreated property to return the date when
the specified file was created:
<%
Dim fs,f
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.GetFile("c:\test.txt")
Response.Write("File created: " & f.DateCreated)
set f=nothing
set fs=nothing
%>
Output:
File created: 9/19/2001 10:01:19 AM
The File object's properties and methods are described below:

Properties
Property Description
Attributes Sets or returns the attributes of a specified file
DateCreated Returns the date and time when a specified file was
created
DateLastAccessed Returns the date and time when a specified file was last
accessed
DateLastModified Returns the date and time when a specified file was last
modified
Drive Returns the drive letter of the drive where a specified file
or folder resides
Name Sets or returns the name of a specified file
ParentFolder Returns the folder object for the parent of the specified file
Path Returns the path for a specified file
ShortName Returns the short name of a specified file (the 8.3 naming
convention)

29
ShortPath Returns the short path of a specified file (the 8.3 naming
convention)
Size Returns the size, in bytes, of a specified file
Type Returns the type of a specified file

Methods
Method Description
Copy Copies a specified file from one location to another
Delete Deletes a specified file
Move Moves a specified file from one location to another
OpenAsTextStream Opens a specified file and returns a TextStream object to
access the file

ASP Summary

In this chapter we have discussed how to add server-side scripts to


our web site, to make our web site more dynamic and interactive.
We have learned how to dynamically edit, change or add any content of a
web page, respond to data submitted from HTML forms return the results
to a browser, customize a web page to make it more useful for individual
users. We will further use this knowledge in web designing in our project.

References
¾ ASP manual
By Mehdi Anchor & Philip Olson

¾ http://www.w3schools.com/asp/default.asp

30

Você também pode gostar