Professional Documents
Culture Documents
Project BSC
Project BSC
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.
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.3 Solution
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
1.5 Conclusion
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.3 Solution
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
1.5 Conclusion
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.1 Ports:
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.
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.
7
Usually the frequency of crystal oscillator is 11.059 MHz.
8
RAM
7F
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
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
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.
TMOD Register
GATE C/T M1 M0 GATE C/T M1 M0
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.
12
particular timer is always monitored to check if the required time has
passed or not.
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.
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.
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
References
17
Chapter – 3A
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.
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.
Server
internet
Client
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
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)
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)
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).
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
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.
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.
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.
M.C
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.
25
Property window of Property window of
Winsock control Ms Comm. control
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.
'**********************************
'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
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
cmdclient.Enabled = False
cmdlisten.Caption = "Close"
27
'***************************************************
Case Is = "Close"
serverclient.Close
cmdlisten.Caption = "Listen"
cmdclient.Enabled = True
End Select
End Sub
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
'***************************************************
'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
'***************************************************
End Sub
End
End Sub
frmain.Caption = "Help"
frconnect.Visible = False
frsendrec.Visible = False
frcode.Visible = False
frserialsetting.Visible = False
frserstatus.Visible = False
frinout.Visible = False
End Sub
'*************************************************
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
name = cboname.ListIndex
baud = cbobaudrate.ListIndex
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
'tcpclient
Case Is = 1
'Call serverclient.SendData("Client >>> " & cbopinnumber.ListIndex)
Call serverclient.SendData(PinNumber)
'serial communication
Case Is = 3
'**********************************
End Sub
32
cmdsend.Enabled = False
Case Is = "Close"
cmdsend.Enabled = True
End Select
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"
'***********************************
End Sub
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
frmain.Caption = "Status"
frconnect.Visible = False
frsendrec.Visible = False
frcode.Visible = False
frserialsetting.Visible = False
frserstatus.Visible = False
frinout.Visible = False
End Sub
End Sub
34
Private Sub serverclient_Close()
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
cmdsend.Enabled = True
txtinout.Text = "connected to ip adress :" & serverclient.RemoteHostIP &
vbCrLf & "port # " & serverclient.RemotePort & vbCrLf & vbCrLf
End Sub
'**************************************
cmdsend.Enabled = True
Call serverclient.Accept(requestID)
txtinout.Text = "connection from ip address : " & serverclient.RemoteHostIP &
35
vbCrLf & " port# : " & serverclient.RemotePort & vbCrLf & vbCrLf
'**************************************
End Sub
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
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
Case Is = 2 'server
result = MsgBox(Source & ":" & Description, vbOKOnly, "TCP/IP error")
End Select
End Sub
If optionselect = 1 Then
End If
End Sub
37
Private Sub Text3_Click(Index As Integer)
If optionselect = 1 Then
End If
End Sub
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.
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.
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
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
43
References
44
Chapter – 3B
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.
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
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>
<p align="center"><font face="Comic Sans MS"><span style="text-transform:
uppercase"><font size="1"><u>software
( in VB )</u>
<u>Thesis</u> <u>
presentations</u>
<u>help</u></font> </span></font></p>
<hr color="#FFFF00">
<p align="center"><font face="Comic Sans MS"><span style="text-transform:
uppercase"> </span></font>
<FORM METHOD="POST">
<p align="center">
ENTER CORRECT CODE TO ON/OFF THE LOAD
<p align="center">
<INPUT TYPE="TEXT" NAME="FNAME" SIZE="20"/>
<INPUT TYPE="SUBMIT" VALUE="SEND DATA"/>
</FORM>
<p> </p>
<hr color="#FFFF00">
<%
DIM NUM
NUM=REQUEST.FORM("FNAME")
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.
serial.CommPort = 1
serial.Settings = "4800,N,8,1"
'disable DTR(data tranmission)
serial.DTREnable = False
'open the port
serial.PortOpen = True
End Sub
50
If txt <> "" Then
If message >= 0 Then
If message <= 15 Then
serial.Output = Chr$(message)
End If
End If
End If
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
References
¾ http://www.w3schools.com/asp/default.asp
53
Chapter - 4
54
4.1 Introduction
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.
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
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.
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
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
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
References
¾ http://www.ibiblio.org/obp/electricCircuits/Digital/DIGI_5.html
61
Notes for:
1
2 Steps in Developing Application
There are three primary steps involved in building a Visual Basic application:
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.
2
The Toolbox is the selection menu for controls used in your
application.
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.
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.
6
3 Variables
Variables are used by Visual Basic to hold information needed by our
application. Rules used in naming variables are:
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.
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
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
If a statement is very long, it may be continued to the next line using the
continuation character, an underscore (_). Example:
Comment statements begin with the keyword Rem or a single quote ('). For
example:
Operator Operation
^ Exponentiation
*/ Multiplication and division
\ Integer division (truncates)
Mod Modulus
+- Addition and subtraction
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
Operator Operation
Not Logical not
And Logical and
Or Logical or
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.
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
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):
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
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 (_).
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.
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.
This routine simply ends the application once the Exit button is clicked.
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.
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.
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.
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.
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.
17
Notes for:
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
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!
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>
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())
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>
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
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>
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>
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.
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
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
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>
<html>
<body>
13
Server Example<br>
</form>
</body>
</html>
Server Example
Text Example
Go!
<%
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>
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>
<%
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>
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
%>
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>
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 />
</body>
</html>
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")
%>
</body>
</html>
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
<%
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>
<%
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>
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
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
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
%>
<%
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>
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>
Response.write("<br>")
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>
<%
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
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
References
¾ ASP manual
By Mehdi Anchor & Philip Olson
¾ http://www.w3schools.com/asp/default.asp
30