Slaa 137 A
Slaa 137 A
ABSTRACT
Computer communication systems and especially the Internet are playing a rapidly
increasingly important role in our everyday environment. But today this is not only a
domain of personal computers or workstations. More and more, it makes its way to
smaller network nodes, too. Imagine applications that are able to control hardware via a
standard Internet browser, to transmit and visualize the state of sensors or automatically
generate and send E-mails on the occurrence of special events (for example, for security
purposes).
This application report describes in detail the implementation of an embedded Web server
based on the MSP430 ultralow-power microcontroller series from Texas Instruments. The
solution consists of both hardware (schematic, parts list) and software (C source). An
ethernet LAN controller offers the physical connection to the Internet. A downsized
TCP/IP protocol stack is used. Its functionality is encapsulated by an easy-to-use
application programming interface (API). By using this API, creating new applications or
modifying existing ones becomes an easy task. As an application example, a dynamic
HTTP server is implemented.
Contents
1 Introduction ........................................................................................................................................3
2 Important Protocol Basics................................................................................................................3
2.1 Ethernet........................................................................................................................................4
2.2 Address Resolution Protocol .......................................................................................................5
2.3 Internet Protocol...........................................................................................................................5
2.4 Internet Control Message Protocol..............................................................................................6
2.5 Transmission Control Protocol ....................................................................................................6
2.6 Hypertext Transfer Protocol.........................................................................................................7
3 Hardware Description........................................................................................................................7
3.1 Interfacing to the LAN Controller .................................................................................................8
3.2 Circuit Description........................................................................................................................9
3.3 Connection to the Network ........................................................................................................10
4 Software Description.......................................................................................................................11
1
SLAA137A
4.1 Ethernet Module .......................................................................................................................... 4
4.2 TCP/IP Module ............................................................................................................................ 4
4.2.1 Buffer Memory................................................................................................................. 4
4.2.2 Global Variables .............................................................................................................. 4
4.2.3 Demultiplexing and Processing of Received Frames..................................................... 4
4.2.4 Opening a Connection .................................................................................................... 4
4.2.5 Data Transfer .................................................................................................................. 4
4.2.6 Closing a Connection ...................................................................................................... 4
4.2.7 Using of Timers ............................................................................................................... 4
4.2.8 Retransmission of Data................................................................................................... 4
4.2.9 Summary ......................................................................................................................... 4
4.3 API............................................................................................................................................... 4
4.3.1 Functions ......................................................................................................................... 4
4.3.2 Flags ................................................................................................................................ 4
4.4 HTTP Server Application Example ............................................................................................. 4
4.4.1 Software Description ....................................................................................................... 4
4.4.2 Dynamic Web Page Example ......................................................................................... 4
5 References ......................................................................................................................................... 4
Appendix A. Application Schematic ....................................................................................................... 4
Appendix B. Parts List.............................................................................................................................. 4
Figures
Figure 1. ISO/OSI vs Internet Reference Model ................................................................................... 3
Figure 2. Data Encapsulation................................................................................................................. 4
Figure 3. Hardware Block Diagram ....................................................................................................... 4
Figure 4. Prototype Board With Components Installed...................................................................... 4
Figure 5. Using the Ethernet Module .................................................................................................... 4
Figure 6. DoNetworkStuff() Flowchart .................................................................................................. 4
Figure 7. Buffer Concept ........................................................................................................................ 4
Figure 8. Demultiplexing of Received Frames ..................................................................................... 4
Figure 9. Using DoNetworkStuff().......................................................................................................... 4
Figure 10. Transmitting of Data ............................................................................................................ 4
Figure 11. SocketStatus Register ......................................................................................................... 4
Figure 12. Data Reception ..................................................................................................................... 4
Figure 13. Web Server Main Module .................................................................................................... 4
Figure 14. Internet Explorer Screen ..................................................................................................... 4
Tables
Table 1. Functions of Internet Reference Model Layers ................................................................... 4
Table 2. Important HTTP Methods ....................................................................................................... 4
Table 3. Overview of the Software Modules ....................................................................................... 4
Table 4. Functions of the Ethernet Module......................................................................................... 4
Table 5. Compatible Communication Systems .................................................................................. 4
Table 6. Stack Error Codes................................................................................................................... 4
1 Introduction
While known for its use in PC networks, the ethernet also offers a robust, well-understood and
reasonably priced technology for networking applications beyond the desktop computer. The
goal of this design is to show how easy it is to implement a TCP/IP stack as well as an ethernet
interface for the MSP430. It provides both a source code for the programmer as well as
schematics for the design engineer.
It is advantageous if the reader of this application report has a general knowledge of TCP/IP
networks and their related communication protocols. Section 2 contains some very basic
information about the protocols used. For more detailed information, additional sources of
information are mentioned. Sections 3 and 4 present both the hardware and software parts of
the demonstration board featured in this application report.
Using the knowledge of this demonstration board, many applications are imaginable. Think of
home automation, utility meters, appliances, security systems, card readers and building
controls that can be easily controlled using either special front-end software or a comfortable
Internet browser from anywhere around the world. The big advantage of an HTTP server in an
embedded environment is that the web browser manages the whole user interface. The
visualizing of information can be done simply by sending ASCII strings (HTML source) to the
client and therefore minimal resources are required.
Application Layer
Presentation Layer
Application Layer
Session Layer
Transport Layer
Transport Layer
Internet Layer
Network Layer
Network Layer
Data Link Layer
Physical Layer
Beginning with the application where data is sent, each layer adds its own header to the
segment. This is called data encapsulation (Figure 2). By receiving a frame for example from
ethernet, the TCP/IP stack has to evaluate and remove step by step the headers of the different
layers to extract the payload. A recommended source for background information about the
TCP/IP software architecture is Reference [1].
2.1 Ethernet
Today, ethernet is the most common medium to transfer data in a local area network (LAN). It
belongs to the network layer in the Internet reference model. The standard IEEE 802.3 defines
possible bit rates, the physical realization of bit coding, and the frame format used. Ethernet
shares the bus and each network node has the same rights to access the media by the carrier
sense multiple access with collision detection (CSMA/CD) method. If a collision is detected, the
sending nodes stop transmitting and use a special back-off algorithm for retransmission. The
data stream is Manchester coded and transferred using differential two-wire lines (twisted pair
cable, RJ45) or coaxial cables (RG58, BNC).
• Basic data transfer: TCP splits a continuous stream of bytes in segments and sends them
out as IP-frames.
• Flow control: Each time a TCP receives a frame, it tells the other TCP how many bytes it is
allowed to send before further permission is needed.
• Multiplexing: The TCP introduces port numbers that allow multiplexing of IP addresses. Any
combination of an IP address and a port-number is called a socket. A unique TCP
connection is determined by a pair of sockets.
• Connections: Before data transfer can take place, a connection between the host and the
client must be established. This is done by using a three-way handshake. During this
handshake, the sequence numbers are synchronized. Afterwards the normal data transfer
can begin.
A TCP session runs through different states from establishing to closing. The state changes
occur as a reaction to different events. These events can be user function calls as well as
receiving segments or time-controlled actions. For detailed information about the TCP state
machine and how to work with it, see RFC 793 [4] and RFC 1122 [6].
The response from a server contains some header lines. Each one has a CR and LF at its end.
An additional CR and LF at the end of the last line of the header indicate that the data is
following. In most cases, this will be an HTML page or a picture file. After transferring the
content, the connection is usually closed again. HTTP protocol version 1.0 is described in RFC
1945.
3 Hardware Description
The two main components of the demonstration board are the MSP430F149 microcontroller
from Texas Instruments and the CS8900A ethernet controller from Crystal™ Semiconductor
Corporation.
The MSP430F149 used in the demonstration board has 60KB of flash memory and 2KB of
RAM. This makes it a good choice for storing and transferring web pages. It has also six
general-purpose input/output ports that can be used not only for interfacing to the LAN
controller, but also to realize a user project.
The CS8900A is a low-cost ethernet LAN controller optimized for industrial-standard-architecture
(ISA) personal computers. The features that made it very suitable for this project are its highly
integrated design, which reduces the amount and cost of external components, and its very
easy-to-handle bus interface. Most LAN controllers that are on the market have a PCI bus
interface. The CS8900A bus interface is simple to interface with a microcontroller directly.
General I/O port pins of the MSP430 are used to provide a bus interface to the LAN controller.
The availability of this device in a 3-V version is another benefit for interfacing it with the
MSP430.
8 MHz 20 MHz
D[7..0]
IOR
IOW
Isolation
Transformer
LEDs: Power,
Link, LAN
RJ45
Connector
Appendix A shows the schematic and Appendix B provides a list of components that are needed
to build the module. For each of the discrete parts, there are several manufacturers available.
4 Software Description
This chapter describes the implemented TCP/IP stack, the ethernet driver, and the HTTP server.
The entire software is written in C and therefore porting to other MCU systems should be quite
easy. For reasons of better understanding, the code is separated into different modules. Table 3
gives an overview of these modules.
NOTE: For developing a user application, it is highly recommended to use a network monitor
program for examining and decoding ethernet frames (for example, Microsoft™ Netmon™).
At first, the ethernet controller must be configured. This is done by calling the function Init8900().
The ethernet controller is reset and the configuration sequence stored in the C-constant
InitSequ[ ] is transferred. Every entity in this constant consists of an address and a data value.
The meaning of the registers accessed and the symbols used is described in detail in the
CS8900A data sheet [8]. After this preparation, data transfer can take place.
Init8900()
User Program
Write8900(ADD_PORT, PP_RxEvent)
(Read8900(DATA_PORT) Yes
CopyFromFrame8900(...)
& RX_OK)?
No
No
No
Rdy4Tx()?
Yes
RequestSend(FrameSize)
• The application triggers an event (for example opens a connection, sends data…)
• A time-out is exceeded
Yes
Demultiplexing
Frame Received?
(DA = Broadcast / Individual)
No
Yes
Handle Retransmission or Timeout Error,
Timer Event Occured?
Close Connection if Requested.
No
Yes
Request Memory in LAN Controller and Send
TxFrame2 Buffer Send Requested?
the TxFrame2 Buffer.
No
Yes
Request Memory in LAN Controller and Send
TxFrame1 Buffer Send Requested?
the TxFrame1 Buffer.
No
TxFrame1
TxFrame2
RxTCPBuffer
ProcessICMPFrame() ProcessTCPFrame()
If the frame was individually addressed, it is first checked to determine if it is an ARP answer
frame for a previously sent ARP request of the local TCP. In this case, the opponent’s MAC
address is extracted. This mechanism is used for performing an active open of a connection. For
the case that the received frame type is IP and its destination address matches the one of the
local TCP, a jump to the function ProcessICMPFrame() or ProcessTCPFrame() is executed,
depending on the IP protocol number.
The procedure ProcessICMPFrame() checks to determine if the frame is an ICMP echo request
and generates an ICMP echo reply. Other types of ICMP messages are ignored and discarded.
If the frame type is TCP, steps for processing incoming TCP segments recommended in RFC
793 are executed. First, the frame is checked to determine if a TCP session is active and
whether the frame belongs to this session, or if a request from another TCP for establishing a
connection was received (segment carries a SYN flag). Afterwards, the state of the variable
TCPStateMachine is changed according to the flags of the segment that arrived. When data is
sent along the segment and the receive buffer is empty, this data is copied to the RxTCPBuffer
memory space. Valid arriving segments are acknowledged by sending a TCP ACK segment.
The program only accepts incoming segments that correspond to the sequence number of the
last segment that was acknowledged. Due to the relatively small amount of memory, no
buffering can be done for segments that are delivered out of order. Preparing a non-data TCP
segment is done by using the PrepareTCPFrame() function. A valid combination of TCP flags is
passed as an argument. The whole frame (including its headers) is generated in the TxFrame2
buffer. For example, calling PrepareTCPFrame(TCP_CODE_ACK) creates an
acknowledgement segment.
4.2.9 Summary
In spite of the fact that during software development many compromises were made [6], the
compatibility of the stack in communicating with other TCPs is very good. No other TCP had
problems establishing a connection during the software evaluation. Table 5 gives a list of several
computers and operating systems where data exchange over TCP/IP is possible.
The main limitations of the protocol specifications that were made are:
4.3 API
The wish to enable existing applications as well as to create new embedded applications with
Internet connectivity was an important reason for this project. Without spending excessive time
in understanding the details of TCP/IP, an application developer should be able to use the
functionality of this stack by calling simple functions to query some flags. The API consists of a
set of subroutines for sending and receiving data and a flag register that indicates the current
status of stack.
DoNetworkStuff()
Misc Program
Misc Program
No
Termination of Program Requested?
Yes
The blocks containing misc program must not contain code which could block the periodic
execution of DoNetworkStuff() (for example endless waiting or polling for an event). The
software should use the help of timers and counters to avoid blocking. An example for this
programming style is the HTTP server that is explained in Section 4.4.
4.3.1 Functions
void TCPLowLevelInit(void)
This function does a basic setup of the ethernet controller and numerous variables; it also
configures ports and timer_A of MSP430. It must be called before any data transmission via
TCP/IP can take place.
void TCPPassiveOpen(void)
By calling this function, the stack switches to the server mode to detect an incoming connection.
The flag SOCK_ACTIVE is set indicating the stack is busy now. Before calling this function, the
local TCP port must have been configured. The local IP address is specified by a constant
declaration in the header file tcpip.h. The following example shows how to open a connection.
TCPLocalPort = 80; // port of a HTTP-server
TCPPassiveOpen(); // listen for any incoming connection
(…)
void TCPActiveOpen(void)
This procedure tries to establish a connection to a remote TCP server. The flag SOCK_ACTIVE
is set and an ARP request to find out the MAC address of the other TCP will be sent out. If the
destination IP address does not belong to the actual subnet, the IP address of the gateway is
used for the ARP request instead. The IP addresses as well as the local and remote TCP port
must be set up before doing an active open. After the opening of the connection, the
synchronization of the TCPs, and the state change of the local TCP to ESTABLISHED, the
SOCK_CONNECTED flag is set and data transfer can take place by using the appropriate API
functions. If an error occurs while opening the connection (for example, destination host is
unreachable), the connection is reset and an error code is stored into the SocketStatus variable
accordingly.
The following example shows how to perform an active open. If the module is connected to a
router and the gateway IP is configured properly, you should be able to read out the quote of the
day of a real Internet server from MCU memory by using the flash emulation tool (FET).
*(unsigned char *)RemoteIP = 24; // destination IP: 24.8.69.7
*((unsigned char *)RemoteIP + 1) = 8;
*((unsigned char *)RemoteIP + 2) = 69;
*((unsigned char *)RemoteIP + 3) = 7;
TCPActiveOpen();
while (SocketStatus & SOCK_ACTIVE) // wait for closing the connection by the
{ // other TCP
DoNetworkStuff();
}
void TCPClose(void)
Use this API function to close an open connection. Before disconnecting, the stack ensures that
a packet that still resides in the output buffer is transmitted and acknowledged properly. After
closing, the application may reconfigure IP addresses, reassign port numbers, and open a new
connection.
void TCPReleaseRxBuffer(void)
After reading out the receive buffer, calling this function tells the stack that the buffer contents is
not needed anymore and may be overwritten by new incoming TCP data. This function also
clears the SOCK_TX_BUF_RELEASED flag used to indicate the presence of new data.
void TCPTransmitTxBuffer(void)
By using this function, an application can send data over an already opened connection. First,
the application has to check if it may write data to the transmit buffer. This is done by testing the
flag SOCK_TX_BUF_RELEASED of the SocketStatus register. If this flag is set, the application
may write a maximum of MAX_TCP_TX_DATA_SIZE bytes to the transmit buffer, starting at
address TCP_TX_BUF (points to the data section of the TxFrame1 buffer). Afterwards, the byte
count must be written to TCPTxDataCount register. Finally, calling TCPTransmitTxBuffer() leads
to the transmission of the data (Figure 10).
Yes
TX_BUF_RELEASED? Copy Data to Transmit to TCP_TX_BUF
No
TCPTransmitTxBuffer()
4.3.2 Flags
The API status flags are stored in the global 8-bit variable SocketStatus. This register can only
be read out. The bit positions of the described flags are shown in Figure 11.
SOCK_ACTIVE (Bit 0)
This flag is set when the TCP is busy opening a connection (previous call of an API method to
open a session). While set, no further call of one of these functions is allowed. If an open fails or
the connection is closed normally, the stack clears this flag again. The occurrence of a possible
error is shown in the error code flags.
SOCK_CONNECTED (Bit 1)
This flag indicates that the state of the TCP state machine is established. If set, data transfer
using the appropriate API function can take place. On closing or resetting a connection this flag
is cleared.
SOCK_DATA_AVAILABLE (Bit 2)
This flag informs the application that a new TCP segment has just arrived and can be read out of
the receive buffer. To get simple access to this buffer, the pointer TCP_RX_BUF should be
used. The variable TCPRxDataCount contains the amount of data received. After reading the
contents of the buffer, the application should release the buffer by calling the API function
TCPReleaseRxBuffer() immediately so that the stack can fill in new data (see Figure 12). If the
buffer is not released for a longer time and therefore a lot of TCP segments have to be
discarded, the connection can be reset by the other TCP.
Yes
DATA_AVAILABLE? No. of Bytes Rec'd = TCPRxDataCount
No
Read Out and Process rx Buffer Starting With
Address TCP_RX_BUF
TCPReleaseRxBuffer()
SOCK_TX_BUF_RELEASED (Bit 3)
This flag indicates whether the application can change the contents of the transmit buffer or
modify the TCPTxDataCount variable. This flag is set by the stack if the previous packet sent
was acknowledged properly. This realizes a kind of handshake mechanism to protect the
transmit buffer from overwriting its contents. For the common way of sending data, see
description of the function TCPTransmitTxBuffer().
SOCK_ERROR (Bits 4 to 7)
If an error occurs while initiating a connection or transferring data, the stack writes an error code
to the upper nibble of register SocketStatus. By reading and interpreting this value, the
application can find out the reason for this error. It is recommended to get the error code by
isolating the upper nibble (AND-operation with SOCK_ERROR_MASK). The occurring of an
error but SOCK_ERR_OK immediately closes the connection. Table 6 gives an overview about
the error codes.
TCPLowLevelInit()
TCPLocalPort = TCP_PORT_HTTP
No
SOCK_ACTIVE? TCPPassiveOpen()
Yes
DoNetworkStuff()
HTTPServer()
<html>
<head>
<meta http-equiv=“refresh” content=“5”>
<title>easyWEB - dynamic Webside</title>
</head>
<p><b>MCU Temperature:</b></p>
<table bgcolor=“#ff0000” border=“5” cellpadding=“0” cellspacing=“0” width=“500”>
<tr>
<td>
<table width=“ADA%” border=“0” cellpadding=“0” cellspacing=“0”>
<tr><td bgcolor=“#00ff00”> </td></tr>
</table>
</td>
</tr>
</table>
5 References
1. TCP/IP Running a Successful Network by Washburn, K., Evans, J. Addison Wesley, 1996
2. Internet Protocol (IP) by Postel, J., RFC 791†
3. Internet Control Message Protocol by Postel, J., RFC 792†
4. Transmission Control Protocol by Postel, J., RFC 793†
5. An Ethernet Address Resolution Protocol by Plummer, D., RFC 826†
6. Requirements for Internet Hosts by Braden, R., RFC 1122†
7. MSP430x13x, MSP430x14x Mixed Signal Microcontroller Data Sheet (SLAS272)
8. CS8900A Product Data Sheet. Cirrus™ Logic, Inc., 1999‡
9. CS8900A Ethernet Controller Technical Reference Manual (AN083). Cirrus Logic Inc., 2001‡
10. Using the Crystal CS8900A in 8-Bit Mode (AN181). Cirrus Logic, Inc., 2000‡
† Request for Comments is a collection of papers of Internet-related topics. Available for download at http://www.faqs.org/rfcs/index.html
‡ Available for download from the Cirrus Logic home page at http://www.crystal.com
Texas Instruments Incorporated and its subsidiaries (TI) reserve the right to make corrections, modifications,
enhancements, improvements, and other changes to its products and services at any time and to discontinue
any product or service without notice. Customers should obtain the latest relevant information before placing
orders and should verify that such information is current and complete. All products are sold subject to TI’s terms
and conditions of sale supplied at the time of order acknowledgment.
TI warrants performance of its hardware products to the specifications applicable at the time of sale in
accordance with TI’s standard warranty. Testing and other quality control techniques are used to the extent TI
deems necessary to support this warranty. Except where mandated by government requirements, testing of all
parameters of each product is not necessarily performed.
TI assumes no liability for applications assistance or customer product design. Customers are responsible for
their products and applications using TI components. To minimize the risks associated with customer products
and applications, customers should provide adequate design and operating safeguards.
TI does not warrant or represent that any license, either express or implied, is granted under any TI patent right,
copyright, mask work right, or other TI intellectual property right relating to any combination, machine, or process
in which TI products or services are used. Information published by TI regarding third-party products or services
does not constitute a license from TI to use such products or services or a warranty or endorsement thereof.
Use of such information may require a license from a third party under the patents or other intellectual property
of the third party, or a license from TI under the patents or other intellectual property of TI.
Reproduction of information in TI data books or data sheets is permissible only if reproduction is without
alteration and is accompanied by all associated warranties, conditions, limitations, and notices. Reproduction
of this information with alteration is an unfair and deceptive business practice. TI is not responsible or liable for
such altered documentation.
Resale of TI products or services with statements different from or beyond the parameters stated by TI for that
product or service voids all express and any implied warranties for the associated TI product or service and
is an unfair and deceptive business practice. TI is not responsible or liable for any such statements.
Following are URLs where you can obtain information on other Texas Instruments products and application
solutions:
Products Applications
Amplifiers amplifier.ti.com Audio www.ti.com/audio
Data Converters dataconverter.ti.com Automotive www.ti.com/automotive
DSP dsp.ti.com Broadband www.ti.com/broadband
Interface interface.ti.com Digital Control www.ti.com/digitalcontrol
Logic logic.ti.com Military www.ti.com/military
Power Mgmt power.ti.com Optical Networking www.ti.com/opticalnetwork
Microcontrollers microcontroller.ti.com Security www.ti.com/security
Telephony www.ti.com/telephony
Video & Imaging www.ti.com/video
Wireless www.ti.com/wireless