Upload
others
View
4
Download
0
Embed Size (px)
Citation preview
VILNIUS GEDIMINAS TECHNICAL UNIVERSITY FACULTY OF ELECTRONICS
DEPARTMENT OF RADIO ELECTRONICS
Artūras Lukošius
EMBEDDED WEB SERVER (APARATINIS ŽINIATINKLIO SERVERIS)
Bachelor thesis
Electronics study program Computerized electronic systems
Project Advisor: Arūnas Šaltis
Head of Department: Prof. Dr. Habil. Romanas Martavičius
VILNIUS, 2004
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
5
TABLE OF CONTENTS
1. INTRODUCTION. TASK ANALYSIS …………………………………………… 6
2. REVIEW OF ANALOGOUS CIRCUITS….………………………………………. 9
3. WEB SERVER PROTOCOL STACK ANALYSIS……………………………....... 11
3.1 TCP/IP Stack………………………………………………………………….. 11
3.2 HTTP Protocol………………………………………………………………… 16
3.3 MicroLAN Protocol Analysis………………………………………………..... 18
4. COMPOSITION OF STRUCTURAL CIRCUIT…………………………………... 22
5. COMPOSITION OF ELECTRICAL CIRCUIT…………………………....………. 26
5.1 Web Server Electrical Circuit………………………………………………..... 26
5.2 MicroLAN Electrical Circuit………………………………………………….. 28
6. SOFTWARE IMPLEMENTATION ………………………………………………. 31
6.1 Programming Model…………………………………………………………... 31
6.2 Main Procedure Algorithm……………………………………………………. 33
6.3 Ethernet Driver ………………………………………………………………... 34
6.4 TCP/IP Stack and HTTP Server Implementation……………………………... 38
6.5 I2C Interface Driver……………………………………………………………. 44
6.6 MicroLAN (DS18S20) Driver………………………………………………… 44
7. MODEL INVESTIGATION……………………………………………………...... 51
8. CONCLUSIONS …………………………………………………………………… 57
9. REFERENCES …………………………………………………………………….. 58
10. RESUME……………………………………………………………………………. 59
11. APPENDIX A…………………………………………………….………………... 60
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
6
1. INTRODUCTION AND TASK ANALYSIS
During the past ten years the electronic communications industry has undergone some
remarkable technological changes. Traditional electronic communications systems that use
conventional analog modulation techniques, such as amplitude modulation (AM), frequency
modulation (FM), and phase modulation (PM), were gradually replaced with modern digital
communication systems, which offer several outstanding advantages: ease of processing, ease of
multiplexing and noise immunity.
The transmission medium involves electronic, radio and optic technologies. Examples of
such networks include telephone networks, computer networks, television broadcast networks,
cellular phone networks and Internet. Data communication between computers is realized by
Local Area Networks (LAN) and Wide Area Networks (WAN).
Today computer networks are connected by solid wires (twisted pair), fiber optic cables,
coaxial cables and microwaves. This results the low cost and simplicity of transmission. But
technology is developing at high rates, hence wireless communication is predominant.
Many applications that involve an interaction between processes running in two computers
may be characterized by client–server interaction. For example, a client may initiate a process to
access a given file on some server. The World Wide Web (WWW) typifies this interaction. The
WWW consists of a frame work for accessing documents that are located in the computers
connected to the Internet. The interaction between Web server and client and retrieval of Web
documents (text, graphics and other media) is managed by Hypertext Transfer Protocol (HTTP).
During the recent years Web interface is relationally preinstalled in most software
applications, more and more intelligent devices (mobile phones, domestic hardware, security
systems, network links, global positioning systems (GPS), etc.). Microwave ovens, TVs, cars,
elevators and aircraft are all controlled by computers, which do not necessarily have screen,
keyboard and hard disk. These computers are embedded in a system (embedded systems), of
which they can be only small component. The ultimate in miniaturization is microcontroller,
which is a complete computer on a single chip, including all the necessary I/O interfaces.
Regardless of the user interface, most embedded systems have an external interface for
status monitoring and system diagnosis. Traditionally this has been in the form of a serial
terminal (RS-232), but the industry is starting to see the advantage of remote diagnosis and
control: because the Web browser is so widespread, it seems the logical choice for the user
interface. Hence embedded system must have a Web server.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
7
Areas of application of embedded Web servers can be of any choice. Theoretically we can
connect all electronic equipment to the global network. Measurement, environment monitoring,
control hardware, data collection devices can be equipped with this network interface. For
example, coffee maker device can include a Web server inside for monitoring quantities of
coffee, milk, sugar, etc., service requirement. Wider project could be collecting information
about temperature, moisture, pollution amount in certain city or country regions from embedded
hardware sensors.
Our task is to investigate the real computer network basics and to design a miniature,
simple, Embedded Web Server, which could be capable to transmit static and dynamic
metrological information over the real computer network.
First we need to obtain the requirements for software and hardware suitable for Web server
design. The main parts are network interface controller (NIC) and microcontroller. Base–level
Ethernet (10-Mbit) card is still available at very low cost at second hand computer retailers.
Ethernet card must be Novell NE2000 compatible with Industry Standard Architecture (ISA)
interface.
Microcontroller is preferred to be an 8-bit unit, due to low cost. Web server HTML code is
kept in separate EEPROM memory, hence microcontroller must be capable to control I2C
interface.
Web server practically is software implementation. We need to construct TCP/IP stack to
be compatible with hardware. The TCP/IP stack must include ARP response, PING response,
TCP protocol stack and HTTP service. Incoming packets must be preceded with higher priority,
TCP client connection – single–user type. Also if overrun occurs, the remain of packets in an
Ethernet buffer must be handled formerly. Web page will include metrological information. This
information is formed by the digital temperature sensors DS18S20 on 1–wire network
(MicroLAN).
MicroLAN was developed by Dallas Instruments (now Maxim Corporation). It represents a
low cost bus–system communicating over twisted pair cabling to microcontrollers a various
sensors. Power and data are supplied over this single wire. Sensors produce well defined,
calibrated digital output without external lines, A/D-converter, etc. Thus development and
prototyping are much simplified.
The information transmitted through MicroLAN is totally digital, hence integrating 1-wire
protocol in our Web server stack, we simply can integrate such information in HTTP data
packets. Text, graphics other time-constant information can be considered as static, and
dynamically refreshing – dynamic (for example, temperature indication every 5 seconds).
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
8
Summarizing we must investigate required protocol stack, MicroLAN protocol, I2C
interface arbitration, then composite the structure of all of them. MicroLAN, I2C and Ethernet
are time sensitive, hence next we will further proceed to electrical, structural and software
analysis.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
9
2. REVIEW OF ANALOGOUS CIRCUITS
Recently the Ethernet interface in non–computer hardware becomes more and more
popular. Tthere are lot of companies, developing certain Embedded Ethernet modules, which
differs from model to model. Our objective is to investigate the principles of operation of TCP/IP
protocols and realization on low-cost hardware. That is the difference between our simple project
and universal professional development tools. The most famous is Ethernut - an Open Source
Hardware and Software Project for building Embedded Ethernet Devices. The hardware design
includes a small board, which is equipped with an Atmel ATmega128 CPU and a Realtek
RTL8019AS (Ethernut 1) or LAN91C111 (Ethernut 2.0) Ethernet Controller, shown in
Figure 2.1. This figure is taken from [9]. It can be easily expanded with add–on boards attached
to its expansion connector. The Ethernut project includes redundant software implementation
and complex hardware structure and is not suitable for low-cost projects, which doesn’t require
universal applications. The Ethernut is proposed for professional embedded system developers.
Fig. 2.1 Ethernut 2.0 board
Other example is AVR embedded web server design (Figure 2.2), which includes a
complete web server with TCP/IP support and Ethernet interface. It also includes support for
sending mail, and software for automatic configuration of the web server in the network. The
AVR web server reference design includes complete source code written in C-language. A
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
10 comprehensive designer’s guide describes all web server components and gives embedded
systems designers a quick start to embedded web servers. The AVR embedded web server can be
plugged into any Ethernet interface and communicate with a standard Web browser. The
disadvantage also is complex hardware, requiring SMD technology to realize, redundancy of
functions, which are not all necessary for simple applications.
Fig. 2.2 AVR Embedded Web Server board
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
11
3. EMBEDDED WEB SERVER PROTOCOL STACK ANALYSIS
Embedded Web Server protocol stack is a combination of TCP/IP protocol suite and
MicroLAN protocol, which serves as 1–wire network. TCP/IP protocol stack allows computers
of all sizes, from many different computer vendors, running totally different operating systems,
to communicate with each other. It forms the basis for what is called the worldwide Internet, a
Wide Area Network (WAN) of millions of computers. The international community, in its
wisdom, decided to standardize on the number of protocol layers in a stack, and the International
Standards Organization (ISO) Open Systems Interconnection (OSI) model was created. We will
use this model in our Embedded Web Server implementation. TCP/IP protocol stack is shown in
Figure 3.1.
Fig. 3.1 Embedded Web Server. TCP/IP protocol stack
3.1. TCP/IP Stack
The revision of network protocols is based on Stevens [1] book.
Network protocols are normally developed in layers, with each layer responsible for a
different facet of the communications. A protocol stack, such as TCP/IP, is the combination of
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
12 different protocols at various levels. TCP/IP is considered to be a 4-layer system, as shown in
Figure 3.1. Physical layer is hardware interface (Ethernet card).
Each layer has different responsibility.
The data–link layer normally includes the device driver in the operating and the
corresponding network interface card in the computer. Together they handle all the hardware
details of physically interfacing with the cable. In our Web Server we use standard network
interface card. Ethernet driver is basically access of NIC registers, SRAM, sending sample
hexadecimal commands. We see that the purpose of the link layer in the TCP/IP protocol stack is
to send and receive IP datagrams for the IP module, Address Resolution Protocol (ARP) request
and replies for the ARP module. In the TCP/IP world the encapsulation of the IP datagrams is
defined in RFC 894 for Ethernets. RFC 894 is most commonly used. Figure 3.2 shows the
Ethernet encapsulation.
Fig. 3.2 Ethernet encapsulation (RFC 894)
This frame format use 48-bit destination and source addresses, typically called hardware or
MAC address. The type field identifies the type of data that follows. The CRC field is a
redundancy check (a checksum) that detects errors in the rest of the frame.
When an Ethernet frame is sent from one host on a LAN to another, it is the 48-bit Ethernet
address that determines for which interface the frame is destined. The device driver software
never looks at the destination IP address in the IP datagram. Example of MAC address could be:
“00–50–FC–74–11–41”.
ARP provides a mapping between the two different forms of addresses: 32–bit IP address
and whatever type of address the data link uses.
Figure 3.3 shows the format of an ARP request and an ARP reply packet, when used on the
Ethernet to resolve the IP address.
Hard type field specifies the type of hardware address. Its value is 1 for Ethernet. Prot type
specifies protocol address type being mapped. Its value is 0x0800 for IP address. Hard size value
is 6, prot size – 4. Op – operation: ARP request (a value of 1), ARP replay (2).
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
13
Fig. 3.3 Format of ARP request or reply packet when used on an Ethernet
The network layer (sometimes called the Internet layer) handles the movement of packets
around the network. IP (Internet Protocol), ICMP (Internet Control Message Protocol) provide
the network layer in the Embedded Web Server TCP/IP protocol stack.
All TCP and ICMP data get transmitted as IP datagrams. IP provides an unreliable,
connectionless datagram delivery service. There is no guarantee that an IP datagram successfully
gets to its destination. When something goes wrong, IP has a simple error handling algorithm:
throw away datagram and try to send ICMP message to the source. Any required reliability must
be provided by upper layers. Connectionless means that IP doesn’t maintain any state
information about successive datagrams. Each datagram is handled independently from all other
datagrams. This means that IP datagrams can be delivered out of order.
Figure 3.4 shows the format of the IP datagram. The normal size of the IP header is
20 bytes. The current protocol version is 4, so IP is sometimes called IPv4. The header length is
the number of 32–bit words (4 bytes per word) in the header, including any options. This limits
the header length to 60 bytes.
TOS value is 0 meaning normal service. Total length of IP datagram in bytes and header
length shows us where the data portion of the IP datagram starts and its length. Maximum size of
IP datagram can be 65535 bytes. Identification field identifies each datagram sent by a host. It
normally increments by one each time a datagram is sent. TTL sets an upper limit on the number
of routers through which datagram can pass. It limits the life time of the datagram. It is
initialized by the sender and decremented by one in every router that handles the datagram.
Protocol is by IP to demultiplex incoming datagrams.
20 b
ytes
Fig. 3.4 IP Header fields
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
14
Fig. 3.5 ICMP message encapsulated within an IP datagram
It identifies which protocol gave the data for IP to send. The header checksum is calculated
over IP header only. It does not cover any data that follows the header. ICMP and TCP have a
checksum in their own headers to cover their own header and data.
ICMP is often considered as part of IP layer. It communicates error messages and other
conditions that require attention. ICMP messages are usually acted on by either the IP layer or
the higher layer protocol (TCP). ICMP messages are transmitted within IP datagrams, as shown
in Figure 3.5.
Basically we will exploit ICMP protocol to generate the PING reply answer to the
requesting client. PING gives the opportunity to examine the IP record route and timestamp
options. Figure 3.6 shows the ICMP echo (PING) request and reply messages.
Server must echo identifier and sequence number fields. Also, any optional data sent by the
client must be echoed. Sequence number starts at 0 and is incremented every time when new
echo request is sent.
Fig. 3.6 ICMP message for echo (PING) request and reply
The transport layer provides a flow of data between two hosts, for the application layer
above in Figure 3.1.
Transmission Control Protocol (TCP) provides a reliable, connection-oriented, byte
stream flow of data between two hosts. It is concerned with things such as dividing the data
passed to it from the application into appropriately sized chunks for the network layer below,
acknowledging received packets, setting timeouts that make certain the other end acknowledges
packets that are sent and so on. Because reliable data flow is provided, the application layer can
ignore all these details.
TCP provides reliability by doing the following:
• the application data is broken into what TCP considers the best chunks to send. The
unit of information passed to IP is called a segment.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
15
• When TCP sends a segment it maintains the timer, waiting for the other end to
acknowledge reception of the segment. If acknowledge is not received in time, the
segment is retransmitted.
• When TCP receives data from the other end of the connection, it sends an
acknowledgment.
• TCP maintains a checksum on its data header page. If segment arrives with invalid
checksum, acknowledge is not generated and sender retransmits the segment.
• TCP segment can arrive out of order. Application can organize the segments in
required order.
• TCP must discard duplicate segments, because IP datagrams can get duplicated.
• TCP also provides flow control. A receiving TCP only allows the other end to send
as much data as the receiver has buffer for.
A stream of 8–bit bytes is exchanged across the TCP connection between the two
applications. There are no record makers automatically inserted by TCP. This is what is called a
byte stream service. If the application on one end writes 10 bytes, followed by a write of
20 bytes and then followed by 50 bytes, the application at the other end may read 80 bytes in
four read of 20 bytes at a time. The interpretation of data stream whether it is binary data, ASCII
characters or other form is handled by application, because TCP does not interpret the content of
the bytes at all.
TCP data is encapsulated in an IP datagram, as shown in Figure 3.7. Figure 3.8 shows
format of TCP header. Its normal size is 20 bytes.
Each TCP segment contains the source and destination port number to identify the sending
and receiving application. These two values, along with the source and destination IP addresses
in the IP header uniquely identify each connection.
Fig. 3.7 Encapsulation of TCP data in an IP datagram
The combination of an IP address and port number is called a socket. The sequence number
identifies the byte stream of data from the sending TCP to receiving TCP that the first byte of
data in this segment represents. TCP numbers each byte with a sequence number. Acknowledge
number contains the next sequence number that the sender of the acknowledgement expects to
receive. This is then the sequence number plus 1 of the last successfully received byte of data
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
16
Fig. 3.8 TCP header
This field is only valid if the ACK flag is set. The 32-bit acknowledgement number field is
always part of the header, as is the ACK flag. This field is always set and the ACK flag is on.
There are 6 flag bits in the TCP header – one or more can be set at one time:
• URG – the urgent pointer is valid.
• ACK – the acknowledgement number is valid.
• PSH – the receiver should pass data to the application as soon as possible.
• RST – reset the connection.
• SYN – synchronize sequence numbers to initiate a connection.
• FIN – the sender is finished sending data.
TCP’s flow control is provided by each end advertising a window size. This is the number
of bytes, starting with the one specified by the acknowledgement number field, that the receiver
is willing to accept. Limit is 65535 bytes.
Checksum covers the TCP segment: TCP header and TCP data. The urgent mode is a way
for the sender to transmit emergency data to the other end. The acknowledgement segment can
be sent without any data. Normal exchange of segments is shown in Figure 3.9.
When an application sends data using TCP, the data is sent down the protocol stack,
through each layer, until it is sent as a stream of bits across the network, each layer adds
information to the data by appending headers to the data that it receives. Figure 3.10 shows this
process.
3.2. HTTP Protocol
The Hypertext Transfer Protocol (HTTP) is a protocol that allows a web client to request
files or other resources from a server. Various types of requests can be sent by the client. The
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
17 most basic are “GET” request and the “POST” request which are used to fetch and post data,
respectively. The server processes the request, returns a header containing a status code and a
file, an HTML document or picture attached after the header. Finally, the server or client closes
the connection.
To fetch a Web document, the browser opens a TCP connection to server port 80, and then
uses HTTP to send a request. HTTP operation is rather simple: the request and response are one
or more lines of text each terminated by new line characters (line feed (LF) and carriage
return (CR)). If the request is successful, the information is sent down the same connection,
which is closed on completion.
HTTP commands are called methods. The first word in the request line is the name of the
method to be executed. The common methods are listed below in Table 1.
Fig. 3.9 TCP states corresponding to normal connection
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
18
Fig. 3.10 Encapsulation of data
Every request gets a response starting with a status line. The status line consists of the
protocol version (for example, HTTP/1.0) followed by a numeric status code (for example,
“200 OK”) and its associated textual phrase. Table 3.1 The commonly built-in HTTP request methods
Method Description GET Request to read a web page POST Append a web page HEAD Request to read a page header PUT Request to store a web page
DELETE Remove a web page LINK Connects two existing resources
UNLINK Brake LINK connection
A request message consists of a request-line followed by some header-lines specifying the
request. A response message consists of a response line followed by header lines and the entity
body. The entity body is separated from the headers by a null line. Example of GET response is
shown in Table 2. Table 3.2 Example of GET response
Status-line HTTP/1.0 200 OK Response headers Server: Artcom Web Server Entity headers Content type: text/html Entity body <HTML File contents>
3.3. MicroLAN Protocol Analysis
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
19
A MicroLAN–based system consists of three main elements: a bus master with controlling
software, the wiring with associated connectors and 1–Wire devices. Any standard
microcontroller such as 8051 with at least a 1.8 MHz clock, as well as PC using 115.2 kbps
capable UART, can serve as master for the MicroLAN.
Timing and especially delays between bit sequences are of the most importance. If the
delays between bits write operations are too short, we may face with loss of control and error
occurrence []. All precise timing is controlled by bus master.
Communicating with the digital temperature sensor DS18S20 is achieved through the use
of time slots, which allow data to be transmitted over the 1-wire bus. All time parameters are
presented in microsecond scale; hence timing must be precise enough.
Because bus is asynchronous, we don’t need separate clocking signal. Every
communication cycle begins with a reset pulse from the microcontroller followed by a presence
pulse from the DS18S20 as shown in Figure 5.1.
If any device is present at the bus, it responds to reset pulse and the bus master knows that
slave devices are on the bus and are ready to operate.
Fig. 3.11 Reset Pulse and Presence Pulse timing diagram
During the initialization sequence the bus master transmits the reset pulse by pulling
1–wire bus low for a minimum 480us. The master then releases the bus and goes into receiver
mode. If under parasite power reset time low constant RSTLt > 960 µs, power on reset may occur,
hence we use not more than 700 µs.
The bus master writes data to the DS18S20 during write time slots and reads data from the
DS18S20 during read time slots. One bit of data is transmitted over the 1-wire bus per time slot.
There are two types of write time slots: “Write 1” time slots and “Write 0” time slots. The
bus master uses a Write 1 time slot to write logic 1 to the DS18S20 and a Write 0 time slot to
write logic 0 to the DS18S20. All write time slots must be a minimum of 60 µs in duration with a
minimum of a 1 µs recovery time between individual write slots. Both types of write time slots
are initiated by the master pulling the 1-wire bus low (see Figure 3.12). To generate a Write
1 time slot, after pulling the 1-wire bus low, the bus master must release the 1-wire bus within
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
20 15 µs. When the bus is released, the 5 kΩ pull–up resistor will pull the bus high. To generate a
Write 0 time slot, after pulling the 1-wire bus low, the bus master must continue to hold the bus
low for the duration of the time slot (at least 60 µs). The DS18S20 samples the 1-wire bus during
a window that lasts from 15 µs to 60 µs after the master initiates the write time slot. If the bus is
high during the sampling window, a 1 is written to the DS18S20. If the line is low, a 0 is written
to the DS18S20.
The DS18S20 can only transmit data to the master when the master issues read time slots.
Therefore, the master must generate read time slots immediately after issuing a Read Scratchpad
[BEh] or Read Power Supply [B4h] command, so that the DS18S20 can provide the requested
data. In addition, the master can generate read time slots after issuing Convert T [44h] or Recall
E2 [B8h] commands to find out the status of the operation as explained in the software section.
All read time slots must be a minimum of 60 µs in duration with a minimum of a 1 µs recovery
time between slots. A read time slot is initiated by the master device pulling the 1-wire bus low
for a minimum of 1 µs and then releasing the bus (see Figure 3.11). After the master initiates the
read time slot, the DS18S20 will begin transmitting a 1 or 0 on bus. The DS18S20 transmits a 1
by leaving the bus high and transmits a 0 by pulling the bus low. When transmitting a 0, the
DS18S20 will release the bus by the end of the time slot, and the bus will be pulled back to its
high idle state by the pull-up resister. Output data from the DS18S20 is valid for 15 µs after the
falling edge that initiated the read time slot. Therefore, the master must release the bus and then
sample the bus state within 15 µs from the start of the slot.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
21
Fig. 3.12 Read/Write time slot timing diagram
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
22
4. COMPOSITION OF STRUCTURAL CIRCUIT
Our project task is to design a simple structure Embedded Web Server. We construct block
diagram, structure is shown in Figure 4.1. We will use it analysing the device.
The microcontroller is a single–chip microcomputer. It contains CPU, memory, busses, I/O
ports, timers, interrupts and special interfaces for handling I2C, U(S)ART, SPI, etc. It is the core
component in our structure. All timings, data flow routines, priority decision are performed here.
Interface between microcontroller and NIC practically is ISA bus, containing only minimum
required connections. Ethernet initially is 16–bit device, but microcontroller 8–bit nature limits it
to this size. Ethernet adapter can operate also in 8–bit data mode. Address bus width is only
5–bits, because we address only NIC registers in memory range 0x300–0x31F.
MICROCONTROLLER(Web Server)
Network interface card (NIC)
I2C EEPROM
MicroLAN (see below)
RS-232Interface(buffer)
Network (LAN)
1-wireTemp.
Sensor 1
1-wireTemp.
Sensor 2
1-wireTemp.
Sensor N
1-wire bus
MicroLAN
Address(5),data(8),IRQ,IOR,IOW
I2C
1-wire
Serial link
Fig. 4.1 WEB Server structural block diagram
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
23
These registers are listed in RTL8019AS specification. It can be found in Appendix A.
Web Server has not only Network (LAN) external interface to interconnect it with outer
world, but also and serial RS-232 interface. To make compatible with personal computer serial
link we include buffer between, because of difference of binary level voltages. This interface can
serve as monitoring with desired applications (Hyper Terminal, AT terminal programs), external
control or setup (setting IP, MAC address, other server parameters), also interconnection with
other serial devices (for example, digital measurement equipment, external modems, etc.).
Microcontroller includes internal EEPROM which is only 512 bytes. Unfortunately it is not
enough for our application, hence Web page must be placed somewhere else. Because of
shortage of free I/O pins we cannot use data Flash Memory. Solution is Inter–Integrated Circuit
(I2C) interface, which belongs to two–wire family. This design employs only two I/O pins –
Serial Clock (SCL) and Serial Data (SDA). Fortunately, microcontroller structure obtained this
interface as hardware operation, and this greatly reduces the complexity of software
implementation. Microcontroller ATmega16 Two–Wire Interface module block diagram is
shown in Figure 4.2.
Transfer speed can be up to 400 kHz and we can connect up to 8 EEPROM memories in
parallel, as shown in Figure 4.3.
Important and implemental complex is 1–wire interface (MicroLAN), which is fully
handled by software. Only 1–wire serves as power supply, synchronization and data I/O.
Fig. 4.2 Microcontroller ATmega16 Two–Wire Interface (TWI)
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
24
Fig. 4.3 TWI bus interconnection
This sets up the very precise timing requirement for microcontroller routines. MicroLAN
structure is shown in Figure 4.1 above. In our project we use digital temperature sensors
DS18S20, bus also there could be other 1–wire family digital devices, such as digital
potentiometers, i–Buttons (memory cells), and other environment sensors.
Each 1–wire device has a unique 56–bit serial code (plus 8–bit CRC) stored in an onboard
ROM. That means ability to connect theoretically almost infinite number of such devices ( 562 ).
Applications that can benefit this feature include Heating Ventilation & Air Conditioning
(HVAC) environmental controls, temperature monitoring systems inside buildings, equipment or
machinery, and process monitoring and control systems [7, p. 1]. The limitations are properties
of transmission line: losses and boundary conditions.
The block diagram in Figure 4.1 illustrates the simplicity of the hardware configuration
when using multiple 1-wire temperature sensors. A single-wire bus provides both
communication access and power to all devices. Power to devices is provided by internal pull–up
circuit of microcontroller. It is realized by setting bidirectional port pull–up in software. If port
excludes this function, we can typically connect 4.7 kΩ resistor between 1–wire bus and 3 V to
5 V positive supply rail. All devices are connected in parallel; hence the incoming connection
can be followed to the next device. This enables to realize any type of network connection (star,
ring, etc.). Suppose if we have 2 or more masters on the same bus, we increase chance for data
packet collisions, which leads to loss of information or even mastering. To solve this problem,
we must separate 1–wire network masters with bus drivers or better introduce changes in
software implementation.
Digital temperature meter internal structure is shown in Figure 4.4. Temperature data flows
through pin DQ and then is included in HTTP data packets as HTML variables.
Power is supplied through the 1–Wire pull–up resistor (MOSFET or resistor pull–up) via
the DQ pin when the bus is high.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
25
Fig. 4.4 DS18S20 block diagram
The high bus signal also charges an internal capacitor (CPP), which then supplies power to
the device when the bus is low. As an alternative, the DS18S20 may also be powered by an
external supply on VDD. “Parasite power” is very useful for applications that require remote
temperature sensing or those are very space constrained.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
26
5. COMPOSITION OF ELECTRICAL CIRCUIT
The electrical circuit structure is not complex. Digital integrated circuits allow direct
coupling of I/O signals. Information interchange is produced by high and low signal levels.
Control, data I/O, interrupts, indication are of digital nature. Full electrical drawing of Embedded
Web Server can be found in Graphical part of work.
5.1 Web Server Electrical Circuit
The core component of the overall structure is Microcontroller Unit (MCU) IC5. The
preferred type of MCU is Atmel Company, AVR family ATmega16 microcontroller, shown in
Figure 5.1. Practically we employ most of its I/O pins for our design. In fact, the limitation of
MCU opportunities is its memory. The data flash memory size is 16 kB, SRAM is 1024 B,
EEPROM is 512 B. But MCU is armed with hardware implementation of some functions, such
as UART, TWI, ADC, SPI, JTAG interfaces. This simplifies the software solution of free
memory shortage. Microcontroller can be reprogrammed (even soldered to the board) through In
System Programming (ISP) interface.
Maximum operating frequency of this microcontroller (according MCU specification) is
16 MHz. But we cannot take it as reference, because system performance and stability depends
on the slowest part of the structure. And it dictates its own operating frequency. Our situation is
similar. Ethernet controller internal SRAM byte access time is typically 100 ns. That means
maximum frequency of 10 MHz. We choose crystal oscillator Q1 equal to 8 MHz, because MCU
timers require prescaler, suitable for exact timing. Capacitors C7 and C8 should always be equal
when using with crystals or resonators. The value of capacitors depends on used crystal, the
amount of stray capacitance and the electromagnetic noise of environment.
PB2(INT2/AIN0)3
XTAL212
XTAL113
PB1(T1)2
PD2(INT0)16
PD3(INT1)17
PD4(OC1B)18
PD5(OC1A)19
GND11 VCC10
PB7[SCK)8 PB6[MISO)7 PB5(MOSI)6 PA4(ADC4)
36
PA5(ADC5)35
PA6(ADC6) 34
PA7(ADC7)33
AREF32
PA3(ADC3)37
PB0(XCK/T0)1
PB3(OC0/AIN1)4
PB4(SS)5
RESET9
PD0(RXD)14
PD1(TXD)15
PD6(ICP1)20
PD7(OC2)21
PA0(ADC0)40
PA1(ADC1) 39
PA2(ADC2) 38
AGND31
AVCC 30
PC7(TOSC2)29
PC6(TOSC1)28
PC5(TDI)27
PC4(TDO) 26
PC3(TMS)25
PC2(TCK)24
PC1(SDA)23
PC0(SCL) 22
IC3
ATMEGA16-DIL40 Fig. 5.1 AVR family ATmega16 microcontroller (schematic view)
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
27
We do not reach critical situation, hence we use standard 22 pF capacitors for 3.0–8.0 MHz
crystal oscillator application.
The power supply voltage is 5 V. MCU I/O high voltage level is minimum 4.2 V, and
maximum low level input voltage is 0.6 V. Taking into account with other component
specifications, we ensure digital compatibility of communication.
The Embedded Web Server primarily communicates through an Ethernet connection. The
Realtek RTL8019AS Ethernet controller (see Figure 5.2) was originally a 16–bit ISA device, but
also can be controlled in 8–bit mode. The Ethernet controller is configured as an 8–bit device. It
features a 16 KB of internal memory which is accessed through the I/O registers Remote DMA
Port. When packet arrives to NIC, it generates interrupt request (IRQ) to microcontroller and
now the packet must be processed as soon as possible to avoid buffer overflow. We setup buffer
ring size for incoming data packets and outgoing from NIC. IOR and IOW are NIC read/write
control signals. By default Ethernet controller obtains initial values for registers.
Connector J6 is an 8–bit ISA junction used for Novell NE2000 compatible Ethernet
controllers (for example RTL8019(AS), 3COM 3C509). Pins A2–A9 is 8–bit data bus for
information I/O. Address bus needs only 5–bits (A27–A31). Connector J6 pins A22–A23 are
pulled–up to 5 volts. This enables base I/O address starting at 300 (hex) of address bus. We
access only register addresses of RTL8019AS chip (Page 0 and Page 1). All other address bits
are grounded. This gives low level or zero value. Ethernet controller memory read pin B12
(MEMR) is connected to 5 V to enable host memory read command. I/O read byte, write byte
signals IOR and IOW, managed by microcontroller, steers Ethernet data action. IRQ9 on pin B4
is interrupt request from Ethernet board to microcontroller when new data packet arrives.
Ethernet board is configured as plug–n–play mode by default. Configuration information is
saved in 16–bit Microwire EEPROM 93C46 (part of NIC card). Plug-n-play is designed the
board to be recognized by Windows OS. We must disable it by soldering jumper between pin 64
and power supply voltage +5 V of RTL8019AS chip. This is the only change in NIC electrical
structure. Otherwise, the contents of 93C46 must be configured to enable Jumper mode (JP).
8–bit mode
16–bit mode
Fig. 5.2 Realtek RTL8019AS Ethernet controller modes
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
28
The lack of microcontroller main memory is solved by connecting I2C serial EEPROM
memory chip IC4. AT24C256 component is available for 32 kB of storage memory. I2C
interface is a Two–Wire synchronous serial Interface (TWI) consisting of one data (SDA) and
one clock (SCL) line. The TWI is a multi–master bus where one or more devices, capable of
taking control of the bus. In our case bus muster is microcontroller IC5. Both SDA and SCL
lines are bi–directional therefore outputs must be of an open–drain or an open–collector type.
Each line must be connected to the supply voltage via a pull–up resistors R5 and R6. Typically it
is 4.7 kΩ, it depends on power supply voltage and bus capacitance. A line is then logic high,
when microcontroller IC5 does not drive the line and logic low – if drives low.
Since TWI bus is synchronous, the duty cycle and the period time to the SCL line is not
critical. For TWI working in Fast mode (400 kHz) the quarter period and half period delay
parameters must ensure 6.0>quartert µs and 3.1>halft µs. The microcontroller ATmega16
includes hardware TWI with maximum clock frequency up to 400 kHz. Hence it solves
compatibility and performance task. Hardware TWI simplifies software implementation. Delay
parameters are controlled by microcontroller integrated TWI.
5.2 MicroLAN Electrical Circuit
Fig. 5.3 Digital sensors DS18S20 connection to MicroLAN
Metrological information is provided by digital thermometers connected to the MicroLAN
network. All 1–wire devices share the DQ line for address, data and power transmission.
Information is serial trains of electrical pulses. The timing was discussed in section 3.3.
Figure 5.3 one more time proves the simplicity of 1-wire hardware interface. Port C of
microcontroller serves as 1-wire master branch. The sensors are connected in “parasite power”
mode: power is supplied from data line DQ. For this we must ground VDD pin (VDD connect to
GND).
MicroLAN protocol uses conventional CMOS/TTL logic levels, where 0.8V or less
indicates a logic zero and 2.2V or greater represents a logic one. Operation is specified over a
supply voltage range of 2.8 to 6 volts. Both the master and slaves are configured as transceivers
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
29 allowing data to flow in either direction, but only in one direction at a time. Technically
speaking, data transfers are half-duplex and bit-sequential over a single pair of wires, data and
return, from which the slaves "steal" power by use of an internal diode and capacitor. Data is
read and written least significant bit first.
As previously mentioned, data on the MicroLAN is transferred with respect to time slots.
For example, to write a logic one to a 1-Wire device, the master pulls the bus low and holds it for
15 microseconds or less. To write a logic zero, the master pulls the bus low and holds it for at
least 60 microseconds to provide timing margin for worst case conditions. A system clock is not
required, as each 1-Wire part is self clocked by its own internal oscillator that is synchronized to
the falling edge of the master. Power for operation is derived from the bus data line by including
a half-wave rectifier onboard each slave.
To understand “parasite power” take a deeper look at DS18S20 structure shown in
Figure 4.4. Power is instead supplied through the 1–Wire pull–up resistor (MOSFET or resistor
pull–up) via the DQ pin when the bus is high. The high bus signal also charges an internal
capacitor (CPP), which then supplies power to the device when the bus is low. As an alternative,
the DS18S20 may also be powered by an external supply on VDD. “Parasite power” is very
useful for applications that require remote temperature sensing or those are very space
constrained [7].
Fig. 5.4 Microcontroller Port PC2 structure
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
30
In parasite power mode, the 1-wire bus and CPP can provide sufficient current to the
DS18S20 to function as long as specified timing and voltage requirements are met. However,
when the DS18S20 is performing temperature conversions or coping data from the scratchpad
memory to EEPROM, the operating current can be high as 1.5 mA. This current can cause an
unacceptable voltage drop across the weak 1-Wire pull-up resistor and is more current than can
be supplied by CPP. To assure that the DS18S20 has sufficient supply current, it is necessary to
provide a strong pull-up on the 1-Wire bus whenever temperature conversions are taking place or
data is being copied from the scratchpad to EEPROM. This is solved in software.
Microcontroller manufacturer provides electrical characteristics for Port PC2 (see
Figure 5.4). Absolute maximum rating of DC per I/O port is 40.0 mA. Referring to electrical
characteristics of DS18S20, we obtain that standby current 5 µA.
The maximum voltage to which the bus pull-up resistor can raise the data line is
determined by the product of the pull-up resistor value and the idle current of all devices on the
line. The more devices, the greater the voltage drop across the pull-up resistor. The fan-out limit
of a particular MicroLAN is reached as the voltage drop across the pull-up resistor reduces the
MicroLAN supply voltage to 2.8 V. This is the minimum voltage that will recharge the parasitic
power supply of the 1-Wire devices. From this, the maximum theoretical fan-out may be
calculated. 15 µA is the worst case of device supply current. For a 5 V supply and 1.5 kΩ
minimum pull-up resistor value we have the following fan–out F:
977105.11500
8.25105.1
8.255 =
×⋅−
=×⋅
−= −−
−uppull
sMax R
VF devices. (5.1)
Using microcontroller active pull-up, we can get:
worst
outMCUMax I
IF max_
. = = 266610151040
5
3
=⋅⋅
−
−
devices. (5.2)
This represents the theoretical maximum number of 1–Wire devices that can successfully
communicate with the master using a 1.5 kΩ pull-up resistor and 5 V supply over worst case
conditions of current and temperature. The assumptions being that all devices are drawing the
maximum supply current and operating in a –40°C to 85°C environment. In the real world, all
devices will only be drawing the 15 µA maximum supply current during System Reset and
Presence Detect. At that time all device oscillators turn on for 5 T times. Since 1 T time typically
lasts 30 µs, 5 T times represents 150 µs, with a worse possible case of 255 µs. Circuit design
ensures that all 1–Wire devices will be able to operate from their internal parasite power source
for the duration of this interval once fully charged.
Now we will proceed to the software implementation section, where it will be shown how
simply connected hardware realizes complex operations.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
31
6. SOFTWARE IMPLEMENTATION
The Embedded Web Server practically is realized in software. The application code of
programming language gives life for embedded hardware. Structural block diagram, electrical
circuit and programming model are smoothly interrelated. Procedure walkthrough involves every
logical component of device. Further we will discuss programming model, main algorithm,
Ethernet driver and TCP/IP stack routines. I2C interface driver and MicroLAN digital sensor
DS18S20 software realization follows as well. Full program algorithm can be accessed in
Grapfical part of work. Analysing we will reference to it.
6.1 Programming Model
Programming model is a structural diagram of software functions, which performs certain
operations or appears as part of hardware initialization, also data storage and retrieval.
Embedded Web Server programming model is shown in Figure 6.1.
Fig. 6.1 Programming model (brown boxes represents the end device)
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
32
The model structure shows clear interchange of information. The interface between two
interrelating logical devices is performed by device driver. For example, RTL8019AS driver
initializes and controls read/write operations, access to registers and SRAM memory of Realtek
Network Interface Card (NIC). Successful initialization of device is of the main importance.
Component manufacturers include the procedure algorithms and timing requirements.
Starting the operation we arrive into setup part, where initial parameters are accessed from
microcontroller internal EEPROM memory. It is IP static address of device. It could be changed
in the help of Terminal application connecting the device to personal computer through RS–232
serial link. During the NIC initialization MAC address is written to its Physical Address
Registers (PAR). Practically it can be any number. For simplicity we choose number
“00–00–00–00–00–01”. Debugging and error information is also transmitted through RS–232.
Very important and very sensitive is microcontroller SRAM space. If we overrun the
1024 bytes of memory, undefined errors may occur. Thus the data packet size we choose as
150 bytes to be ensured that errors not occur. For TCP incoming data we set only 20 bytes. This
is to identify the incoming HTTP request. The same SRAM space is filled with global variable
definitions, matrices. Constant are kept in data flash memory. Data strings are situated both in
flash and SRAM.
The networking part is mainly based on the theory. Lot of realizations of TCP/IP stack are
spread wide as open source codes for different platform systems. Our algorithm references the
synthesis of standards. It is very simplified to perform only the basic operations. Web Server is
capable to respond to ping, ARP requests, check the incoming data packet direction (ARP,
ICMP, TCP), maintain TCP connection and termination, respond to client /GET request and send
HTML code with included static and dynamic information. We are concentrating on simplicity
of matter. Of course, if required, there could be included DHCP, UDP, TFTP, FTP protocols,
Telnet application.
The HTTP (Web Server) application accesses the HTML code from I2C EEPROM
memory. And decides where to include digital temperature information. For the meantime we
only read the HTML code without ability to save new information to EEPROM chip through
Internet.
Digital temperature sensors are intelligent components; they have digital interface,
individual ROM code, memory, ADC converter, temperature conversion logic. Sensor operates
on the MicroLAN network, which consists only from one wire; hence the accurate timing is of
the most importance. The accurate timing is ensured by bus master (microcontroller). Timer 1
and Timer 2 produce exact microsecond and millisecond delay intervals. MicroLAN driver is
discussed later in further section.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
33
The programming language can be of any type: assembler, basic or C. The latter one is
most efficient. Microcontroller C language compilers include optimal function libraries and even
code compressors (for example, ImageCraft C Compiler) for code optimization. The structure
can be simply analysed and understood, there are no tiding to certain platform or compiler.
Assembler ensures exact cycle counting, which is practically obsolete, because we can integrate
assembler routines in sensitive places of C language code. Embedded Web Server program code
written in C language can be found in Appendix A. Further we analyse program operation
principles referencing to program algorithm, but not to white code.
6.2 Main Procedure Algorithm
The microcontroller includes programming code. The normal mode of microcontroller
operation is idle state. Sleep state sometimes is selected when device is in battery mode for
reducing power consumption. And the activity mode is called by interrupt signals.
The main algorithm is a routine that initializes all the devices and enters idle mode (waiting
for interrupts). The procedure algorithm is shown in Figure 6.2. First at the very beginning the
microcontroller must define all global (accessible by any function without declaration) variables,
arrays and strings, which must reserve free operational memory space for further applications.
Next, the initial type of I/O ports, interrupt request lines and timers must be started. For
example, our data and address buses are bidirectional. Thus they are once more declared before
read/write operation (microcontroller enables or disables integrated pull–up resistors). The
USART initialization starts RS–232 serial link interface. For later compatibility old
asynchronous systems we declare 8–bit asynchronous mode with no parity check.
Microcontroller two–wire interface (TWI) is initialized as master to control slave I2C EEPROM
memory. The clock line SCL frequency is 400 kHz. Is calculated by formula (ATmega16 spec.):
TWPSfreq
freq TWBRCPU
SCL2)(216
.
⋅⋅+= , (6.1)
where TWBR – value of TWI Bit Rate Register, TWPS – value of the prescaler bit in TWI
Status Register.
Next follows the Realtek RTL8019AS initialization. The detailed explanation provides
next section. We must wait minimum 2 ms after NIC is initialized. This ensures that no process
will occur in Ethernet adapter after that time.
Finally we clear SYN and FIN flags for TCP, start NIC to be able accept packets
(command register CR Start command), start Timer 1 and enabling all microcontroller interrupt
lines we enter idle mode. Here is performed the infinite empty loop. Any allowed interrupt signal
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
34 will bring us into required routine and next again will return here. If during initialization any
device fails, the error message will be sent to serial link and “Service” LED turns on.
6.3 Ethernet Driver
The Ethernet driver consists of initialization, read and write RTL8019AS routines. The
initialization process is a configuration of RTL8019AS parameters accessed through registers.
Refer to specification in Appendix A. Command Register CR controls start or stop NIC, send
packet and DMA operations. The Interrupt Status Register (ISR) reflects the NIC status.
First when the network card is supplied by power source, it must be initialized.
Initialization routine algorithm is presented in Figure 6.3. We don’t show every bit operation,
because all these can be analysed using C code. The start of initialization begins from setup of
Fig. 6.2 Main program algorithm
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
35 data and address busses. We enable microcontroller internal pull–up resistors. Then make
hardware reset by sending logic one signal to NIC Reset line. But also there is required and
software reset of network controller. If software reset was successful, we continue to the register
initialization. Read and Write operations are performed by separate functions, which controls bit
level of data interchange between NIC and microcontroller. They are shown in Figure 6.4.
Initializing NIC parameters we access them through registers. First we must stop the NIC,
abort DMA mode (CR). We ensure that everything is done waiting for 2 ms. Now we enable
packet sending command and normal mode of loopback select (register DCR). Remote DMA
Byte Count registers RBCR0 and RBCR1 must be reset. Receive Configuration Register (RCR)
controls acceptation of packets. We filter packets with multicast addresses and accept only those
that include broadcast ones. RCR also enables CRC generator and CRC checker in hardware
level. CRC is inhibited by NIC. Then we set start page of the packet to be transmitted (TPSR),
address of the received buffer ring (PSTART), boundary for prevention of overwrite the received
buffer ring (register BNRY). Now we stop the NIC and go to register Page 1. We set current
page receive start address (CURR) and write to PAR0 – PAR5 register our MAC address. This is
physical card address, which responds or not to the incoming packets.
Setup pull-ups on data and address busses
If ISR bit RST =0
RTL8019AS Initialization
Disable IOR and IOW signals
Reset NIC
Read BYTE = RSTPORT
Do software reset. Write RSTPORT = BYTE
Wait for 10 ms
Read ISR register
error
Write CR: RD2=1, STP=1
i=0
No
Yes
Wait for 2 ms
Write DCR: ARM=1, LS=1
Write RBCR0,1=0
Write RCR: AB=1
Write TPSR = 40h
Write TCR: LB0=1
Write PSTART = 46h
Write BNRY = 46h
Write PSTOP = 60h
Write CR: PS0=1, RD2=1, STP=1
Wait for 2 ms
i<6
Write PAR0 + i = MAC[i]
i=i+1
No
Yes
Write CR: SD2=1, STP=1
Write DCR: ARM=1, LS=1
Write CR: SD2=1, STA=1
Write ISR = FFh
Write IMR: PRX=1, OVW=1
Write TCR=0
Write CURR = 46h
Return
Fig. 6.3 Network controller Realtek RTL8019AS initialization routine
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
36
Once more we stop the NIC, enable send packet operations, clear ISR register writing FFh
value, enable Receive Packet and Buffer Exhausted interrupt flags and finally end initialization
enabling normal mode and CRC generator. Now the NIC is prepared for reception of incoming
data packets.
When packet reaches the Ethernet controller, RTL8019AS generates hardware interrupt on
microcontroller pin INT0. We were in idle state and now we jump to the INT0_Received routine.
The procedure algorithm is shown in Figure 6.5. First we must disable all interrupts, which
would trouble the microcontroller during reception of data packet. The values of ISR register
shows if the NIC buffer overrun (OVW = 1) or the buffer received new data packet (PXR = 1).
When Current Page Register and Boundary register become equal (CURR = BNRY), then we
processed all incoming packets and return to idle state. It is very important to enable interrupts to
microcontroller to be sensitive.
When buffer overruns, we need to stop and reset the NIC, reset Remote Byte Count
Registers RBCR0 and RBCR1. Entered the loopback mode again we write boundary page
address BNRY = 46h (4600h) and the same to the current page address CURR. Now we start
NIC, clear ISR interrupt flag OVW and exit from loopback mode (TCR = 0).
A pair of pointers, BNRY and CURR, point into the buffer. BNRY protects data not yet
read from the buffer. The receiver cannot store data above this boundary. When reading data
from the device, this register needs to be updated to contain the address of the page just before
unread data. Second register, CURR, points to the location of NIC memory where incoming data
will be stored.
The next important step is to get the incoming packet from network controller SRAM to
microcontroller predefined packet space. The Get_Packet routine performs this action and then
passes the arbitration rights to the upper layers in the TCP/IP stack.
Fig. 6.4 Read RTL8019AS and WriteRTL8019AS routines
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
37
Fig. 6.5 Interrupt INT0 Received routine
Every incoming data packet includes 4 byte page header, which is generated by NIC. This
is main information about next packet sequence. Page header consists from Ethernet packet
status byte, next block pointer byte and 2 bytes of Ethernet packet length. The last parameter is
received packet length (RX_length). We read the packet from Remote DMA Port. The packet
length is 150 bytes, because it was initially assumed. When DMA operation is completed, we
check the packet destination. In fact, there are some parameters, which must be checked. The
packet direction is performed here. If Ethernet frame type is 0806h, then we proceed to ARP
routine. This is over up the data link layer. Else if Ethernet frame type appears as 0800h and the
destination IP in an IP datagram is equal to our IP address, this means that the packet is passed to
network layer, IP protocol. In our TCP/IP stack we realized ICMP (IP_Protocol = 1) and
TCP (IP_Protocol = 6) directions.
When Server makes response to client Ping or ARP request, we echo the incoming packet
with modified information. The Echo_Packet routine is shown in Figure 6.6. First we start the
NIC in Page 0 mode. Transmit Page Start Register (TPSR) sets the start page address of the
packet to be transmitted. We define it as 40h (4000h). Now cleared the interrupt register ISR we
start NIC in Remote DMA write mode. We take packet length parameter from page header. This
value minus 4 is our transmission length. We write our packet for this length and start NIC to
send the packet.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
38
Fig. 6.6 Echo Packet routine
Packet encapsulation is performed through TCP/IP stack. When sending packet, we always
refer to RTL8019AS driver. It controls the writing of data to NIC memory using Remote DMA
access.
6.4 TCP/IP Stack and HTTP Server Implementation
The implementation of TCP/IP stack is closely related to theoretical definitions discussed
in third Chapter. Every protocol routine performs its own encapsulation of header. The algorithm
tree shows clear sequence of operations. Thus we just briefly review the main routines. Full
algorithm tree is represented in Graphical part of the work.
When packet is accepted by microcontroller, the Get Packet routine makes decision about
packet destination. The ARP routine is shown in Figure 6.7. This operation practically is just
over the network link layer. We start the NIC in Page 0 mode. Set transmission start page at
address 40h (4000h). Remote Start Address Registers (RSAR) is set to the same value. Starting
NIC in Remote DMA mode we write to RDMAPORT the Ethernet header (14 bytes), and ARP
reply message (28 bytes), also 12 bytes zeros trailer to reach the minimum data length of
46 bytes.
The network layer IP protocol encapsulates its 20 bytes header, including destination and
source IP and MAC. Its routine is shown in Figure 6.8. Checksum calculation is appended after
header data is completed. Destination IP and MAC address depends on type of service, which is
using this encapsulation. If the Server does not echo the packet, it must respond with client IP
and MAC address, which are placed as CLIENT_IP[ ] and T–MAC[ ] variables.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
39
Internet Control Management Protocol (ICMP) provides opportunity to check whether the
server is reachable over the network. Thus we employ ICMP as Ping reply message generator.
The ICMP routine is represented in Figure 6.9. Type and Code are 0, this means Ping reply
message (query). Then we decline to network layer (Set IP Address routine). Here are
incorporated IP and MAC addresses, and finally, the checksum calculation.
Fig. 6.7 ARP routine
Fig. 6.8 Setting IP Address routine
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
40
Fig. 6.9 ICMP routine
The checksum is a contribution to detect if the data has been transmitted successfully. The
header checksum is calculated over the IP header only. It does not cover any data that follows
the header. ICMP and TCP have a checksum in their own headers to cover their header and data.
The checksum field (Chksum) is calculated as the 16 bit one's complement of the one's
complement sum of all 16 bit words in the TCP segment header and TCP segment data. If the
segment contains an odd number of octets (that is, it does not end on a 16-bit boundary), then it
is padded with zeroes for checksum calculation purposes [1, p. 37]. While computing the
checksum, the checksum field itself is replaced with zeros. The checksum calculation routine is
shown if Figure 6.10. Example of checksum calculation is presented in Figure 6.11. To calculate
TCP checksum a "pseudo header" is added to the TCP header. This includes:
Fig. 6.10 Checksum Calculation routine
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
41
Fig. 6.11 Checksum Calculation example
• IP Source Address (4 bytes);
• IP Destination Address (4 bytes);
• TCP Protocol (2 bytes);
• TCP Length (2 bytes).
The checksum is calculated over all the octets of the pseudo header, TCP header and data.
If the data contains an odd number of octets a pad, zero octet is added to the end of data. The
pseudo header and the pad are not transmitted with the packet.
The transport layer includes TCP protocol suite. Algorithm is presented in Graphical part
of work. The TCP is connection–oriented protocol. First we need to establish a connection
between server and client. This is done by three segment connection establishment, called the
three way handshake: client SYN segment, server own SYN segment and client acknowledge to
the server’s SYN segment.
The client sends a SYN segment specifying the port number to the server that the client
wants to connect to, and the clients Initial Sequence Number (ISN). We started only HTTP
server service on port 80, thus only to this port the response is activated, connections including
different port than 80 will be silently discarded. During SYN we must assign client IP address
CLIENT_IP[ ]. Our server can maintain only one TCP connection at once. This is done because
of microcontroller memory limitations and simplicity purposes. When client requests for SYN,
we disable the response for other clients until the connection is free (HTTP_free = 1). If initial
sequence number overflows i. e. more than 16–bit length, we just to set it to 1234FFFFh to
become root users on software systems if chopping off error occurs.
We echo the SYN packet to the client. Our server acknowledges the client’s SYN by
acknowledging the client’s ISN plus 1. A SYN consumes one sequence number. The client must
acknowledge this SYN from the server by acknowledging the servers ISN plus one.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
42
When TCP connection is established the client sends GET request. Of course, identification
of this request belongs to application level, but we first look at it from the transport layer point.
If we get TCP data packet containing some data, we must acknowledge the reception. We read
the first 4 bytes data (DATA[ ]) for later analysis in HTTP. Then check for the number of bytes
acknowledged. We determine how many bytes are outstanding and adjust the outgoing sequence
number accordingly (SEQ_num_out = ACK_num_in). And send acknowledgement TCP packet
with no data included. Now this routine continues in application layer, HTTP routine.
The principle of operation of TCP and HTTP in our Embedded Web Server is based on
basic operations, which minimally satisfy the TCP connection establishment, HTTP data
transmission and connection close. When we get HTTP request, we transmit HTTP response,
then wait for acknowledgement. If acknowledge is received we do continuation of HTTP data
transmission until we reach the end of data. At the end we set FIN flag and initiate the
connection close. Client must refresh the connection sending new SYN request. If packet is lost,
sever retransmits it once more.
And finally we arrived at the top point in our TCP/IP stack. It is application layer, HTTP
server. Here can be performed all operations with HTML processing, I2C EEPROM data reading
and incorporation into TCP data packets, temperature conversion and all other I/O operations
with connected hardware.
HTTP routine is represented in Figure 6.12. HTTP server checks if the incoming data
contains GET/ request from the client. In this condition is satisfied, server initiates the initial
state of HTTP data transmission. The HTML code appears in I2C EEPROM memory. For
simplicity the starting address of HTTP response message (“HTTP/1.0 200 OK”) is located at
address 0h. Now we need to initiate temperature conversion in digital temperature sensors
DS18S20. This consumes more than one second. Then temperature data is written to temperature
information array. Also sensor identification ROM codes are read during Find_Devices routine.
Now we can start the processing of HTML data.
HTML source code is read in data portions, because our TCP data buffer is available only
for 96 bytes. Hence we read these 96 bytes from I2C EEPROM memory. All dynamic
information, such as temperature strings, sensor identification ROM codes and client IP address
are treated as variables. We must predefine space in HTML code for these variables accurately.
For example, temperature string consumes 10 bytes of data space, which will be written during
variable recognition.
We assume variable sign ‘@’ and next symbol as reference to variable. @1 means that 1st
variable is first temperature sensor information. In HTML code we must reserve empty space for
10 bytes: “@1________”. Suppose that 96 bytes data portion includes variable at the end of
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
43
Fig. 6.12 HTTP server routine
TCP data packet. Our algorithm includes variable pointer HTML_var, which obtains the answer
if the variable is suitable for incorporation until packet end without feeding. In a case, when
variable is too long to fit inside, we save current memory address of EEPROM memory and send
TCP packet cut off in the place where variable must start. During next continuation of data
sending we start reading EEPROM from that location. Because we do not built file system, the
HTML code is ended with “@/”. We assume that it is initiation of end of transmission. The TCP
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
44 then sets FIN flag and initiates the connection close to the client. Client must acknowledge the
session ending.
We realized the task in the C programming language. The program procedure includes only
minimum functions required for successful server data interchange. There is a wide range of
code optimization, extension and promotion.
6.5 I2C Interface Driver
All transfers on the I2C bus is byte sized. Each byte is followed by an acknowledge bit set
by the Receiver. The slave address byte contains both a 7–bit address and a read/write bit. In the
combined format, multiple data can be sent in any direction (to the same slave I2C device). In our
project we perform only reading from I2C memory. Writing is similar and can be integrated if
required. Reading from I2C EEPROM AT24Cxx routine is shown in Figure 6.13.
First at start point of Server operations the microcontroller initialize TWI interface, set SCL
frequency. AT24Cxx serial EEPROMs respond to device address with fixed portion equal ‘1010’
and a programmable portion matching the address inputs (A0, A1, A2). We are using AT24C256
memory chip, it responds only to A0 and A1 pins. Thus, first step in reading routine is to set
slave device address. It is 10100000 (bin) or A0 (hex). Every time, when we perform operation
on TWI bus, we must check the microcontroller Two Wire Control Register (TWCR) interrupt
flag TWINT if the operation was successful.
We set Start Condition. When it is acknowledged by slave, TWINT is set and then we write
to TWI data register TWDR the slave address. This address is 15–bit long. We set the current
high 8 bits of data address (TWDR=EE_h), then after transmission set next low 8 bits
(TWDR=I2C_Address). Now we send Repetitious Start Condition. Device entered sequential
read mode (Slave_Addr +1). We must enable TWEA flag of microcontroller TWCR register. We
acknowledge every byte sending pulse to the slave and it transmits another byte until no
acknowledgement is generated by bus master. This operation we continue until the specified
length of data read is reached. We decrease length pointer (len) by one every new cycle and
when len = 1, we set TWCR register not to generate more acknowledges and then sent Stop
Condition (TWCR = 94h). This finishes the reading I2C routine. The data buffer pointer is input
variable of routine function. Every cycle the read data is placed in the pointed location. In our
project it is TCP packet data place stating with pointer address.
6.6 MicroLAN (DS18S20) Driver
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
45
EE_h = I2C_Addr / 256
Slave_Addr = A0h
Read_EEPROM (I2C_ address,len,buff) Routine
Send Start Condition. TWCR = A4h
TWCR:TWINT = 0
TWDR = Slave_Addr + 1
Clear Interrupt. TWCR = 84h
TWCR:TWINT = 0
TWDR = EE_h
Clear Interrupt. TWCR = 84h
TWCR:TWINT = 0
TWDR = I2C_Address
Clear Interrupt. TWCR = 84h
TWCR:TWINT = 0
Send Repetitious Start Condition. TWCR = A4h
TWCR:TWINT = 0
TWDR = Slave_Addr
TWCR:TWINT = 0
Len > 0
Twcr = C4h
Len = 1
Send NAK. Twcr = 84h
TWCR = Twcr
Clear Interrupt. TWCR = 84h
TWCR:TWINT = 0Twst = TWSR
Twst = Data_NACK Len = 0
Twst = Data_ACK
Packet[Buff] = TWDR
Buff = Buff + 1
R_len = R_len +1
Send Stop Condition. TWCR = 94h
Return R_len
Len = Len - 1
Yes
No
No
Yes
Yes
No
No
Yes
No
No
Yes
Yes
Yes
No
No
Yes
No
Yes
No
Yes
Yes
No
Fig. 6.13 Reading from I2C EEPROM memory routine
DS18S20 memory structure (Figure 6.14) consists from 64-bit lasered ROM code, 9–byte
Scratchpad memory and 2–byte non–volatile EEPROM. All they are controlled by memory
control logic circuit. Master can access all memory. Each 1-wire component includes unique
64–bit ROM code. That results infinite number of different slave on single bus. ROM code is
composition of 8-bit cyclic redundancy check (CRC, discussed in further section), 48-bit
(6–byte) serial number and 8–bit family code, which is 10h for DS18S20 family 1-wire devices.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
46
Fig. 6.14 Memory structure of DS18S20
When more than one slave is present on bus, master must address the selected device by its
personal ROM code (example in Figure 6.15). Search ROM code function command locates
existing slave codes search algorithm.
8-bit/1-byte CRC (hex) 48-bit/6-byte serial number (hex) 8-bit/1-byte family code (hex) D6 00 08 00 3A D3 D4 10 6F 00 08 00 57 52 D2 10
MSB LSB Fig. 6.15 Lasered 64-bit ROM code examples
Next memory section I named as Scratchpad. Scratchpad structure is represented in Figure
6.16. It -is 9byte SRAM connected with 2-byte non–volatile EEPROM storage for the high or
low alarm trigger registers ( HT and LT ). If alarm function is not used, these registers can serve as
general–purpose memory. When device is connected in parasite mode, EEPROM serves as room
for temperature conversion data storage. The data retains unchanged when device power is low.
Byte 0 Temperature LSB AA Byte 1 Temperature MSB 00 EEPROM Byte 2 TH Register or User Data 1 ~ TH Register or User Data 1 Byte 3 TL Register or User Data 1 ~ TL Register or User Data 1 Byte 4 Reserved FF Byte 5 Reserved FF Byte 6 COUNT REMAIN 0C Byte 7 COUNT PER ºC 10 Byte 8 CRC ~
Fig. 6.16 Scratchpad memory structure (values during power–up)
Byte 0 and 1 of the scratchpad contain LSB and the MSB of the temperature register,
respectively. During power–up the return value of +85.0 ºC. These bytes are read-only.
Bytes 2 and 3 provide access to HT and LT . Bytes 4 and 5 are reserved for internal use by the
device and cannot be overwritten. These bytes return FF (hex) value when read. Bytes 6 and 7
contain the COUNT REMAIN and COUNT PER ºC registers, which can be used to calculate
extended resolution results. For example, two significant numbers after decimal point.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
47
Temperature registers contain information about current temperature conversion data and
sign. Least significant byte of temperature register show value in resolution of 0.5 ºC steps. Most
significant byte is able to obtain only two values 00 or FF (hex), meaning “+” and “–”
respectively. EEPROM write times are up to 50000 and data retention is minimum 10 years.
In order to accurately control the special timing requirements of 1–wire interface, we must
establish certain key functions: reset, read bit and write bit. All other control commands and
procedures are constructed from these all basic, but precise functions.
Each communication cycle begins with reset from microcontroller. Reset function routine
is composition of delays and direct control of I/O of microcontroller ports. According C code
and block diagram the Reset routine takes approximately 1.1 ms. We say approximately because
every batch command also takes one or more processor cycles. Master issues reset pulse pulling
DQ line low for 500 µs, then allows the bus return to initial high level stage (to be sure we wait
for 100 µs). Now microcontroller checks level of port input PINC state. If 1–wire devices are
present on bus, the state will be 1 and 0 otherwise. The value is returned back to function caller
handler.
Reading information from 1–wire bus is supervised by Read Bit routine. Comparing it with
previous described Reset function we see the same structure. Difference is only in timing delays.
The read bit is returned to routine caller as variable. The data transmission direction is observed
from slave to master. Communicating with slave device on 1–wire master issues commands,
which control slave action. To write information into 1–wire device memory it must be
transmitted as a binary sequence. Write Bit routine has one input variable reflecting output
record of master. Input data influences the algorithm path. It depends on 1 or 0 is written on bus.
Read Byte and Write Byte functions are cyclic routines, accepting or writing data from/to
1-wire bus. Cycle length is 8 loops. During Read Byte procedure master role is receiver. 8–bit
data is filled into global variable matrix. Cycle number corresponds to matrix index. Block
diagram is presented in Graphical part of work.
Write byte operation is similar to previously described one. Output variable is sent by
master bit sequence. Figure 6.10 represents simple Write Byte routine.
All further command will be constructed from these basic functions. For example
temperature conversion command is issued by sending command byte 44 (hex).
MicroLAN is designed to connect any number of 1-wire devices into one network. To
realize this main advantage, master (microcontroller) must learn the 64-bit ROM identification
code for each device using the Find_Devices algorithm.
During the ROM search process, the bus master must repeat a simple three–step routine:
• Read a ROM code bit from the slave devices.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
48
• Read the complement of the bit.
• Write the selected value for that bit.
The bus master must perform this three–step routine 64 times (once for each ROM code
bit). After one complete pass, the bus will know the ROM code for one slave device on the bus.
The remaining devices and their ROM codes can be identified through additional pass.
The algorithm starts with Setup handler, which resets the bus and done flag, clears Last
Discrepancy (misalignment) bit. The master issues the Search ROM command F0h on 1–wire
bus. Each device will respond to Search ROM command by placing the value of the first bit of
their own ROM codes onto the bus. The next bit placed on the bus by slaves is complement of
first. For this reason we have four following situations of 2–bit reading:
• 00 There are devices connected to the bus which have conflicting bits in the current
ROM code bit position.
• 01 All devices connected to the bus have 0 in this bit position.
• 10 All devices connected to the bus have 1 in this bit position.
• 11 No devices on the bus.
Temperature_Conversion Routine
Reset Routine
Search_ROM Routine
Match_ROM Routine
Write_Byte (44h)
Return
Fig. 6.17 Temperature conversion routine
Suppose that we have connected 2 devices, which ROM codes start from 0. Both they will
place 0 on the bus, i.e. they will pull it low. Next master writes bit “0”, which deselects one
device and selects other and continues to read all the code. When code is read, master can
continue searching or perform operations with obtained device. If we continue searching, now
master put 1 instead of 0 to decouple the read device and obtain another code.
The operation initiates a single temperature conversion by writing byte 44h (hex).
Following the conversion, the resulting thermal data is stored in 2–byte temperature register in
the scratchpad memory and DS18S20 return to low-power idle state. In our case, when we use
parasite power mode, within 10 µs (max) after temperature conversion command byte is sent, the
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
49 microcontroller must enable a strong pull-up on 1–wire for convt =750 ms. DS18S20 internal
structure includes power mode detection circuit. If “parasite power” mode is supplied, the slave
device writes temperature register contents to EEPROM. Temperature Conversion routine is
presented in Figure 6.17.
The master issuing the Read Scratchpad command BEh (hex) allows the contents of the
scratchpad to be read. We have described Scratchpad data structure earlier. The data transfer
starts with least significant bit of byte 0 and continues through scratchpad until MSB of 9th byte
(byte 8 – CRC) is read. Very suitable advantage is that master can send reset pulse during
reading Scratchpad if partial information is required. For example, this is used in integer
temperature measurement. Only Temperature LSB and Temperature MSB registers are required
for identification. This method is called direct-to-temperature, because Temperature LSB register
indicates temperature in steps of 0.5 ºC.
If we need more accurate results, we must calculate it according formula
C
REMAINCLSB
MSB
COUNTCOUNTCOUNTTT −
+−⋅−= 25.0)1( . (6.1)
Now the extended resolution temperature by special–purpose registers COUNT_PER_ºC
and COUNT_REMAIN in scratchpad. LSBT is obtained by truncating the 0.5 ºC bit (bit 0) from
the temperature data. Temperature conversion algorithm is shown in Figure 6.18.
Fig. 6.18 Read DS18S20 scratchpad routine
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
50
CRC bytes are provided as part of the DS18S20’s 64-bit ROM code and in the 9th byte of
the scratchpad memory. The ROM code CRC is calculated from the first 56 bits of the ROM
code and is contained in the most significant byte of the ROM. The scratchpad CRC is calculated
from the data stored in the scratchpad, and therefore it changes when the data in the scratchpad
changes. The CRCs provide the bus master with a method of data validation when data is read
from the DS18S20. To verify that data has been read correctly, the bus master must re-calculate
the CRC from the received data and then compare this value to either the ROM code CRC (for
ROM reads) or to the scratchpad CRC (for scratchpad reads).
The calculation of CRC is performed on every bit of testing portion of data, this includes
eight shift and XOR operations, thus is long and not efficient way to use it in microcontroller
routines. Hence was developed table look–up method, which contains currently calculated CRC
values for every combination of 1–byte bit sequence. The look–up table can be found in
manufacturer’s application note.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
51
7. MODEL INVESTIGATION
Fig. 7.1 Embedded Web Server model (inside view)
After electrical design and software implementation of Embedded Web Server we can
construct the prototype device, which realizes the project task. Photo of this device is shown in
Figure 7.1.
For investigation we measure some electrical parameters, which concern microcontroller
frequency, power supply and I/O voltages, power consumption. They are represented in
Table 7.1. It can be noticed, that device is conservative. When LAN cable is disconnected, the
NIC turns into auto detection mode and switches from 10Base–T (twisted pair) to 10Base–2
(coaxial cable) interface, which we do not use. This consumes considerably more power.
When a NIC has data to transmit, the NIC first listens to the cable (using a transceiver) to
see if a carrier (signal) is being transmitted by another node. This may be achieved by
monitoring whether a current is flowing in the cable (each bit corresponds to 18–20 mA). The
individual bits are sent by encoding them using Manchester encoding at 10 Mbps, the
62 alternating bits produce a 5 MHz square wave. Data is only sent when no carrier is observed
(i.e. no current present) and the physical medium is therefore idle. Any NIC which does not need
to transmit listens to see if other NICs have started to transmit information to it.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
52
Table 7.1 Device electrical parameters
Parameter Measured value Ambient temperature Notes
Voltage of power Supply, Vcc 4.98 V 20-30 oC MCU Supply Current, Iidle 11.5 mA 25 oC Power consumption, Pmax 215 mW 25 oC Power consumption, Pmax 216 mW 55 oC Tested for 5 min Power consumption, Pidle 208 mW 25 oC Power consumption, Pidle 298 mW 25 oC LAN cable disconnected MCU Clock frequency, fMCU 8 MHz - MCU Clock Period, Tclock 125 ns - MCU I/O high voltage, VI/Oh 4.7 V - MCU I/O low voltage, VI/Ol 2.1 mV -
When the device is turned on, microcontroller begins initialization of interfaces and
connected components. During the first 8 seconds, microcontroller waits for a data byte from
RS–232 serial interface to jump into service mode. Here we can setup IP address of Embedded
Web Server. We use program AT Command Scanner version 1.3. The program procedure
window is shown in Figure 7.2. If during 8 seconds microcontroller do not receive setup request
from serial link, it continues into Server Mode. To exit from Service Mode, we send letter ‘e’.
Yellow LED indicates the status of the service mode. It is lighted during setup.
Fig. 7.2 Embedded Web Server setup. AT Command Scanner 1.3 program window
Packet transmission and reception we analyze only in software level, because electrical
pulse information is investigated when undefined error occurs. Floating network packets we
capture with well known network protocol analyzer Ethereal (ver. 0.10). Data is captured "off the
wire" from a live network connection.
Final result is transmitted as Web page using HTML format. The client connects to our
Server in a help of Internet browser (Internet Explorer, Opera, Mozilla, etc.) to IP address, which
we predefined earlier. TCP session is establish and after /GET request, Server start transmit TCP
data packets including HTTP data. We captured by Ethereal program all this transmission
stream. It is shown in Figure 7.3.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
53
Fig. 7.3 TCP stream. Captured by Ethereal program
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
54
This program debug feature was used developing correct TCP sequence and acknowledge
number rows in our Server software, also other parameters of all headers. Following The
presented TCP stream, we see that every HTTP data packet is acknowledged by client. In fact,
we sent next packet (continuation) when we get acknowledgement. Our server does not include
kernel, which could control independent packet transmission, thus we solve this problem that
way. Next figure (Figure 7.4) is exported from ethereal program. It is the Time/Sequence graph.
Here we see that SYN is started at zero reference. And after follows 1.6 s gap. For this time,
microcontroller initiates digital temperature sensors temperature conversion. Approximately
750 ms each conversion and 160 ms reading ROM codes. After that follows HTTP data
transmission. Duration between continuations is 200 ms. Hence such time amount is needed for
microcontroller to process one data packet, i.e. read 96 bytes from I2C EEPROM, search for
variables in HTML code and integrate them into TCP data.
Fig. 7.4 TCP transmission Time vs. Sequence Graph. Generated by Ethereal program
Embedded Web Server HTML code appears in I2C EEPROM memory. Source code is
shown in Figure 7.5.
At the beginning we incorporate response message to client’s /GET request. Normally it is
not the part of HTML code, but we saving memory space connect it as HTML file header. Body
code is created using Microsoft Frontpage program packet. Variables are identified as @. And
following number correspond to predefined variable in microcontroller code. For example, @1 is
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
55 temperature sensor DS18S20 temperature string, which is copied in certain TCP data packet
place. When client accesses our Web Server, final Internet browser window shows web page
with all included dynamic information. Portion of window is presented in Figure 7.6.
Fig. 7.5 Web page HTML code (I2C memory contents)
HTTP/1.0 200 OK Content-Type:text/html <html><head> <meta http-equiv="Content-Language" content="en-us"> <meta http-equiv="REFRESH" content="5"> <title>Test form</title> <style> </style> </head> <body class="ms-simple2-main"> <html><head><title>Test form</title></head> <body class="ms-simple2-main"> <p align="center"> </p> <p align="center"><font size="6">Embedded Web Server</font></p> <p align="center">Your IP address: <b>@5 </b></p> <div align="center"> <table border="1" width="581" height="29"> <tr> <td height="23" width="115" align="center" valign="top" bgcolor="#FFCC66"> <font face="Microsoft Sans Serif" size="2">Temperature 1:</font></td> <td bgcolor="#00FF00"> <p align="center"> <font face="Microsoft Sans Serif"><b> <font color="#800000">@1 </font></b></font></td> <td height="23" width="94" align="center"> <font face="Microsoft Sans Serif" size="2">ROM CODE:</font></td> <td height="23" width="218"> <p align="center"><font face="Microsoft Sans Serif"> <font color="#FF0000">@3 </font></font></td> </tr> <tr> <td height="23" width="115" align="center" valign="top" bgcolor="#FFCC66"> <font face="Microsoft Sans Serif" size="2">Temperature 2:</font></td> <td bgcolor="#00FF00"> <p align="center"><font face="Microsoft Sans Serif"><b> <font color="#800000">@2 </font></b></font></td> <td height="23" width="94" align="center"> <font face="Microsoft Sans Serif" size="2">ROM CODE:</font></td> <td height="23" width="218"> <p align="center"><font face="Microsoft Sans Serif"> <font color="#FF0000">@4 </font></font></td> </tr> </table> </div> </html> <p align="center"> </p> </body> </html>@/
/GET response
Refresh every 5 seconds
Variable number and reserved space
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
56
Fig. 7.6 Embedded Web Server page accessed by Opera Internet Browser
The resultant page supplies temperature information from two digital sensors DS18S20
(connected to MicroLAN) and its identification ROM codes. Clients IP is also included. This
page refreshes every 5 seconds while browser window is open.
Embedded Web Server can accept only one TCP client at a time. When connection is
closed by issuing FIN flag (page send completed or user closed connection), next or the same
client can access this page once more (dynamic refresh).
The last step we need investigate the transmission rate. Microcontroller program is not
optimized for maximum operation speed; hence the results are not so astonishing. We test
download and upload rates with DU Meter (version 3.03) program. It measures the incoming and
outgoing transmission rate. Graphical representation is presented in Figure 7.7.
Fig. 7.7 DU Meter 3.03 program window. Embedded Web Server transmission rates.
Colors: red – download speed, green – upload, yellow – both
Now it is obvious that 8–bit microcontroller platform can serve as control or monitoring
system. For data retransmission, routing, media stream broadcasting more powerful
microcontrollers are required. This model can be applied in ambient (inside and outside)
temperature monitoring, body temperature measurement and information transmission over the
Internet. With slight modifications of model design the application field can be greatly extended.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
57
8. CONCLUSIONS
Concerning the project task, we designed the Embedded Web Server, which maintains task
requirements and the following conclusions according the obtained results are:
• Inspected TCP/IP stack showed, that it can be implemented on 8–bit microcontroller
systems. Other network protocols also can be realized.
• Our Embedded Web Server provides Web page containing temperature information
accessible for clients from Internet. To realize the same task without embedded system
we need personal computer and huge operational system. Comparing electrical circuits
we can say, that Embedded Web Server is small and inexpensive system.
• Integrated MicroLAN network allows connecting digital sensors on only one wire.
Expanding operational memory of microcontroller, number of sensors can be increased
to some hundreds. The only limitation – network cable properties. CRC error check
algorithm ensures that we will get only correct data.
• Current design application – temperature monitoring over the Internet.
• Web page HTML code is saved in separate memory chip. Thus page size is
independent from microcontroller flash memory size. We can integrate data flash
memory and reach huge amounts of available memory.
• Client access the Embedded Web Server’s page using Internet Browser. For this reason,
no additional programs or drivers are needed.
• HTML variable search algorithm incorporates dynamic data into source code. We can
employ microcontroller AD converter and get analog data, connect more sensors.
• Power consumption is slightly over 200 mW (max. 300 mW). Thus exploitation of
device is inexpensive. Using planar electrical components this power consumption can
be more decreased.
• Device IP address (IPv4) is saved in microcontroller EEEPROM memory and can be
easily changed in help of Terminal program (RS–232 interface). We do need to
reprogram the source code. Thus the Embedded Web Server is portable and
independent.
• The Embedded Web Server’s source code is written in C language. It can be simply
modified and improved.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
58
9. REFERENCES
1. Stevens, W. Richard . TCP/IP Illustrated. Volume 1. Addison Wesley Publishing
Company, 1994.
2. Bentham, Jeremy. TCP/IP Lean. Web servers for Embedded Systems. Second Edition.
CMP Books, 2002.
3. Leon-Garcia, A., Wid jaja, I. Communication Networks. Fundamental concepts.
Mc Graw Hill, 2000.
4. Atmel. 8–bit AVR RISC microcontrollers. Internet access on
http://www.atmel.com/products/avr/. Date accessed: February, 2004.
5. Atmel. Serial EEPROM. Internet access on
http://www.atmel.com/products/product_selector.asp. Date accessed: March, 2004.
6. Realtek RTL8019AS specification and schematic reference. Internet access on:
http://www.realtek.com.tw/products/products1-2.aspx?modelid=1. Date accessed: April,
2004.
7. Dallas Semiconductors. 1–wire and iButton product family. Internet access on
http://www.maxim-ic.com/. Date accessed: March, 2004.
8. EDTP Electronics. Internet access on http://www.edtp.com/. Date accessed: March, 2004.
9. Ethernut. Open Source Hardware and Software for Embedded TCP/IP. Internet access on
http://www.ethernut.de/en/. Last accessed: March, 2004.
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
59
10. RESUME
EINGEBETTETER WEBSERVER
Zusammenfassung
Im Junggeselle-Postulat für den Radioelektronikingenieur-Grad wird TCP/IP Protokoll-
Schober, bestimmter elektronischer Schaltkreis, schriftliches Programm für den
Mikrokontrolleur in der C Sprache, verfertigtem und untersuchtem Plan analysiert. An
eingebetteten Webserver kann die Überwachung gewandt werden, Temperaturen, Maß-
Temperatur von Patienten im Krankenhaus zu bauen, und über das Internet übersenden. Mit
einigen Modifizierungen konnte es als Wiederanlauf-Maschine für Netzwerkanschlusspläne
dienen. Eingebetteter Webserver schließt breite Reihe von Anwendungen in häuslich,
wissenschaftlich und Andeutungslösungen ein.
Eingebettete Webserver-Netzspannung ist 5 V. In der vollen Weise arbeitend, ist
Leistungsverbrauch 300 mW (Maximum).
Artūras Lukošius. Embedded Web Server
Vilnius Gediminas Technical University 2004
60
11. APPENDIX A