187
2006 Corporate Seminar : TCP/IP TCP/IP ENC28J60 April 26 th , 2006 Philip Seo CAE, Microchip Korea

TCP IP 2006 Corp Seminar

Embed Size (px)

DESCRIPTION

PIC MICROCONTROLLER TCP /IP

Citation preview

2006 Corporate Seminar : TCP/IP

TCP/IP – ENC28J60

April 26th, 2006

Philip Seo

CAE, Microchip Korea

Advanced Solutions SellingAdvanced Solutions Selling

2006 Corporate Seminar : TCP/IP

Contents

Ethernet OverviewEthernet Overview

Microchip Ethernet Solution

LAB 1 : Configuring the Network

TCP/IP Stack Overview Network Concept

Basic TCP/IP Review

Networking Concept

Microchip TCP/IP Stack & HTTP Server Microchip TCP/IP Stack Overview

Microchip File System

Lab 2 – Using Microchip File System

HTTP Server

Lab 3 – Using HTTP to monitor & control

Lab 4 – Using HTTP to download info

Lab 5 – Custom UDP application

2006 Corporate Seminar : TCP/IP

Ethernet Overview

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 4

Ethernet

Page 5

Connectivity SummaryConnectivity Summary

13941394--Fire Wire Fire Wire

1 Gb1 Gb480 Mb/s480 Mb/s100 Mb/s100 Mb/s12 Mb/s12 Mb/s1.5 Mb/s1.5 Mb/s1 Mb/s1 Mb/s500 Kb/s500 Kb/s

FSFS--USBUSB

EthernetEthernet

CANCAN

SerialSerial

HSHS--USBUSB

USB 1.1USB 1.1

USB 2.0USB 2.0

Parallel PortParallel Port

WiFi (b/g)WiFi (b/g)

PCIPCI

AGPAGP

TodayToday

TomorrowTomorrow

Unlikely Unlikely

LSLS--USBUSB

10Mb/s10Mb/s

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 6

Why Ethernet?

Ethernet is the most widely deployed network in offices and industrial buildings

Ethernet’s infrastructure, interoperability and scalability ensure ease of development

Once equipment is connected to a Ethernet network, it can be monitored or controlled through the Internet

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 7

How does Ethernet work?

Carrier Sense Multiple Access w/Collision Detect

- Carrier Sense - each interface must wait until there is no signal before transmitting

- Multiple Access - all interfaces have equal priority on the network

- Collision Detect - when interfaces transmit simultaneously, the collision is detected and the data is retransmitted

Collisions are normal & expected events

- Interfaces wait random amounts of time to retransmit

Page 8

Ethernet Market TrendsEthernet Market Trends

Industrial and businesses are already wiredIndustrial and businesses are already wired

Ethernet is the deEthernet is the de--facto standard for wired facto standard for wired commscomms

No longer PC centricNo longer PC centric

Ethernet speeds will continue to increaseEthernet speeds will continue to increase

Installation costs high but installed base is massiveInstallation costs high but installed base is massive

Wireless is in its infancyWireless is in its infancy

VOIP allows speech over the internetVOIP allows speech over the internet

VVoice oice OOver ver IInternet nternet PProtocol is the fastest growing arearotocol is the fastest growing area

Wireless VOIP is new but will be significantWireless VOIP is new but will be significant

Page 9

ApplicationsApplications

Fire & Safety PanelsFire & Safety Panels

Industrial ControlIndustrial Control

Access ControlAccess Control

Industrial printerIndustrial printer

Label printerLabel printer

Hotel minibarHotel minibar

Home automationHome automation

VOIP intercomVOIP intercom

MeteringMetering

SpeakersSpeakers

Environmental monitoringEnvironmental monitoring

Kitchen appliancesKitchen appliances

Drink dispenserDrink dispenser

Network monitoringNetwork monitoring

InstrumentsInstruments

Server monitoringServer monitoring

Fingerprint recognitionFingerprint recognition

Medicine dispensingMedicine dispensing

Page 10

Ethernet InstallationsEthernet Installations

Where else would you find Ethernet installed?Where else would you find Ethernet installed?

Commercial buildings (Retail / Warehousing etc)Commercial buildings (Retail / Warehousing etc)

Industrial (Factories etc)Industrial (Factories etc)

OfficesOffices

HotelsHotels

HomesHomes

BridgesBridges-- CAN CAN –– EthernetEthernet

-- Zigbee Zigbee –– EthernetEthernet

-- USB USB –– EthernetEthernet

Page 11

Market DriversMarket Drivers

Industrial Applications:Industrial Applications:

-- Access controlAccess control

-- Security camerasSecurity cameras

-- Fire panelsFire panels

-- Industrial PrintersIndustrial Printers

VoIPVoIP::

-- AdaptersAdapters

-- PhonesPhones

ZellwegerZellweger Gas DetectorGas Detector

Smart Card ReaderSmart Card Reader

PrintersPrintersSecurity CamerasSecurity Cameras

Page 12

Power Over EthernetPower Over Ethernet

Powers devices connected to EthernetPowers devices connected to EthernetNew MarketNew Market

-- Does not require mains to be routed to deviceDoes not require mains to be routed to device

-- Reduces installation costs greatly Reduces installation costs greatly

-- Reduces cable runs Reduces cable runs

-- It a worldwide standardIt a worldwide standard

-- 48 Volts48 Volts

ZellwegerZellweger Gas DetectorGas DetectorSmart Card ReaderSmart Card Reader

Smart Card LockSmart Card Lock

Ethernet ClockEthernet Clock

Security CamerasSecurity Cameras

Page 13

VoIP Phone AdapterVoIP Phone Adapter

ADSLADSLADSL COMPUTER

ADSL MODEM

Page 14

VoIP Phone AdapterVoIP Phone Adapter

ADSLADSLADSL

Standard wired phone Standard wired phone

Router VOIP Adapter

COMPUTER

Page 15

VoIP Phone AdapterVoIP Phone Adapter

Page 16

Page 17

ENC28J60 ENC28J60 Product SummaryProduct Summary

WorldWorld’’s Smallest Ethernet Controller:s Smallest Ethernet Controller:-- Minimizing board space, cost, complexityMinimizing board space, cost, complexity

OptimisedOptimised for Embedded Solutionsfor Embedded Solutions

ENC28J60 highly integrated ENC28J60 highly integrated -- OnOn--chip 10Mbps MAC/PHY, 8Kb Buffer RAM, SPIchip 10Mbps MAC/PHY, 8Kb Buffer RAM, SPITM TM

serial interface, 28serial interface, 28--pin package pin package

Microchip offers FREE TCP/IP StackMicrochip offers FREE TCP/IP Stack-- Modular design, no license/royalty feesModular design, no license/royalty fees

Page 18

ENC28J60: Ethernet Controller ENC28J60: Ethernet Controller

Provides Remote Application AccessProvides Remote Application Access

Page 19

ENC28J60ENC28J60WorldWorld’’s Smallest Ethernet Controller!s Smallest Ethernet Controller!

INT, WOL

MCU

MAC Address from IEEE $1500

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 20

Serial Ethernet Controller

INT, WOL

MCU

8Kbytes

Vdd range =>3.14 to 3.45V Temperature => 0C to 70C

IEEE 802.3

DIP, SOIC, SSOP, QFN

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 21

ENC28J60 Block Diagram

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 22

ENC28J60 External Connection

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 23

ENC28J60 Register Map

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 24

ENC28J60 Memory

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 25

ENC28J60 External Connection

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 26

ENC28J60 Transmit Packet Layout

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 27

ENC28J60 Receive Packet Layout

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 28

ENC28J60 SPI Instruction Set

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 29

ENC28J60 SPI READ

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 30

ENC28J60 SPI WRITE

Page 31

VoIP Phone AdapterVoIP Phone Adapter

Competitive 10 Mbps, 100-pin Device

Microchip 10 Mbps,ENC28J60: 28 Pins

SOIC, SDIP, SSOP,QFNSOIC, SDIP, SSOP,QFN

Current Part is a standard Current Part is a standard Network Interface Card ICNetwork Interface Card IC

DS

Page 32

Ethernet PICtailEthernet PICtail™™ #AC164121: #AC164121: Supporting Demo BoardsSupporting Demo Boards

PICDEM FS USB - $59

Future PICDEMTM II+ $99

PICDEM Z - $199

PICDEM LCD - $125PICDEM HPC Explorer -$59

Ethernet PICtailTM

Page 33

Competition SummaryCompetition Summary

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 34

Parallel Ethernet Controllers

RTL8019AS- IEEE 802.3 10Mbit

- 16Kbytes RAM, 100-pin QFP

- ISA Bus

CS8900A- IEEE 802.3 10Mibt

- 4Kbytes RAM, 100-pin QFP

- ISA Bus

LAN91C111- IEEE 802.3/802.3u 10/100 Mbit

- 8Kbytes RAM, 128-pin QFP

- ARM, PowerPC, MIPS 32-bit interface

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 35

Ethernet PICTailTM Daughter Board

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 36

Ethernet PICTailTM Daughter Board

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 37

dsPICDEM.net™ Board

10-base TEthernet

UART

LCD

ICD2

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 38

dsPIC30F ⇔ Ethernet Controller Connection (1 of 2)

PORTD

PORTD

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 39

dsPIC30F ⇔ Ethernet Controller Connection (2 of 2)

PORTDData I/OControl

RegisterAddress

40

Microchip’s PICDEM.netMicrochipMicrochip’’s PICDEM.nets PICDEM.net

PICDEM.net Kit includes:PICDEM.net board

PIC16F877

TCP/IP Lean book

Users Guide

Power Adapter

Ethernet Cable

PICDEM.net Connectivity Solutions CD-ROM

Price: $299USD

PICDEM.net Kit includes:PICDEM.net Kit includes:PICDEM.net boardPICDEM.net board

PIC16F877PIC16F877

TCP/IP LeanTCP/IP Lean bookbook

Users GuideUsers Guide

Power AdapterPower Adapter

Ethernet Cable Ethernet Cable

PICDEM.net Connectivity PICDEM.net Connectivity Solutions CDSolutions CD--ROMROM

Price: $299Price: $299USDUSD

41

*Hardware OverviewPICDEM.net™ Block Diagram

**Hardware OverviewHardware OverviewPICDEM.netPICDEM.net™™ Block DiagramBlock Diagram

Not all connections shown

VCCRB5/MCLR

AN0/RA0AN1/RA1

SCLSDA

PIC18F452

RA2RA3

RE2RE1RE0

RD7-0RB4-0

RC6/TXDRC5(CTS)RC7/RXDRC2(RTS)

S2S3

D6

D5

USER LEDs

JP2

24LC256

A2A1A0GND

VCCWP

SCLSDA

19.66MHz

RTL8019

D3

D1

20MHz

RSTDRV

IOWBIORBSD7-0SA4-0SA19-SA5

LED2LED1LED0

TPout+

TPout-TPin+

TPin-

D2

RJ45

TC232

T1INT2INR1OUTR2OUT

T1OUTT2OUT

R1INR2IN

1

3

2

4

5

6

7

8

9

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 42

Explore 16 + Ethernet Demo Kits

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 43

Integrated MCU + Ethernet

PIC18F97J60

- 64K, 96K or 128K bytes Flash

- 3.9K bytes RAM

- 8K bytes TX/RX Buffer

- 41.67MHz max

Package (TQFP)

- 64/80/100-Pins

Other:

- External Memory Bus

- 16 channel 10-bit A/DCommunication- Ethernet: MAC+PHY

(IEEE 802.3 10BASE-T)- 2 EUSARTs- MSSP (SPI /MI2C)

Peripherals- 16 ch. 10-Bit ADC- 2 Comparators- 5 Timers- CCP/ECCP modules

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 44

LAB1 : Configuring our Network

45

LAB1 : Ethernet Demo Kit ConnectionLAB1 : Ethernet Demo Kit ConnectionLAB1 : Ethernet Demo Kit Connection

PICDEM HPC Explorer Boardrunning Microchip TCP/IP Stack program

EthernetConnection

RJ-11 Phone Cable USB Cable

CAT-5 Crossover Cable

Optional

ICD 2 Jack

PC/Laptop running:

• MPLAB® IDE for ICD2 • IE for displaying HTML pages

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 46

LAB1 : Go to Network Connections

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 47

LAB1 : Network Connections Properties

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 48

LAB1 : Local Area Connection Properties

Highlight thisselection

Click thisbutton

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 49

LAB1 : Internet Protocol (TCP/IP) Properties

10 . 10 . 5 . 15

Select thisoption

Copy thesenumbers

Make sure thelast numberis board + 1

10 . 10 . 5 . 16

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 50

Lab #1

Goal: Setup Computer & Board

Open LAB.PJT in C:₩Ethernet₩LAB

Edit address

- S1 + RESET Button : Menu Selection

- Select “2. Change default IP address”- Insert “New IP Address” -> Enter

Compile & Download program

Open Internet Explorer, Type in IP address of your board

2006 Corporate Seminar : TCP/IP

TCP/IP Stack Overview

© 2001 Microchip Technology Incorporated. All Rights Reserved. . S4601 Internet Connectivity Internet Connectivity 5252

What is a network?What is a network?What is a network?

network

a computer or telecommunications system linked to permit exchange of information

network

a computer or telecommunications system linked to permit exchange of information

© 2001 Microchip Technology Incorporated. All Rights Reserved. . S4601 Internet Connectivity Internet Connectivity 5353

What is a network?What is a network?What is a network?

internet

(Lower case i) any time you connect 2 or more networks together, you have an internet - as in inter-national or inter-state

Also known as a network

internet

(Lower case i) any time you connect 2 or more networks together, you have an internet - as in inter-national or inter-state

Also known as a network

© 2001 Microchip Technology Incorporated. All Rights Reserved. . S4601 Internet Connectivity Internet Connectivity 5454

What is a network?What is a network?What is a network?

intranet

a network operating like the World Wide Web but having access restricted to a limited group of authorized users (as employees of a company)

intranet

a network operating like the World Wide Web but having access restricted to a limited group of authorized users (as employees of a company)

© 2001 Microchip Technology Incorporated. All Rights Reserved. . S4601 Internet Connectivity Internet Connectivity 5555

What is a network?What is a network?What is a network?

Internet

(Upper case I) The vast collection of inter-connected networks that all use the TCP/IP protocols and that evolved from the ARPANET of the late 60’s and early 70’sThe Internet now connects roughly 60,000 independent networks into a vast global internet

Internet

(Upper case I) The vast collection of inter-connected networks that all use the TCP/IP protocols and that evolved from the ARPANET of the late 60’s and early 70’sThe Internet now connects roughly 60,000 independent networks into a vast global internet

© 2001 Microchip Technology Incorporated. All Rights Reserved. . S4601 Internet Connectivity Internet Connectivity 5656

What is a network?What is a network?What is a network?

LAN

a computer network limited to the immediate area, usually the same building or floor of a building

LAN

a computer network limited to the immediate area, usually the same building or floor of a building

© 2001 Microchip Technology Incorporated. All Rights Reserved. . S4601 Internet Connectivity Internet Connectivity 5757

What is a network?What is a network?What is a network?

WAN

any internet or network that covers an area larger than a single building or campus

WAN

any internet or network that covers an area larger than a single building or campus

© 2001 Microchip Technology Incorporated. All Rights Reserved. . S4601 Internet Connectivity Internet Connectivity 5858

What devices make up a network?

What devices make up a What devices make up a network?network?

client

software used to contact and obtain data from Server software on another computer

designed to work with one or more specific kinds of Server programs, and each Server requires a specific kind of Client

a Web Browser is a specific kind of Client

client

software used to contact and obtain data from Server software on another computer

designed to work with one or more specific kinds of Server programs, and each Server requires a specific kind of Client

a Web Browser is a specific kind of Client

© 2001 Microchip Technology Incorporated. All Rights Reserved. . S4601 Internet Connectivity Internet Connectivity 5959

What devices make up a network?

What devices make up a What devices make up a network?network?

server

a computer or software package that provides services to clients running on other computers

can refer to a particular piece of software or to the machine which is running the software

A server machine can run different server software packages providing many different servers to clients on a network

server

a computer or software package that provides services to clients running on other computers

can refer to a particular piece of software or to the machine which is running the software

A server machine can run different server software packages providing many different servers to clients on a network

© 2001 Microchip Technology Incorporated. All Rights Reserved. . S4601 Internet Connectivity Internet Connectivity 6060

What devices make up a network?

What devices make up a What devices make up a network?network?

router

a special-purpose computer or software package that handles the connection between 2 or more networks

routers spend all their time looking at the destination addresses of the packetspassing through them and deciding which route to send them on

router

a special-purpose computer or software package that handles the connection between 2 or more networks

routers spend all their time looking at the destination addresses of the packetspassing through them and deciding which route to send them on

© 2001 Microchip Technology Incorporated. All Rights Reserved. . S4601 Internet Connectivity Internet Connectivity 6161

What devices make up a network?

What devices make up a What devices make up a network?network?

gateway

protocol converter

an application-specific node that connects otherwise incompatible networks

converts data codes and transmission protocols to enable interoperability between networks

gateway

protocol converter

an application-specific node that connects otherwise incompatible networks

converts data codes and transmission protocols to enable interoperability between networks

62

Modem USART Ethernet

PPP SLIP DHCP ARP

IP

ICMP

UDP TCP

SNMP (T)FTP

Internet Protocol StackInternet Protocol Stack

Physical Layer - communications medium such as telephone wires,

CAT-5 cable, etc.

Network Access Layer - manages HW interface to communications medium

Internet Layer - implements addressing and routing for transmitting/receiving data

Transport Layer - implements reliablecommunication over the Internet Layer

Application Layer - web browsers, email and other user oriented servicesHTTP SMTP

Basic TCP/IP ReviewBasic TCP/IP ReviewBasic TCP/IP Review

63

Internet Protocol Stack LayersInternet Protocol Stack LayersInternet Protocol Stack Layers

Physical Layer - communications medium such as telephone wires, CAT-5 cable, etc.

Network Access Layer - manages hardware interface to communications medium

Internet Layer - implements addressing and routing for transmitting and receiving data

Transport Layer - implements reliable communication over the Internet Layer

Application Layer - web browsers, email and other user oriented services

Physical Layer - communications medium such as telephone wires, CAT-5 cable, etc.

Network Access Layer - manages hardware interface to communications medium

Internet Layer - implements addressing and routing for transmitting and receiving data

Transport Layer - implements reliable communication over the Internet Layer

Application Layer - web browsers, email and other user oriented services

64

Basic TCP/IP ReviewBasic TCP/IP ReviewBasic TCP/IP Review

ProtocolProtocol DescriptionDescription

PPP PPP PointPoint--toto--Point ProtocolPoint Protocol

IPIP Internet ProtocolInternet Protocol

TCPTCP Transmission Control ProtocolTransmission Control Protocol

UDPUDP User Datagram ProtocolUser Datagram Protocol

SMTPSMTP Simple Mail Transfer ProtocolSimple Mail Transfer Protocol

FTPFTP File Transfer ProtocolFile Transfer Protocol

HTTPHTTP Hyper Text Transfer ProtocolHyper Text Transfer Protocol

RFCRFC Request For CommentRequest For Comment

For a complete glossary, search the For a complete glossary, search the ““RFCRFC’’s, go to: s, go to: http://www.ietf.org/rfc/rfc1983.txt?number=1983http://www.ietf.org/rfc/rfc1983.txt?number=1983

65

Basic TCP/IP Review IETF RFCs Recommended Reading List

Basic TCP/IP Review Basic TCP/IP Review IETF RFCs Recommended Reading ListIETF RFCs Recommended Reading List

RFC Description172 FTP File Transfer Protocol768 UDP User Datagram Protocol791 IP Internet Protocol793 TCP Transmission Control Protocol821 SMTP Simple Mail Transfer Protocol937 POP3 Post Office Protocol1055 SLIP Nonstandard for transmission of IP

datagrams over serial lines1122 Protocol walkthroughs1123 Protocol walkthroughs1331, 1661 PPP The Point-to-Point Protocol1332 IPCP The PPP Internet Protocol Control Protocol1334 PPP Authentication Protocols1350 TFTP Trivial File Transfer Protocol1541 DHCP Dynamic Host Configuration Protocol1542 BOOTP Bootstrap Protocol2854 HTML Hyper-Text Markup Language

(http://www.w3c.org/)

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 66

Ethernet Packet

FCS

7

1

6

6

2

46-1500

4

Filtered out by the MACStart-of-Frame DelimiterFiltered out by the MAC

Destination Address

Source AddressType of Packet or the Length of the Packet

Packet Payload(with optional padding)

Frame Check Sequence - CRC

Used in thecalculationof the FCS

Numberof Bytes Field Comments

Data

Padding

Type/Length

SA

DA

SFD

Preamble

67

Physical LayerPhysical LayerPhysical Layer

Physical Layers

Takes many forms

Telephone Line (modem, DSL)

Twisted pair, coaxial, fiber optic, RF (Ethernet)

Supports many data rates

Modem - up to 56 Kbps

Ethernet - up to 1 Gbps

Physical Layers

Takes many forms

Telephone Line (modem, DSL)

Twisted pair, coaxial, fiber optic, RF (Ethernet)

Supports many data rates

Modem - up to 56 Kbps

Ethernet - up to 1 Gbps

68

Network Access LayerNetwork Access LayerNetwork Access Layer

Network Access Layer - PPP (RFC 1661)

Point-to-Point Protocol

most well known as a protocol that allows a computer to use a regular telephone line and a modem to make TCP/IP connections to the Internet

Network Access Layer - PPP (RFC 1661)

Point-to-Point Protocol

most well known as a protocol that allows a computer to use a regular telephone line and a modem to make TCP/IP connections to the Internet

69

Network Access LayerNetwork Access LayerNetwork Access Layer

Network Access Layer - DHCP (RFC 1541)

Dynamic Host Configuration Protocola protocol for assigning dynamic IP addresses to devices on a network

Network Access Layer - ARP (RFC 826)

Address Resolution Protocol

protocol used to convert an IP address into a physical address (i.e. Ethernet address)

Network Access Layer - DHCP (RFC 1541)

Dynamic Host Configuration Protocola protocol for assigning dynamic IP addresses to devices on a network

Network Access Layer - ARP (RFC 826)

Address Resolution Protocol

protocol used to convert an IP address into a physical address (i.e. Ethernet address)

70

Internet LayerInternet LayerInternet Layer

Internet Layer - IP (RFC 791)

Internet Protocol

specifies the format of packets, also called datagrams, and the addressing scheme

Handles routing of data over the arbitrary collections of networks called the Internet

Most networks combine IP with a Transport Layer protocol, which establishes a virtual connection between a destination and a source

Internet Layer - IP (RFC 791)

Internet Protocol

specifies the format of packets, also called datagrams, and the addressing scheme

Handles routing of data over the arbitrary collections of networks called the Internet

Most networks combine IP with a Transport Layer protocol, which establishes a virtual connection between a destination and a source

71

IP Header FormatIP Header FormatIP Header Format

00 44 8822 66

VersionHdr len Service Length Ident

FlagsFragment Offset

Timeto live Pcol Checksum Source Address

Destination Address

Header options0 - 40 bytes

IP data0 - ? bytes

00

88

1616

2020

Header length is default 20 bytes long

72

Internet LayerInternet LayerInternet Layer

Internet Layer - ICMP (RFC 792)

Internet Control Message Protocol

an extension to IP

Handles transfer of messages containing error, control, and informational data

PING, for example, is a ICMP echo request/reply to see if a computer exists

Internet Layer - ICMP (RFC 792)

Internet Control Message Protocol

an extension to IP

Handles transfer of messages containing error, control, and informational data

PING, for example, is a ICMP echo request/reply to see if a computer exists

73

Transport LayerTransport LayerTransport Layer

Transport Layer - UDP (RFC 768)

User Datagram Protocol

a connectionless protocol that runs on top of IP networks

provides very few error recovery services, offering instead a direct way to send and receive datagrams over an IP network

used primarily for broadcasting messages over a network

Transport Layer - UDP (RFC 768)

User Datagram Protocol

a connectionless protocol that runs on top of IP networks

provides very few error recovery services, offering instead a direct way to send and receive datagrams over an IP network

used primarily for broadcasting messages over a network

74

UDP Packet FormatUDP Packet FormatUDP Packet Format

00 44 8822 66

Source Port Destination Port Message Length Checksum

Data

00

88

75

Transport LayerTransport LayerTransport Layer

Transport Layer - TCP (RFC 793)

Transmission Control Protocol

one of the main protocols used in networks

enables two hosts to establish a connection and exchange streams of data

guarantees delivery of data and also guarantees that packets will be re-assembled in the same order in which they were sent

Transport Layer - TCP (RFC 793)

Transmission Control Protocol

one of the main protocols used in networks

enables two hosts to establish a connection and exchange streams of data

guarantees delivery of data and also guarantees that packets will be re-assembled in the same order in which they were sent

76

TCP FunctionsTCP FunctionsTCP Functions

Why is TCP so difficult?Initiate a connection between two computers

Send data bi-directionally between 2 computers

Handle loss of data on the network

Handle duplication of data on the network

Handle reception of packets out of order

Handle network failure

Handle data rates from single byte to bulk transfers

Provide flow control to prevent data overload

Close connection between 2 computers

Support partially closed connection

Handle data arrival after connection closed

Why is TCP so difficult?Initiate a connection between two computers

Send data bi-directionally between 2 computers

Handle loss of data on the network

Handle duplication of data on the network

Handle reception of packets out of order

Handle network failure

Handle data rates from single byte to bulk transfers

Provide flow control to prevent data overload

Close connection between 2 computers

Support partially closed connection

Handle data arrival after connection closed

77

TCP Packet FormatTCP Packet FormatTCP Packet Format

00 44 8822 66

Source Port Destination Port Sequence Number

Acknowledgement Number HeaderLength

Urgent Pointer

Data

00

88

1616Checksum

Flags Window

Options2020

78

Applications ProtocolsApplications ProtocolsApplications Protocols

In addition to the basic protocols, application protocols allow communication of information

Mail

Web browsing

Network management

File Transfer

Application protocols run on top of the basic protocols

In addition to the basic protocols, application protocols allow communication of information

Mail

Web browsing

Network management

File Transfer

Application protocols run on top of the basic protocols

79

Application LayerApplication LayerApplication Layer

Application Layer - SMTP (RFC 821)

Simple Mail Transfer Protocol

a protocol for sending email messages between servers

generally used to send messages from a mail client to a mail server

Application Layer - SMTP (RFC 821)

Simple Mail Transfer Protocol

a protocol for sending email messages between servers

generally used to send messages from a mail client to a mail server

80

Application LayerApplication LayerApplication Layer

Application Layer - HTTP (RFC 2616)

HyperText Transfer Protocol

underlying protocol for World Wide Web

defines how messages are formatted and transmitted, what actions web servers and browsers should respond to commands

enter a URL in web browser, sends an HTTP command to the Web server directing it to fetch and transmit the requested web page

Application Layer - HTTP (RFC 2616)

HyperText Transfer Protocol

underlying protocol for World Wide Web

defines how messages are formatted and transmitted, what actions web servers and browsers should respond to commands

enter a URL in web browser, sends an HTTP command to the Web server directing it to fetch and transmit the requested web page

81

Application LayerApplication LayerApplication Layer

Application Layer - TFTP (RFC 1350)

Trivial File Transfer Protocol

a simple form of the FTP

uses UDP and provides no security features

often used by servers to boot diskless workstations, X-terminals, and routers

Application Layer - TFTP (RFC 1350)

Trivial File Transfer Protocol

a simple form of the FTP

uses UDP and provides no security features

often used by servers to boot diskless workstations, X-terminals, and routers

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 82

Networking

Three ways to communicate

- Wired dial-up

- SLIP, PPP, etc.

- Wireless Ethernet

- 948 WLC presented by Fred Eady

- www.edtp.com

- TRENDnet TEW-222CF 802.11b RF card

- Wired Ethernet

- Subject of this class

83

Network TopologiesNetwork TopologiesNetwork Topologies

Serial link

Three wires connect computers together

Ground

A transmit to B receive

B transmit to A receive

Serial link

Three wires connect computers together

Ground

A transmit to B receive

B transmit to A receive

AA BB

84

Network TopologiesSerial Link

Network TopologiesNetwork TopologiesSerial LinkSerial Link

Both computers have equal access to the link

There are only two computers on the network

A computer can transmit data at any time

Message delivery is reliable

The serial data is a free-format stream of bytes, with little or no integrity checking

There is no limit on message size

There is no need for addressing

Both computers have equal access to the link

There are only two computers on the network

A computer can transmit data at any time

Message delivery is reliable

The serial data is a free-format stream of bytes, with little or no integrity checking

There is no limit on message size

There is no need for addressing

85

Network TopologiesSerial Link

Network TopologiesNetwork TopologiesSerial LinkSerial Link

TCP/IP assumes data is sent in blocks with defined beginning and end

Serial driver resides on top of serial link

Serial Line Internet ProtocolEnd of each block signaled by a C0h byte

Most SLIP drivers send C0h at beginning to clear out any garbage characters

Maximum 1006 bytes per block

TCP/IP assumes data is sent in blocks with defined beginning and end

Serial driver resides on top of serial link

Serial Line Internet ProtocolEnd of each block signaled by a C0h byte

Most SLIP drivers send C0h at beginning to clear out any garbage characters

Maximum 1006 bytes per block

ENDC0h

ENDC0h

Data1 - 1006 bytes

SLIP frameSLIP frame

86

Network TopologiesNetwork TopologiesNetwork Topologies

Network

Computers are connected to a common cable or to a hub

A hub copies the signals and is essentially transparent to the computer

Network

Computers are connected to a common cable or to a hub

A hub copies the signals and is essentially transparent to the computer

Network - bus topology Network - star topology

87

Network TopologiesNetwork (Ethernet)Network TopologiesNetwork TopologiesNetwork (Ethernet)Network (Ethernet)

All computers on the network have equal access to the network

All computers have a unique 48-bit address

Any computer may transmit on the network when it is idle

Message delivery is unreliable

All data on the network is in blocks (frames) with a defined beginning and end and integrity check

The network can send a maximum of 1500 bytes per frame

All messages are equipped with a source and destination address

All computers on the network have equal access to the network

All computers have a unique 48-bit address

Any computer may transmit on the network when it is idle

Message delivery is unreliable

All data on the network is in blocks (frames) with a defined beginning and end and integrity check

The network can send a maximum of 1500 bytes per frame

All messages are equipped with a source and destination address

88

Network TopologiesNetwork (Ethernet)Network TopologiesNetwork TopologiesNetwork (Ethernet)Network (Ethernet)

Ethernet frames include

Destination address

Source address

Type/Length field

Data

CRC

Ethernet frames include

Destination address

Source address

Type/Length field

Data

CRC

Dest6 bytes

Source6 bytes

Type2 bytes

CRC4 bytes

Data46 - 1500 bytes

Ethernet frame 64 Ethernet frame 64 -- 1518 bytes1518 bytes

89

TCP Packet FormatTCP Packet FormatTCP Packet Format

00 44 8822 66

Source Port Destination Port Sequence Number

Acknowledgement Number HeaderLength

Urgent Pointer

Data

00

88

1616Checksum

Flags Window

Options2020

Bytes

90

UDP Packet FormatUDP Packet FormatUDP Packet Format

00 44 8822 66

Source Port Destination Port Message LengthChecksum

(Ignore: 0x0000)

Data

00

88

Bytes

91

IP Header FormatIP Header FormatIP Header Format

00 44 8822 66VersionHdr len Service Length Ident

FlagsFragment Offset

Timeto live Pcol Checksum Source Address

Destination Address

Header options0 - 40 bytes

IP data0 - N bytes

00

88

1616

2020

Header length is default 20 bytes long

Bytes

92

Transporting TCP/IPTransporting TCP/IPTransporting TCP/IP

Ether IP TCP/UDP User Payload CRC

16 bitchecksum

16 bitchecksum

93

Transporting TCP/IPTransporting TCP/IPTransporting TCP/IP

Ether IP TCP/UDP User Payload CRC

16 bitchecksum

16 bitchecksum

Handled by datalink (hardware and/or software)Handled byHandled by datalinkdatalink (hardware and/or software)(hardware and/or software)

94

Transporting TCP/IPTransporting TCP/IPTransporting TCP/IP

Ether IP TCP/UDP User Payload CRC

16 bitchecksum

16 bitchecksum

Handled by datalink (hardware and/or software)

Handled by stack (segment discard on checksum fail)

Handled byHandled by datalinkdatalink (hardware and/or software)(hardware and/or software)

Handled by stack (segment discard on checksum fHandled by stack (segment discard on checksum fail)ail)

95

Transporting TCP/IPTransporting TCP/IPTransporting TCP/IP

Ether IP TCP/UDP User Payload CRC

16 bitchecksum

16 bitchecksum

Handled by datalink (hardware and/or software)

Handled by stack (segment discard on checksum fail)

Handled by stack (checksum test deferred)

Checksum appears in header

Value set so overall sum is FFFF

Handled byHandled by datalinkdatalink (hardware and/or software)(hardware and/or software)

Handled by stack (segment discard on checksum fHandled by stack (segment discard on checksum fail)ail)

Handled by stack (checksum test deferred)Handled by stack (checksum test deferred)

Checksum appears in headerChecksum appears in header

Value set so overall sum is FFFFValue set so overall sum is FFFF

96

Transporting TCP/IPTransporting TCP/IPTransporting TCP/IP

Ether IP TCP/UDP User Payload CRC

16 bitchecksum

16 bitchecksum

Handled by datalink (hardware and/or software)

Handled by stack (segment discard on checksum fail)

Handled by stack (checksum test deferred)

Checksum appears in header

Value set so overall sum is FFFF

Passed to application

Data streamed up as it arrives

Checksum pass/fail notified at end of data

Handled byHandled by datalinkdatalink (hardware and/or software)(hardware and/or software)

Handled by stack (segment discard on checksum fHandled by stack (segment discard on checksum fail)ail)

Handled by stack (checksum test deferred)Handled by stack (checksum test deferred)

Checksum appears in headerChecksum appears in header

Value set so overall sum is FFFFValue set so overall sum is FFFF

Passed to applicationPassed to application

Data streamed up as it arrivesData streamed up as it arrives

Checksum pass/fail notified at end of dataChecksum pass/fail notified at end of data

97

Network DiagramNetwork DiagramNetwork Diagram

SUBNET 1SUBNET 1

SUBNET 2SUBNET 2

SUBNET 3SUBNET 3

LINK TO OTHER NETWORKLINK TO OTHER NETWORK

ROUTERROUTER

ROUTERROUTER

ROUTERROUTER

ROUTERROUTER

98

Physical Layer AddressingPhysical Layer AddressingPhysical Layer Addressing

Ethernet

Each device on the network has a unique six byte physical address

Highly specific to the hardware

Upper 3 bytes are Organizationally Unique ID

Buy from IEEE for $1500

Lower 3 bytes are serial number

Cumbersome to use to transfer information

Need a logical address

Ethernet

Each device on the network has a unique six byte physical address

Highly specific to the hardware

Upper 3 bytes are Organizationally Unique ID

Buy from IEEE for $1500

Lower 3 bytes are serial number

Cumbersome to use to transfer information

Need a logical address

99

Internet Layer AddressingInternet Layer AddressingInternet Layer Addressing

IP Address

Uses the Network Access Layer protocols to assign logical address to physical address

4 byte number represents:

Network address - uniquely identifies an organization

Subnet address - identifies a subnet within the organization

System address - identifies a single node on the subnet

IP Address

Uses the Network Access Layer protocols to assign logical address to physical address

4 byte number represents:

Network address - uniquely identifies an organization

Subnet address - identifies a subnet within the organization

System address - identifies a single node on the subnet

100

Network AddressingNetwork AddressingNetwork Addressing

Network needs to know if the recipient is on the same subnet

Does it send the message directly

Does it sent the message through a router

Each node has a subnet mask

Logically ANDed with IP address & compared

Network needs to know if the recipient is on the same subnet

Does it send the message directly

Does it sent the message through a router

Each node has a subnet mask

Logically ANDed with IP address & compared Node 1Node 1

123.45.67.8123.45.67.8255.255.255.0255.255.255.0123.45.67.0123.45.67.0

Node 2Node 2123.45.78.9123.45.78.9255.255.0.0255.255.0.0123.45.0.0123.45.0.0

IP AddressIP AddressSubnet MaskSubnet MaskResulting SubnetResulting Subnet

101

Connection Orientated Model (TCP)Connection Orientated Model (TCP)Connection Orientated Model (TCP)

1. Request Connection

TCP provides Connection-orientated services to upper layer TCP/IP and User applicationsTCP provides ConnectionTCP provides Connection--orientated services to upper layer TCP/IP and orientated services to upper layer TCP/IP and User applicationsUser applications

3. Session Established, Transmit Data Units

5. Transmit n Data Units

7. Done, disconnecting

2. Connection acknowledged Request n Data Units

4. Received, send n more.

6. Received,send n more

8. OK, terminating session

Internet

Originating host

Destination host

102

Connectionless Model (UDP)Connectionless Model (UDP)Connectionless Model (UDP)

1. Ready or not, I’m sending n data units to you

UDP provides Connection-LESS services to upper layer UDP/IP and User applicationsUDP provides ConnectionUDP provides Connection--LESS services to upper layer UDP/IP and User LESS services to upper layer UDP/IP and User applicationsapplications

2. Done

Internet

Originating host

Destination host

103

Why TCP/IP?Why TCP/IP?Why TCP/IP?

Not the only option (CAN, ARC, MODBUS, proprietary), but certainly the most popular one. Basis for the Internet. The role of private LANs.

Suitable for most but not all applications

Benefit from the wide availability of tools and expertise

TCP vs. UDP – if TCP guarantees delivery, and UDP is “unreliable”, why is UDP still around ? Critical application design decisions

Not the only option (CAN, ARC, MODBUS, Not the only option (CAN, ARC, MODBUS, proprietary), but certainly the most popular proprietary), but certainly the most popular one. Basis for the Internet. The role of one. Basis for the Internet. The role of private LANs.private LANs.

Suitable for most but not all applicationsSuitable for most but not all applications

Benefit from the wide availability of tools Benefit from the wide availability of tools and expertiseand expertise

TCP vs. UDP TCP vs. UDP –– if TCP guarantees delivery, if TCP guarantees delivery, and UDP is and UDP is ““unreliableunreliable””, why is UDP still , why is UDP still around ? Critical application design around ? Critical application design decisionsdecisions

104

Delivery GuaranteesDelivery GuaranteesDelivery Guarantees

TCP provides ordered reliable deliverybi-directional connection-orientated protocoldata is segmented and acknowledgedflow control via a “window”sequence numbering on contenttimeouts and re-transmitslarger memory footprint

UDP is accepted best-effortlow overhead, connection-LESS protocoltransaction orientated (transmitter to receiver)application must address reliability (no ACK)packet delivery is not guaranteeduse for periodic data transmissionssmaller memory footprint

TCP provides ordered reliable deliveryTCP provides ordered reliable deliverybibi--directional connectiondirectional connection--orientated protocolorientated protocoldata is segmented and acknowledgeddata is segmented and acknowledgedflow control via a flow control via a ““windowwindow””sequence numbering on contentsequence numbering on contenttimeouts and retimeouts and re--transmitstransmitslarger memory footprintlarger memory footprint

UDP is accepted bestUDP is accepted best--efforteffortlow overhead, connectionlow overhead, connection--LESS protocolLESS protocoltransaction orientated (transmitter to receiver)transaction orientated (transmitter to receiver)application must address reliability (no ACK)application must address reliability (no ACK)packet delivery is not guaranteedpacket delivery is not guaranteeduse for periodic data transmissionsuse for periodic data transmissionssmaller memory footprintsmaller memory footprint

105

TCP versus UDPTCP versus UDPTCP versus UDP

TCP Takes elaborate measures to ensure reliable delivery, mandating use of specific timers and thus effectively defining the behavior of the data transfer.

Especially appropriate for transfer of file-like data (firmware, etc.) which must arrive intact but not necessarily time-critical.

Larger memory footprint.

TCP TCP Takes elaborate measures Takes elaborate measures to ensure reliable delivery, to ensure reliable delivery, mandating use of specific mandating use of specific timers and thus effectively timers and thus effectively defining the behavior of defining the behavior of the data transfer.the data transfer.

Especially appropriate for Especially appropriate for transfer of filetransfer of file--like data like data (firmware, etc.) which (firmware, etc.) which must arrive intact but not must arrive intact but not necessarily timenecessarily time--critical.critical.

Larger memory footprintLarger memory footprint..

UDP Thin layer on top of IP protocol. Does not guarantee delivery. Many “real- time” protocols built on top of UDP to obtain the precise timing and reliability requirements for a particular application (RTSP for example).

Much smaller memory footprint.

UDP UDP Thin layer on top of IP Thin layer on top of IP protocol. Does not protocol. Does not guarantee delivery. Many guarantee delivery. Many ““realreal-- timetime”” protocols protocols built on top of UDP to built on top of UDP to obtain the precise timing obtain the precise timing and reliability and reliability requirements for a requirements for a particular application particular application (RTSP for example).(RTSP for example).

Much smaller memory Much smaller memory footprint.footprint.

2006 Corporate Seminar : TCP/IP

Microchip TCP/IP Stack &File System Overview

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 107

Introduction to Microchip’s TCP/IP Stack

Page 108

Microchip FREE TCP/IP Stack Microchip FREE TCP/IP Stack

Stack is license FREEApplication Notes:

AN833AN870

Runs on most PIC18 microsRequires approx 25K Code space

Ethernet

ARP

IP

ICMP

UDP

DHCP

TCP

SNMP HTTP FTP TFTP

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 109

Microchip’s TCP/IP Stack

Microchip App Note AN833 & AN870

Source code available for FREE !

- No fee license agreement

- Must use with Microchip MCU

- Download off Microchip website

Standard Microchip technical support

Suite of files- ‘C’ Source files and PC based utility

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 110

What can I do?

Provides Remote Application Access

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 111

TCP/IP Stack Features

Portable across PIC18 microcontrollers

Out-of-box support for Microchip MPLAB® C18 and PICC 18™ (Hitech)compilers

- Additional support for PIC24 & dsPIC

RTOS independent – Cooperative Multitasking Environment

Modular Design

- Full TCP State machine

- Socket support for TCP and UDP

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 112

Stack Modules

Internet Protocol StackInternet Protocol Stack

Physical Layer

Network Access Layer

Internet Layer

Transport Layer

Application Layer

* To be added

Modem* USART Ethernet

PPP* SLIP ARP

IP

ICMP

UDP TCP

DHCP SMTP* SNMP HTTP FTP

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 113

Block Diagram

Host-To-Network

Internet

Transport

Application HTTP Stack Manager

TCP/UDP

ICMP

IP

ARPTask

ARP

MAC

SMTPCustom FTPServerClientServer

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 114

Media Access Control (MAC)

Out-of-box support for:- ENC28J60

- RealTek 8019AS

- SMSC LAN91C111

Uses many of Microchip’s demo boards including PICDEM.net™ & dsPICDEM.net™Uses NIC RAM as buffer

MCU EthernetInterface

Data

Address

Control

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 115

IP Configuration

IP Address, Subnet Mask, Gateway

Static values

- Hard-coded in source code

IP Gleaning

- Only IP address

Dynamic Host Configuration Protocol

- All IP parameters

- Fully automatic

Function calls to MAC

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 116

Transmission Control Protocol (TCP)

Connection Oriented

- Reliable data transfer

Full TCP State Machine

Unlimited TCP Sockets

- Limited by available RAM and compiler only

Function calls to:

- MAC

- IP

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 117

TCP Functions

TCPInit

TCPListen

TCPConnect

TCPIsConnected

TCPDisconnect

TCPIsPutReady

TCPPut

TCPFlush

TCPIsGetReady

TCPGet

TCPGetArray

TCPDiscard

TCPProcess

TCPTick

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 118

TCP Client Steps

TCPConnect(...)

TCPIsConnected(..)

TCPPut(...)TCPFlush(...)

TCPGet(...)TCPDiscard(...)

TCPIsGetReady(..)TCPIsPutReady(..)

TCPDisconnect(...)

TCPIsConnected(..)

ARPResolve(...)

ARPIsResolved(..)

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 119

TCP Server StepsTCPListen(...)

TCPIsConnected(..)

TCPPut(...)TCPFlush(...)

TCPGet(...)TCPDiscard(...)

TCPIsGetReady(..)TCPIsPutReady(..)

TCPDisconnect(...)

TCPIsConnected(..)

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 120

User Datagram Protocol (UDP)

Connectionless Protocol

- No built-in error recovery

Unlimited UDP Socket support

- Socket count limited by available RAM

- Multiple applications can access UDP simultaneously

No checksum calculation

Function calls to:

- MAC

- IP

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 121

UDP Functions

UDPInit

UDPOpen

UDPClose

UDPIsPutReady

UDPPut

UDPFlush

UDPIsGetReady

UDPGet

UDPDiscard

UDPProcess

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 122

UDP Steps

UDPOpen(...)

UDPPut(...)UDPFlush(...)

UDPGet(...)UDPDiscard(...)

UDPIsGetReady(..)UDPIsPutReady(..)

UDPClose(...)

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 123

Security

No built-in security

Application must provide reasonable authentication and encryption

Avoid blind remote control

Restrict critical commands

PIC® microcontroller is not same as PC

- Limit no. of users to designed limit

- No built-in solution for “Denial Of Service”

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 124

Microchip TCP/IP Stack Configure

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 125

Microchip TCP/IP Stack Configure

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 126

Microchip TCP/IP Stack File

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 127

Microchip TCP/IP Stack File

128

SLIP

DHCP HTTP

TCP/UDP

ICMP

IP

ARP

MAC

SNMPFTP

*Microchip TCP/IP Stack Compile-Time Options (Module

Selection)

**Microchip TCP/IP Stack Microchip TCP/IP Stack CompileCompile--Time Options Time Options (Module (Module

Selection)Selection)

Custom Stack Manager

ARPTask

STACK_USE_DHCPSNMP

FTP_SERVERHTTP_SERVER

ICMPIP_GLEANING

TCP / UDPMAX_SOCKETSMAX_UDP_SOCKETS

IP_GLEANING

SLIP

StackTsk.h

129

SLIP

DHCP

IP

MAC

SNMPFTP

*Microchip TCP/IP Stack Compile-Time Options

**Microchip TCP/IP Stack Microchip TCP/IP Stack CompileCompile--Time OptionsTime Options

Custom Stack ManagerMAX_HTTP_CONNECTIONS

MAX_ICMP_DATA_LENTCP_NO_WAIT_FOR_ACKSTACK_CLIENT_MODE

STACK_CLIENT_MODE

MAC_TX_BUFFER_SIZEMAC_TX_BUFFER_COUNT

StackTsk.h

HTTP

TCP/UDP

ICMP

ARP

ARPTask

130

ServerClient

*Microchip TCP/IP Stack Compile-Time Options

**Microchip TCP/IP Stack Microchip TCP/IP Stack CompileCompile--Time OptionsTime Options

ACKACK

TCP

TCP_NO_WAIT_FOR_ACK

Allows back-to-back TCP packet transfers (within a TCP window) while waiting for ACK

Throughput increased

Don’t care: HTTP

browser always

retries

TCP_NO_WAIT_FOR_ACKTCP_NO_WAIT_FOR_ACK

Allows backAllows back--toto--back TCP packet back TCP packet transfers (within a TCP window) while transfers (within a TCP window) while waiting for ACKwaiting for ACK

Throughput increasedThroughput increased

DonDon’’t care: HTTPt care: HTTP

browser always browser always

retriesretries

131

Server and/or client?

Two modes of operationsServer

Server and Client

STACK_CLIENT_MODE enables Client mode

Client mode providesTCPConnectARPResolveARPIsResolved

SMTP module enables Client mode

Server and/or client?Server and/or client?

Two modes of operationsTwo modes of operations

ServerServer

Server and ClientServer and Client

STACK_CLIENT_MODESTACK_CLIENT_MODE enables Client modeenables Client mode

Client mode providesClient mode providesTCPConnectTCPConnectARPResolveARPResolveARPIsResolvedARPIsResolved

SMTPSMTP module enables Client modemodule enables Client mode

*Microchip TCP/IP Stack Compile-Time Options

**Microchip TCP/IP Stack Microchip TCP/IP Stack CompileCompile--Time OptionsTime Options

132

*Microchip TCP/IP Stack Software Structure

**Microchip TCP/IP Stack Microchip TCP/IP Stack Software StructureSoftware Structure

Initialization

Tasks

ISRs

Subroutines

void main(void) {// Initialization

while(1){ // Main infinite loop// Cooperative Multitasks// RTOS Independent

} }

// Int service routines

// Subroutines

void main(void) {void main(void) {

// Initialization// Initialization

while(1){while(1){ // Main infinite loop// Main infinite loop

// Cooperative Multitasks// Cooperative Multitasks

// RTOS Independent// RTOS Independent

} }

}}

// Int service routines// Int service routines

// Subroutines// Subroutines

133

// InitializationMyInit(); // Your app initStackInit(); // RequiredTickInit();HTTPInit(); // Application

dependentMPFSInit();FTPInit();DHCPInit();SNMPInit();

// Initialization// InitializationMyInit();MyInit(); // Your app init// Your app initStackInit();StackInit(); // Required// RequiredTickInit();TickInit();HTTPInit();HTTPInit(); // Application // Application

dependentdependentMPFSInit();MPFSInit();FTPInit();FTPInit();DHCPInit();DHCPInit();SNMPInit();SNMPInit();

*Microchip TCP/IP Stack Software Structure -

Initialization

**Microchip TCP/IP Stack Microchip TCP/IP Stack Software Structure Software Structure --

InitializationInitialization

134

while(1){ // Main infinite loopMyTask(); // Your app task(s)StackTask(); // Required

HTTPServer(); // Application dependent

FTPServer();DHCPServer();SNMPServer();

}

while(1){while(1){ // Main infinite loop// Main infinite loopMyTask();MyTask(); // Your app task(s)// Your app task(s)StackTask();StackTask(); // Required// Required

HTTPServer();HTTPServer(); // Application // Application dependentdependent

FTPServer();FTPServer();DHCPServer();DHCPServer();SNMPServer();SNMPServer();

} }

*Microchip TCP/IP Stack Software Structure - Main Loop

**Microchip TCP/IP Stack Microchip TCP/IP Stack Software Structure Software Structure -- Main LoopMain Loop

135

// SubroutinesTickUpdate(); // Required

HTTPExecCmd(); // Callbacks app dependentHTTPGetVar();

// Subroutines// SubroutinesTickUpdate();TickUpdate(); // Required// Required

HTTPExecCmd();HTTPExecCmd(); // Callbacks app // Callbacks app dependentdependentHTTPGetVar();HTTPGetVar();

*Microchip TCP/IP Stack Software Structure - Subroutines

**Microchip TCP/IP Stack Microchip TCP/IP Stack Software Structure Software Structure -- SubroutinesSubroutines

136

ServerClient

HTTPGetVarCallback function to get dynamic variable value

Used when client requesting info from server

HTTPGetVarHTTPGetVarCallback functionCallback function to get dynamic variable valueto get dynamic variable value

Used when client requesting info from serverUsed when client requesting info from server

*Stack Layers Application - HTTP Server API

**Stack Layers Stack Layers Application Application -- HTTP Server APIHTTP Server API

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 137

Microchip TCP/IP Stack Usage

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 138

Microchip File System

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 139

Microchip File System(MPFS)

Small yet powerful file system

Flexible storage scheme

- Internal program memory or external data EEPROM (up to 64KB)

PC based utility to generate MPFS image

8 + 3 Short file names

Case-insensitive file names

Read AN833 for more detail

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 140

Microchip File System(MPFS)

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 141

MPFS Image

Two types- ‘C’ data file for Program Memory

- ‘bin’ file for external data EEPROM

PC utility “mpfs.exe”All web pages in one directory

Image size must fit in available memory

“CR LF” stripped from “*.htm” files

Reserved block for application specific data

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 142

MPFS Utility

mpfs [/?] [/c] [/b] [/r<Block>] <InputDir> <OutputFile>- /? : Display help

- /c : Generate ‘C’ data file

- /b : Generate binary data file (Default)

- /r : Reserve a block of memory at beginning (Used in /b mode only. Default=32)

- <InputDir>: Directory that contains files

- <OutputFile>: Output file name

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 143

MPFS Examples

Generate ‘C’ data file- mpfs /c MyPagesDir mypages.c

- Link this file into your project

Generate binary data file, with 32 bytes reserved block- mpfs MyPagesDir mypages.bin

Reserve 128 bytes in EEPROM- mpfs /r128 MyPagesDir mypages.bin

- Useful to store custom data outside MPFS

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 144

Lab #2

Goal: Learn how to modify MPFS image

Exercise:

- Modify name in c:₩Ethernet₩LAB₩webpages₩main.htm

- Build MPFS image

- mpfs c:₩Ethernet₩LAB₩webpageswebpage.bin

- Download new webpages using HyperTerminal

- Open Internet Explorer and type in Board IP Address

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 145

LAB2 : Downloading Web Pages with Hyperterminal

Open HyperTerminal

File -> Properties

Connect using:- Select COM port

Select Configure

Use same options ->

Click OK

Click OK

Connect ->

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 146

LAB2 : Downloading Web Pages with Hyperterminal

Press & Hold S1, Press & Release MCLR, Release S1

Select 7

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 147

LAB2 : Downloading Web Pages with HyperterminalSelect Transfer -> Send File

Pulldown menu & select XmodemBrowse & select this file Click Send

C:\Ethernet\LAB\webpages.bin

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 148

LAB2 : Downloading Web Pages with Hyperterminal

Select 8 to Finish

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 149

HTTP Servers

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 150

HTTP Server

Multiple simultaneous connections

Supports HTML Forms

Dynamic web page creation

Pages stored in Program Memory or external serial EEPROM

Simple and powerful Microchip File System (MPFS)

Easy to integrate

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 151

HTTP Server API

HTTPInitHTTPServer- Performs HTTP Server tasks - Call

periodically

HTTPGetVar- Callback to get dynamic variable value

HTTPExecCmd- Callback to execute HTML form command

152

Web contentWeb contentWeb content

Static HTML pages and graphics

Interactive pagesClickable graphics

Forms

Dynamic pagesCommon Gateway Interface

Embedded Gateway Interface

Server-side inclusion

Variable substitution

Static HTML pages and graphics

Interactive pagesClickable graphics

Forms

Dynamic pagesCommon Gateway Interface

Embedded Gateway Interface

Server-side inclusion

Variable substitution

153

Static HTML pagesStatic HTML pagesStatic HTML pages

Stored in EEROM filesystem

Copied from ROM to network

ROM containsFile directory

Location

Length

Attributes

Pre-calculated TCP checksum

File

HTTP header

Data

Stored in EEROM filesystem

Copied from ROM to network

ROM containsFile directory

Location

Length

Attributes

Pre-calculated TCP checksum

File

HTTP header

Data

154

Interactive HML pagesInteractive HML pagesInteractive HML pages

Clickable graphicsClickable graphics

<table><tr valign=middle>

<td><a href="switch2.htm"><img src="switchu.gif"></a></td>

<td><img src="ledoff.gif"></td>

</tr></table>

155

Interactive HTML pagesInteractive HTML pagesInteractive HTML pages

HTML formsHTML forms

GET /thank.htm?name=Joe+Bloggs&addr=joe@home&

state=happy&send=Submit HTTP/1.0

156

Display variable substitutionDisplay variable substitutionDisplay variable substitution

@3 &deg;C

becomes

23.5&deg;C

@2:@1:@0

becomes

20:44:19

157

Form variable substitutionForm variable substitutionForm variable substitution

<form action='setime.egi'>

<input type=text name=hrs size=2 value='@2'> :

<input type=text name=min size=2 value='@1'> :

<input type=text name=sec size=2 value='@0'>

<br><br>

<input type=submit name=sub value='Set clock'>

</form><br>

158

Button value substitutionButton value substitutionButton value substitution

<form action='digout.egi'>

<table border=2><tr>

<td><input type=submit name=out7 value=#></td>

<td><input type=submit name=out6 value=#></td>

<td><input type=submit name=out5 value=#></td>

</tr></table></form>

159

ChipWeb home pageChipWeb home pageChipWeb home page

Monitor digital I/Ps

Control digital O/Ps

Display analog values

Use conventional Web browser

Monitor digital I/Ps

Control digital O/Ps

Display analog values

Use conventional Web browser

160

Navigation frameNavigation frameNavigation frame

Standard HTML techniques

Change page in the center frame<A href="main1.htm" target=middle>

Home</A>

Animate switches and LEDs<td><a href="digout11.htm"> <img s

rc="sw0.gif"></a></td><td><a href="digout00.htm"> <img s

rc="sw1.gif"></a></td>

Standard HTML techniques

Change page in the center frame<A href="main1.htm" target=middle>

Home</A>

Animate switches and LEDs<td><a href="digout11.htm"> <img s

rc="sw0.gif"></a></td><td><a href="digout00.htm"> <img s

rc="sw1.gif"></a></td>

161

Dynamic status frameDynamic status frameDynamic status frame

Update page using ‘client pull’<meta http-equiv="refresh" content="5">

Dynamic data using @ variables<tr><th>O/P states</th></tr><tr><td>@5</td><td>@6</td></tr>

Dynamic graphics using stacked GIFs

Update page using ‘client pull’<meta http-equiv="refresh" content="5">

Dynamic data using @ variables<tr><th>O/P states</th></tr><tr><td>@5</td><td>@6</td></tr>

Dynamic graphics using stacked GIFs

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 162

Dynamic HTML Pages

Must have “cgi” file extension

Variable substitution method

Format: %xx - xx is a variable (0-99)

Substitution may be one or more characters

- May be used to upload complete binary image

Use extra ‘%’ to display % itself

- 23%% displays 23%

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 163

Variable Substitution Example

1. <table>2. <tr><td><b><Results></b></td></tr>3. <tr><td><Pot1:></td><td>%02</td></tr>4. <tr><td><Pot2:></td><td>%03</td></tr>5. <tr><td><Switch:></td><td>%04</td></tr>... %02

%03

%04

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 164

Dynamic HTML Pages - Uses

Change web page content- ...Serial Number=%01…

Change graphics based on a variable

- img src=LED%02.gif

Change page link

- <a href=%02.htm>LinkName</a>

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 165

HTTPGetVar

(BYTE var, WORD ref, BYTE *val)

Data transferred byte at a time

ref is used for multi-byte transfers

- First transfer with ref = HTTP_START_OF_VAR

- return other than HTTP_END_OF_VAR to indicate multi-byte transfer

- Finish data transfer by returning HTTP_END_OF_VAR

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 166

HTTPGetVar Example

(BYTE var, WORD ref, BYTE *val)1. if (var == 4) // Identify variable.2. { // Return ‘1’ if switch is open, else ‘0’3. if ( RB5 ) *val = ‘1’;4. else *val = ‘0’;5. return HTTP_END_OF_VAR;6. }7. else8. // Check for other variable......

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 167

Multi-byte transfer

(BYTE var, WORD ref, BYTE *val)1. if (var == 1) // Identify var.2. { // If this first call, init array index.3. if ( ref == HTTP_START_OF_VAR ) ref = 0;4. // Stuff current byte in buffer.5. *val = SerialNumberStr[(BYTE)ref];6. if ( *val ==‘\0’ ) return HTTP_END_OF_VAR;7. return ++ref; // Advance array index8. }9. else // Check for other variable......

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 168

Lab #3

Goal: Use command execution via browser and how to dynamically change web pages

Exercise:

- Modify c:₩Ethernet₩LAB₩MainDemo.c

- Implement HTTPExecCmd() callback to toggle LEDs D5, D6 when “Toggle LED1” and “Toggle LED2” buttons are pressed

- Change status.cgi to display graphical LED state – led0.gif for OFF and led1.gif for ON

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 169

HTML Forms

Interactive HTML pages

- Data is transferred from PC to PIC18 microcontroller

Form method ‘GET’ only

Remote command invocation

- User application must implement the command

Caution: Multiple users may execute same command “simultaneously”- Must protect critical data

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 170

Form Example

1. <FORM METHOD=GETaction=command.cgi>

2. <table> 3. <tr><td>Power Level:</td>4. <td><input type=text size=2

maxlength=1 name=P value=%07></td></tr> ...5. <tr><td><input type=submit name=Bvalue=Apply></td></tr> ...

Action by browser when Apply is clicked

10.10.5.110/command.cgi?P=5&L=1&H=255&B=Apply

P, %07

B

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 171

HTTPExecCmd

(BYTE **argv, BYTE argc)argv[0] = Form Action Name

argv[1…argc] = Parameter 1 to argcargc = Number of parameters including Form Action Name

command.cgi?P=5&L=1&H=255&B=Apply- argv[0] = “command.cgi”, argv[1] = “P”,

argv[2]= “5” etc… ; argc = 9

- argv[0] determines page to be uploaded next

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 172

HTTPExecCmd Example

(BYTE **argv, BYTE argc)1. for ( i = 1; i < argc; i++ ) {2. if ( argv[i][0] == ‘P’ ) // Power setpoint ?3. PowerVal = atoi(argv[++i]); // Save value4. else if ( argv[i][0] == ‘L’ ) // Low setting ?5. LowPowerSetting = atoi(argv[++i]); // Save6. else if ( argv[i][0] == ‘H’ ) // High setting ?7. HighPowerSetting = atoi(argv[++i]); // Save}}// If required, another page may sent as a resultstrcpy(argv[0], “RESULTS.CGI”); // Set result page

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 173

Form Fields Limit

Allowable max. number of arguments- FormAction?Arg1=Val1+Arg2=Val2…- See MAX_HTTP_ARGS & MAX_HTML_CMD_LEN

in “http.c”

Default - MAX_HTTP_ARGS = 5 (Includes action)

- MAX_HTML_CMD_LEN = 80

If limit is exceeded,

- Extra arguments are ignored

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 174

Lab #4

Goal: Learn about PC to PIC data transfer using forms

Exercise:- Implement code in HTTPExecCmd() to

accept “User Name” from Output Control and save it to PIC microcontroller RAM

- Implement code in HTTPGetVar() to display saved “User Name” in System Status page.

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 175

Custom Application

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 176

Lab #5

Create the Sensor

- Receives UDP packets that change PORTD<5>

- Receives request for status (PORTD<5> and AN0)

- Serves web page on local status

Presenter’s board

- Collects information from each sensor

- Serves web page displaying all sensors info

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 177

Lab #5

Add source code to MainDemo.c, see flow chart on next page

Compile project

Download into board

Run & wait for instructor

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 178

UDP Process

UDPPut(LATD5?’1’:’0’)

UDPGet(&UDPChar)UDPDiscard()

UDPIsGetReady(..)

UDPIsPutReady()

UDPFlush(...)

UDPChar == 0x55

UDPPut(AN0String[x])

UDPChar == 0xAA

LATD5 ^= 1;

YES

NO

YES

NO

YESEXIT

YES

EXIT

NO

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 179

Summary

Overview of Ethernet and Ethernet controllers

Intro to the Microchip TCP/IP Stack

Using the Microchip File System

Using HTTP Servers to monitor, control and download information

Designing Custom Applications

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 180

References

AN833 – The Microchip TCP/IP Stack

AN870 – An SNMP Agent for the Microchip TCP/IP Stack

DM163004 PICDEM.net Internet/Ethernet Demonstration Board

DM300004-1/2 dsPICDEM.net 1/2 Connectivity Demonstration Board

ENC28J60 Ethernet PICTail

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 181

MAC Functions

MACInit

MACIsTxReady

MACGetHeader

MACGet

MACGetArray

MACDiscardRx

MACPutHeader

MACPut

MACPutArray

MACFlush

MACDiscardTx

MACSetRxBuffer

MACSetTxBuffer

MACReserveTxBuffer

MACGetFreeRxSize

MACGetRxBuffer

MACGetTxBuffer

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 182

IP Functions

IPIsTxReady

IPSetTxBuffer

IPPutHeader

IPPutArray

IPGetHeader

IPGetArray

IPSetRxBuffer

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 183

Dynamic Host Configuration Protocol (DHCP)

Fully automatic method

- Node gets configured on power-up

- Automatic IP renewal

Needs at least one DHCP Server on network

Configures

- IP, Gateway Address, Subnet Mask

Solves Embedded Systems Problem

- Discovery of IP Address

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 184

Simple Network Management Protocol (SNMP)

Manage network devices: server, printer etc.

Machine-to-machine protocol

Supports SNMPv1 over UDP

Protocol of choice for small embedded systems

Network

Manager

Devices

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 185

Web Page Types

Page file extension defines how browser displays/interprets the page- Default support for “txt”, “htm”, “gif”, “cgi”,

“jpg”, “cla”, “wav”.- If needed, modify “httpFiles” and

“httpContents” in http.c file

“index.htm” is the default web page - Defined by HTTP_DEFAULT_FILE_STRING in

http.c file

© 2005 Microchip Technology Incorporated. All Rights Reserved. Class Slide 186

Web Page Design Guidance

Avoid using excessive files in a page

- More simultaneous connections

- More RAM usage

Hand-code the pages

- Or remove unnecessary tags generated by visual web authoring tool

Try to shrink the graphics

- Use correct file formats

Auto refresh dynamic content only

2006 Corporate Seminar : TCP/IP

감사합니다.

Q/A