MEGA16的W5100以太网模块驱动例程英文_第1页
MEGA16的W5100以太网模块驱动例程英文_第2页
MEGA16的W5100以太网模块驱动例程英文_第3页
MEGA16的W5100以太网模块驱动例程英文_第4页
MEGA16的W5100以太网模块驱动例程英文_第5页
已阅读5页,还剩35页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Therapidpenetrationoftheinternetnetworksintomanyoftoday’smodernhomesandpersonalgadgets(e.g.smartphoneandsmartpads)openingatremendoususefulandinterestingembeddedsystemapplicationthatcouldbeintegratedintoourhouseorknownastheintelligenthouse.Forexamplebyputtingasmallembeddedsystemwebserverinourhouse,wecouldeasilymonitorsuchasalarm,temperatureoreventurnon/offthelamporthegarden’swatersprinkle;eventuallyfromanyremotelocationthroughthewirelesspersonalgadget;OrperhapsyoujustwanttoimpressyourrelativeorfriendwithaveryaccuratedigitalclockwhichautomaticallysynchronizedthetimethroughtheNetworkTimeProtocol(NTP)overtheinternetatyourhomeoroffice.

AlloftheseinterestingandchallengingembeddedsystemapplicationscouldbeaccomplishedbyintegratingtheEthernetprotocolwhichisformedthebasicofthecommunicationprotocolusedintheinternetintotheembeddedsystem.Currentlythereareseveralapproachesforthissolutionbutbasicallytheycouldbedividedintotwocategorieswirede.g.WiznetW5100,W5300,MicrochipENC28J60andwirelesssuchastheMicrochipZG2100MCWi-Fimodule(recentlyisacquiredbyMicrochipfromtheZero-GWirelessonJan11,).

OnthistutorialwearegoingtobuildtheembeddedwebserverusingtheWiznetWIZ811MJnetworkmodulewhichisbasedontheWiznetwellknownW5100TCP/IPhardwiredchipthatincludetheethernetcontrollerphysicallayer(PHY).TheWIZ811MJnetworkmodulecomeswiththeWiznetW5100chip,MAG-JACK(RJ45)togetherwiththegluedlogicneededtocommunicatewiththemicrocontrollerthroughtheSPIorbusinterface.

ThereasonIchoosetheWiznet5100basedchiponthistutorialbecausethischiphastheTCP/IPhardwiredonit;thereforeitwillmakedevelopingtheTCP/IPprotocolstackbasedapplicationmucheasierandcouldbeimplementedonthesmallRAMsizemicrocontrollerclasscomparedtothefirmwareTCP/IPprotocolsstackbasedimplementation

approach(youdon’thavetoknoweverythingabouttheTCP/IPprotocolstackinordertobeabletousethischip).TheotherreasonisbecausetheWiznet5100chiphasbeenaroundforafewyearsinthemarketandhasalreadybeingmatured.ThischipisusedinmanycommercialapplicationssuchastheArduinoframeworkontheirstandardArduinoEthernetshieldasshownonthisfollowingpicture.

Ok,nowletslistdownthenecessaryelectronicscomponentsandsupportedsoftwareforthistutorialandmakesureyouhavetheAVRATMega328microcontrollerdatasheetnearyou:

Resistors:10KOhm(1),1KOhm(1)and470Ohm(2)

Capacitors:10uF/16v(2)and0.1uF(2)

LEDS:3mmBlueLED(2)

Transistor:2N3904(1)

VoltageRegulatorIC:LM1086-3.3Volt

Onemomentarypushbutton

One30×60mmPrototypeboard

Two10pinsmaledoubleheaderand5pinsmalesingleheader

One2pinsmalesinglepolarizedheader

AVRJazzMega328boardandJazzMate5Voltvoltageregulatorboardfromermicro

WiznetWIZ811MJNetworkModule

AtmelAVRStudioversion4.17IDE

WinAVRAVR-GCC4.3.2;avr-libc1.6.6(WinAVR0313)

ReferenceDocument:W5100Datasheet,WIZ811MJDatasheet,W5100PortingGuide,AtmelAVRATMega328Datasheet.

TheWiznetW5100HardwiredTCP/IPProtocolChip

BasicallytheWiznetW5100implementsafull-featuredofstandardIEEE802.3(Ethernetphysicalanddatalinklayer)andpowerfulTCP/IPstackinsidethechip;thismaketheWiznetW5100chipissuitablechoiceforintegratingtheembeddedsystemintotheinternet.ProgrammingtheWiznetW5100chipisalsoeasieraswejustneedtowriteandreadtoandfromtheW5100internalregistersinordertousethebuild-inTCP/IPprotocolfeatures.

TheWiznetW5100chipcomewiththreemethodofcontrollingitsinternalregisters;thisfirsttwoistousetheparalleldirectorindirectbus,thelastoneistouseawellknownembeddedserialdatatransferknownastheSPI(serialperipheralinterface),onthistutorialwearegoingtousetheSPItocontroltheWiznetW5100chip.YoucouldreadmoreaboutSPIonmypreviouspostedblogUsingSerialPeripheralInterface(SPI)MasterandSlavewithAtmelAVRMicrocontroller.ThebasicSPIconnectionbetweentheWiznetWIZ811MJnetworkmoduleandAtmelAVRATMega328microcontrollerisshownonthisfollowingpicture.

TheWiznetW5100willactastheSPIslavedevicecontrolledbyAtmelAVRATMega328microcontrollerastheSPIMaster.TheSPIprotocolneedatleastfoursignali.e.MOSI(MasterOutSerialIn),MISO(MasterInSerialOut),SCK(signalclockprovidedbythemaster)andCS(theSPIslavechipselect).AlthoughtheAVRATMega328microcontrollersupportalltheSPImodes(i.e.0,1,2and3)buttheWiznetW5100chipsupportthemostSPIcommonmodes(mode0andmode3)whereitwillsampleadataonrisingedgeclockandoutputtingonthefallingedgeclock.TheW5100chipalsoprovidestheinterruptpin,butonthistutorialwedon’tusetheinterruptfeature,insteadweuseapoolingmethodtocontroltheW5100operation.

InordertounderstandofhowwecontroltheWiznetW5100astheSPIslavedevice,wearegoingtocreatetheW5100initializationprogram;soitwillresponsetothesimple“ping”networkcommand(ICMPprotocol).ThefollowingisthecompleteCcodecalled“wiznetping.c”forinitializingtheWiznetW5100chip.

/*****************************************************************************

// FileName :wiznetping.c

// Version :1.0

// Description :WiznetW5100

// Author :RWB

// Target :AVRJazzMega168Board

// Compiler :AVR-GCC4.3.2;avr-libc1.6.6(WinAVR0313)

// IDE :AtmelAVRStudio4.17

// Programmer :AVRJazzMega168STK500v2.0Bootloader

// :AVRVisualStudio4.17,STK500programmer

// LastUpdated:01July

*****************************************************************************/#include<avr/io.h>

#include<string.h>#include<stdio.h>#include<util/delay.h>

#defineBAUD_RATE19200

//AVRJazzMega168/328SPII/O#defineSPI_PORTPORTB

#defineSPI_DDR DDRB

#defineSPI_CS PORTB2

//WiznetW5100OpCode

#defineWIZNET_WRITE_OPCODE0xF0#defineWIZNET_READ_OPCODE0x0F

//WiznetW5100RegisterAddresses#defineMR 0x0000 //ModeRegister

#defineGAR 0x0001 //GatewayAddress:0x0001to0x0004#defineSUBR0x0005 //SubnetmaskAddress:0x0005to0x0008

#defineSAR 0x0009 //SourceHardwareAddress(MAC):0x0009to0x000E#defineSIPR0x000F //SourceIPAddress:0x000Fto0x0012

#defineRMSR0x001A//RXMemorySizeRegister#defineTMSR0x001B//TXMemorySizeRegistervoiduart_init(void)

{

UBRR0H=(((F_CPU/BAUD_RATE)/16)-1)>>8; //setbaudrateUBRR0L=(((F_CPU/BAUD_RATE)/16)-1);

UCSR0B=(1<<RXEN0)|(1<<TXEN0); //enableRx&TxUCSR0C= (1<<UCSZ01)|(1<<UCSZ00); //configUSART;8N1

}

voiduart_flush(void)

{

unsignedchardummy;

while(UCSR0A&(1<<RXC0))dummy=UDR0;

}

intuart_putch(charch,FILE*stream)

{

if(ch=='\n')uart_putch('\r',stream);

while(!(UCSR0A&(1<<UDRE0)));UDR0=ch;

return0;

}

intuart_getch(FILE*stream)

{

unsignedcharch;

while(!(UCSR0A&(1<<RXC0)));ch=UDR0;

/*EchotheOutputBacktoterminal*/uart_putch(ch,stream);

returnch;

}

voidansi_cl(void)

{

//ANSIclearscreen:cl=\E[H\E[Jputchar(27);

putchar('[');

putchar('H');putchar(27);putchar('[');

putchar('J');

}

voidansi_me(void)

{

//ANSIturnoffallattribute:me=\E[0mputchar(27);

putchar('[');

putchar('0');

putchar('m');

}

voidSPI_Write(unsignedintaddr,unsignedchardata)

{

//ActivatetheCSpinSPI_PORT&=~(1<<SPI_CS);

//StartWiznetW5100WriteOpCodetransmissionSPDR=WIZNET_WRITE_OPCODE;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//StartWiznetW5100AddressHighBytestransmissionSPDR=(addr&0xFF00)>>8;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//StartWiznetW5100AddressLowBytestransmissionSPDR=addr&0x00FF;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//StartDatatransmissionSPDR=data;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//CSpinisnotactiveSPI_PORT|=(1<<SPI_CS);

}

unsignedcharSPI_Read(unsignedintaddr)

{

//ActivatetheCSpinSPI_PORT&=~(1<<SPI_CS);

//StartWiznetW5100ReadOpCodetransmissionSPDR=WIZNET_READ_OPCODE;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//StartWiznetW5100AddressHighBytestransmissionSPDR=(addr&0xFF00)>>8;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//StartWiznetW5100AddressLowBytestransmissionSPDR=addr&0x00FF;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//SendDummytransmissionforreadingthedataSPDR=0x00;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//CSpinisnotactiveSPI_PORT|=(1<<SPI_CS);

return(SPDR);

}

voidW5100_Init(void)

{

//EthernetSetup

unsignedcharmac_addr[]={0x00,0x16,0x36,0xDE,0x58,0xF6};unsignedcharip_addr[]={192,168,2,10};

unsignedcharsub_mask[]={255,255,255,0};unsignedchargtw_addr[]={192,168,2,1};

//SettingtheWiznetW5100ModeRegister:0x0000SPI_Write(MR,0x80); //MR=0b10000000;

_delay_ms(1);

printf("ReadingMR:%d\n\n",SPI_Read(MR));

//SettingtheWiznetW5100GatewayAddress(GAR):0x0001to0x0004printf("SettingGatewayAddress%d.%d.%d.%d\n",gtw_addr[0],gtw_addr[1],\

gtw_addr[2],gtw_addr[3]);SPI_Write(GAR+0,gtw_addr[0]);SPI_Write(GAR+1,gtw_addr[1]);SPI_Write(GAR+2,gtw_addr[2]);SPI_Write(GAR+3,gtw_addr[3]);

_delay_ms(1);

printf("ReadingGAR:%d.%d.%d.%d\n\n",SPI_Read(GAR+0),SPI_Read(GAR+1),\SPI_Read(GAR+2),SPI_Read(GAR+3));

//SettingtheWiznetW5100SourceAddressRegister(SAR):0x0009to0x000Eprintf("SettingSourceAddress%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",mac_addr[0],mac_addr[1],\

mac_addr[2],mac_addr[3],mac_addr[4],mac_addr[5]);SPI_Write(SAR+0,mac_addr[0]);

SPI_Write(SAR+1,mac_addr[1]);SPI_Write(SAR+2,mac_addr[2]);SPI_Write(SAR+3,mac_addr[3]);SPI_Write(SAR+4,mac_addr[4]);SPI_Write(SAR+5,mac_addr[5]);

_delay_ms(1);

printf("ReadingSAR:%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n\n",SPI_Read(SAR+0),SPI_Read(SAR+1),\

SPI_Read(SAR+2),SPI_Read(SAR+3),SPI_Read(SAR+4),SPI_Read(SAR+5));

//SettingtheWiznetW5100SubMaskAddress(SUBR):0x0005to0x0008printf("SettingSubMaskAddress%d.%d.%d.%d\n",sub_mask[0],sub_mask[1],\

sub_mask[2],sub_mask[3]);SPI_Write(SUBR+0,sub_mask[0]);SPI_Write(SUBR+1,sub_mask[1]);SPI_Write(SUBR+2,sub_mask[2]);SPI_Write(SUBR+3,sub_mask[3]);

_delay_ms(1);

printf("ReadingSUBR:%d.%d.%d.%d\n\n",SPI_Read(SUBR+0),SPI_Read(SUBR+1),\SPI_Read(SUBR+2),SPI_Read(SUBR+3));

//SettingtheWiznetW5100IPAddress(SIPR):0x000Fto0x0012printf("SettingIPAddress%d.%d.%d.%d\n",ip_addr[0],ip_addr[1],\

ip_addr[2],ip_addr[3]);SPI_Write(SIPR+0,ip_addr[0]);SPI_Write(SIPR+1,ip_addr[1]);

SPI_Write(SIPR+2,ip_addr[2]);SPI_Write(SIPR+3,ip_addr[3]);

_delay_ms(1);

printf("ReadingSIPR:%d.%d.%d.%d\n\n",SPI_Read(SIPR+0),SPI_Read(SIPR+1),\SPI_Read(SIPR+2),SPI_Read(SIPR+3));

//SettingtheWiznetW5100RXandTXMemorySize,weuse2KBforRx/Tx4channelsprintf("SettingWiznetRMSRandTMSR\n\n");

SPI_Write(RMSR,0x55);

SPI_Write(TMSR,0x55);

printf("DoneWiznetW5100Initialized!\n");

}

//AssignI/OstreamtoUART

FILEuart_str=FDEV_SETUP_STREAM(uart_putch,uart_getch,_FDEV_SETUP_RW);intmain(void){

//SetthePORTDasOutput:

DDRD=0xFF;

PORTD=0x00;

//DefineOutput/InputStreamstdout=stdin=&uart_str;

//InitialUARTPeripheraluart_init();

//ClearScreenansi_me();ansi_cl();ansi_me();ansi_cl();uart_flush();

//InitialtheAVRATMega168/328SPIPeripheral

//SetMOSI(PORTB3),SCK(PORTB5)andPORTB2(SS)asoutput,othersasinputSPI_DDR=(1<<PORTB3)|(1<<PORTB5)|(1<<PORTB2);

//CSpinisnotactiveSPI_PORT|=(1<<SPI_CS);

//EnableSPI,MasterMode0,settheclockratefck/2SPCR=(1<<SPE)|(1<<MSTR);

SPSR|=(1<<SPI2X);

//InitialtheWiznetW5100printf("WiznetW5100Init\n\n");W5100_Init();

//Loopforever

for(;;){

}

return0;

}

/*EOF:wiznetping.c*/

AftercompilinganddownloadingtheHEXprogramintotheAVRJazzMega328board;connecttheRJ45connectorUTPethernetcabletoyourhubs/switchoryoucouldconnectdirectlywiththecrossconfigurationcabletoyourcomputer.UsetheserialterminalsuchasHyperterminal,puTTYorTeraTermandconfigureittoaccepttheserialconnectionwith19200baudrate,8-bitdatawithNoParityCheck.

NowyouarereadytotestyourfirstembeddedEthernetbyusingthe“ping”commandasshownonthesefollowingpictures:

WiznetW5100SPIInitialization

ToinitializetheW5100chip,weneedtowriteoneachoftheW5100commonregistersnamedMR(ModeRegister),SUBR(SubnetmaskRegister),SAR(SourceHardwareRegister),SIPR(SourceIPRegister),RMSR(ReceiveMemorySizeRegister)andTMSR(TransmitMemorySizeRegister).

AlltheWiznetW5100registersaddresshas16-bitswideandtheregisteritselfis8-bitswide;becauseweuse8-bitAVRATMega328microcontrollerSPI,thereforeinordertoperformwriteorreadoperationweneedtopassthefirst8-bitMSB(mostsignificantbyte)andfollowbythe8-bitLSB(leastsignificantbyte)oftheW5100registeraddress.TheWiznetW5100alsousetwooperantcommandstodifferentiatebetweentheWRITE(0xF0)andREAD(0×0F)

operation.TheWiznetW5100SPIwriteandreadroutineisimplementedintheSPI_Write()andSPI_Read()

functionsontheaboveCcode.

TheSARregistersisalsoknownastheMAC(MediaAccessControl)address,thisW5100registerwillrepresenttheuniquehardwareidentificationinthenetwork.TheMACaddressisassignedandmanagedbyInstituteofElectricalandElectronicsEngineers(IEEE)foreachNIC(NetworkInterfaceCard)manufacturerwherethefirst3bytesof6bytesMACaddressisusedtoidentifytheorganizationthatissuedtheidentifierandareknownastheOUI(OrganizationallyUniqueIdentifier).ForexamplethefollowingarethelistofAtmel,MicrochipandWiznetOUI:

00-04-25

(hex)

AtmelCorporation

000425

(base

16)

AtmelCorporation

Multimedia&CommunicationsGroup

2200GatewayCentre,Suite201

MorrisvilleNC27560

UNITEDSTATES

00-04-A3

(hex)

MicrochipTechnology,Inc.

0004A3

(base

16)

MicrochipTechnology,Inc.

2355W.ChandlerBlvd.

ChandlerAZ85224

UNITEDSTATES

00-08-DC

(hex)

Wiznet

0008DC

(base

16)

Wiznet

5FSimmtechbldg.,228-3,

Nonyhun,Kangnam

Seoul 135-830

KOREA,REPUBLICOF

NowthequestionishowyoucouldgetyourownMACaddressbecausetheWiznetW5100chipisshippedwithoutitsownMACaddress;theanswerisyoucouldeitherregisteryourownMACaddress(OUI)toIEEE(ofcoursethisisnotrecommendedforthehobbyistasthiswillbeveryexpensiveunlessyoucouldeffortit)oryoucouldsimplyuseyourowncomputerNIC’sMACaddressandjustchangethelastbyteofthe6byteMACaddressandcrossyoufinger,hoppingthisMACaddresswillbeuniquewithinyournetworkasIdid.Byusingthe“ipconfig/all”commandinthewindowcommandprompt,youcouldgettheinformationofyourcomputerMACaddressinhexnotationi.e.

00-16-36-DE-58-F5(theMACaddressofmycomputer);nowbyaddingonetothelastbyteyouwillgettheW5100MACaddressthatIusedinthistutorial(00-16-36-DE-58-F6).

TheWiznetW5100supportuptofoursimultaneouschannelsorsockets,eachofthechannelshasitsownregistersaddresstocontroltheoperation.Allofthesechannelsissupportedby8KBmemoryofthetransmitbufferand8KBmemoryofthereceivebuffer.WecouldadjustthismemorysizeoneachchannelbyassigningtheRMSRandTMSRregister(thedefaultis2KBforeachchannel)asshownonthisfollowingCcode:

//SettingtheWiznetW5100RXandTXMemorySize,weuse2KBforRx/Tx4channelsprintf("SettingWiznetRMSRandTMSR\n\n");

SPI_Write(RMSR,0x55);

SPI_Write(TMSR,0x55);

AlltheW5100initializationroutineisimplementedinW5100_Init()function,whereweperformbothwritingandreadinginordertounderstandhowwecouldcontroltheW5100registerthroughtheSPI.ThefollowingisthesummaryofhowweinitializedtheW5100register.ForthecompleteinformationabouttheW5100registerspleaserefertotheWiznetW5100datasheet(consideritasyourbestfriendinthistutorial):

Write0×80toW5100MR(ModeRegister)onaddress:0×0000tosoftresetthechip

AssignfourbytesofthegatewayIPaddresstotheW5100GAR(GatewayAddressRegister)onaddress0×0001to0×0004

AssignfourbytesofthesubmaskaddresstotheW5100SUBR(SubMaskAddressRegister)onaddress0×0005to0×0008

AssignsixbytesoftheMACaddresstotheW5100SAR(SourceAddressRegister)onaddress0×0009to0×000E

AssignfourbytesoftheIPaddresstotheW5100SIPR(SourceIPRegister)onaddress0×000Fto0×0012

ThelastistoallocatethetransmitandreceivebuffersizetoeachofRMSR(RXMemorySizeRegister)address:0×001AandTMSR(TXMemorySizeRegister)onaddress0×001B.

Becauseweusethedefaultvalue0×07D0(200ms,where1mean100us)oftheRTR(RetryTimeValueRegister)anddefaultvalue0×08(8timesretrybeforegeneratinginterrupt)oftheRCR(RetryCountRegister),thereforewedon’tneedtosettheseregisters

AfterperformingalltheW5100requiredinitializationroutineyoucouldexaminewhetheritworkornotbysendingthe“ping”commandtotheW5100buildinICMP(InternetControlMessageProtocol)packageresponder.Ifeverythingworks,thenyouwillgettheICMPreplyfromtheWiznetW5100chip.Withthisunderstandingnowwearereadytocontinuethistutorialandmakeourfirstsimpleembeddedwebserver.

TheEmbeddedWebServer

TheadvantageofusingtheHypertextTransferProtocol(HTTP)serverintheembeddedsystemis;youdon’thavetodevelopaspecialclientapplicationtocommunicatewithyourembeddedsystem.Allyouneedistouseanystandardbrowserthatcomeswithyourpersonalcomputeroperatingsystemorgadgettotalktoyourembeddedsystem.TheHTTPserverusesasimpletextcalledHypertextMarkupLanguage(HTML)tointeractwiththebrowser(clientapplication)throughtheTCP/IPprotocol.

TheHTTPserverworkbylisteningtoanyrequestfromtheclient(browser)foranyHTTP“GET”or“POST”requestthroughtheTCP/IPport80(standardHTTPserverport).OncetheclientsendsthisrequesttotheHTTPserver,thentheHTTPserverwillresponsetothisclientrequestbysendingtheHTTPresponseheader(HTTP/1.0200OKandContent-Type:text/html)followbytheblanklineandtheHTMLtexttotheclient,aftertransferalltheHTMLtexttotheclient;theHTTPserverwillautomaticallydisconnecttheestablishedconnectionwiththeclient.ThefollowingistheexampleoftheclientrequestandtheHTMLtextresponsetransmittedbytheembeddedHTTPserver:

ClientRequest:

GET/HTTP/1.1Host:01

User-Agent:Mozilla/5.0(Windows;U;WindowsNT5.1;en-US;rv:)Gecko/20100401Firefox/3.6.3

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language:en-us,en;q=0.5

Accept-Encoding:gzip,deflate

Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive:115

Connection:keep-alive

HTTPServerResponse:

HTTP/1.0200OK

Content-Type:text/html

<html>

<body>

<spanstyle="color:#0000A0">

<h1>EmbeddedWebServer</h1>

<h3>AVRJazzMega328andWIZ811MJ</h3>

<p><formmethod="POST">

<strong>Temp:<inputtype="text"size=2value="26"><sup>O</sup>C

<p><inputtype="radio"name="radio"value="0">BlinkingLED

<br><inputtype="radio"name="radio"value="1"checked>ScanningLED

</strong><p>

<inputtype="submit">

</form></span>

</body>

</html>

TheclientthenwilltranslatethisreceivedHTMLtextanddisplaytheinformationonthebrowserscreensuchasroom’stemperatureandtheoutputLEDstatus.BysubmittingdifferentLEDsettingfromthebrowser(POSTrequest)totheHTTPserver,nowwecouldeasilygivetheneededinstructiontotheAVRATMega328microcontrollerthatalsofunctionedastheembeddedwebserver.

NowasyouunderstandthebasicprincipalofhowtheHTTPserverprotocolwork,itstimetoimplementitontheAVRATMega328MicrocontrollerandWiznetW5100chip.ThefollowingisthecompleteCcodecalled“wiznetweb.c”forourembeddedwebserver:

/*****************************************************************************

// FileName :wiznetweb.c

// Version :1.0

// Description :AVRJazzMega328andWiznetW5100WebServer

// Author :RWB

// Target :AVRJazzMega328Board

// Compiler :AVR-GCC4.3.2;avr-libc1.6.6(WinAVR0313)

// IDE :AtmelAVRStudio4.17

// Programmer :AVRJazzMega328STK500v2.0Bootloader

// :AVRVisualStudio4.17,STK500programmer

// LastUpdated:20July

*****************************************************************************/#include<avr/io.h>

#include<string.h>#include<stdio.h>#include<util/delay.h>#include<avr/interrupt.h>

#include<avr/pgmspace.h>

//AVRJazzMega328SPII/O#defineSPI_PORTPORTB#defineSPI_DDR DDRB#defineSPI_CS PORTB2

//WiznetW5100OpCode

#defineWIZNET_WRITE_OPCODE0xF0#defineWIZNET_READ_OPCODE0x0F

//WiznetW5100RegisterAddresses

#define

MR

0x0000

//

ModeRegister

#define

GAR

0x0001

//

GatewayAddress:0x0001to0x0004

#define

SUBR

0x0005

//

SubnetmaskAddress:0x0005to0x0008

#define

SAR

0x0009

//

SourceHardwareAddress(MAC):0x0009to0x000E

#define

SIPR

0x000F

//

SourceIPAddress:0x000Fto0x0012

#define

RMSR

0x001A

//

RXMemory

SizeRegister

#define

TMSR

0x001B

//

TXMemory

SizeRegister

#define

S0_MR

0x0400

//

Socket0:

ModeRegisterAddress

#define

S0_CR

0x0401

//

Socket0:

CommandRegisterAddress

#define

S0_IR

0x0402

//

Socket0:

InterruptRegisterAddress

#define

S0_SR

0x0403

//

Socket0:

StatusRegisterAddress

#define

S0_PORT

0x0404

//

Socket0:

SourcePort:0x0404to0x0405

#define

SO_TX_FSR

0x0420

//

Socket0:

TxFreeSizeRegister:0x0420to0x0421

#define

S0_TX_RD

0x0422

//

Socket0:

TxReadPointerRegister:0x0422to0x0423

#define

S0_TX_WR

0x0424

//

Socket0:

TxWritePointerRegister:0x0424to0x0425

#defineS0_RX_RSR 0x0426 //Socket0:RxReceivedSizePointerRegister:0x0425to0x0427#defineS0_RX_RD 0x0428 //Socket0:RxReadPointer:0x0428to0x0429

#defineTXBUFADDR 0x4000 //W5100SendBufferBaseAddress#defineRXBUFADDR 0x6000 //W5100ReadBufferBaseAddress

//S0_MRvalues

#define

MR_CLOSE

0x00

//

Unusedsocket

#define

MR_TCP

0x01

//

TCP

#define

MR_UDP

0x02

//

UDP

#define

MR_IPRAW

0x03

//

IPLAYERRAWSOCK

#define

MR_MACRAW

0x04

//

MACLAYERRAWSOCK

#define

MR_PPPOE

0x05

//

PPPoE

#define

MR_ND

0x20

//

NoDelayedAck(TCP)flag

#define

MR_MULTI

0x80

//

supportmulticating

//S0_CRvalues

#define

CR_OPEN

0x01

//

Initializeoropensocket

#define

CR_LISTEN

0x02

//

Waitconnectionrequestintcpmode(Server

mode)

#define

CR_CONNECT

0x04

//

Sendconnectionrequestintcpmode(Clientmode)

#define

CR_DISCON

0x08

//

Sendclosingreqeusetintcpmode

#define

CR_CLOSE

0x10

//

Closesocket

#define

CR_SEND

0x20

//

UpdateTxmemorypointerandsenddata

#define

CR_SEND_MAC

0x21

//

SenddatawithMACaddress,sowithoutARPprocess

#define

CR_SEND_KEEP

0x22

//

Sendkeepalivemessage

#defineCR_RECV 0x40 //UpdateRxmemorybufferpointerandreceivedata

//S0_SRvalues

#define

SOCK_CLOSED

0x00

//Closed

#define

SOCK_INIT

0x13

//Initstate

#define

SOCK_LISTEN

0x14

//Listenstate

#define

SOCK_SYNSENT

0x15

//Connectionstate

#define

SOCK_SYNRECV

0x16

//Connectionstate

#define

SOCK_ESTABLISHED

0x17

//Successtoconnect

#define

SOCK_FIN_WAIT

0x18

//Closingstate

#define

SOCK_CLOSING

0x1A

//Closingstate

#define

SOCK_TIME_WAIT

0x1B

//Closingstate

#define

SOCK_CLOSE_WAIT

0x1C

//Closingstate

#define

SOCK_LAST_ACK

0x1D

//Closingstate

#define

SOCK_UDP

0x22

//UDPsocket

#define

SOCK_IPRAW

0x32

//IPrawmodesocket

#define

SOCK_MACRAW

0x42

//MACrawmodesocket

#define

SOCK_PPPOE

0x5F

//PPPOEsocket

#define

TX_BUF_MASK

0x07FF

//Tx2KBufferMask:

#define

RX_BUF_MASK

0x07FF

//Rx2KBufferMask:

#define

NET_MEMALLOC

0x05

//Use2KofTx/RxBuffer

#define

TCP_PORT

80

//TCP/IPPort

//DebuggingMode,0-DebugOFF,1-DebugON#define_DEBUG_MODE 0

#if_DEBUG_MODE

#defineBAUD_RATE19200#endif

//DefineW5100SocketRegisterandVariablesUseduint8_tsockreg;

#defineMAX_BUF512uint8_tbuf[MAX_BUF];inttempvalue;

uint8_tledmode,ledeye,ledsign;#if_DEBUG_MODE

voiduart_init(void)

{

UBRR0H=(((F_CPU/BAUD_RATE)/16)-1)>>8; //setbaudrateUBRR0L=(((F_CPU/BAUD_RATE)/16)-1);

UCSR0B=(1<<RXEN0)|(1<<TXEN0); //enableRx&TxUCSR0C= (1<<UCSZ01)|(1<<UCSZ00); //configUSART;8N1

}

voiduart_flush(void)

{

unsignedchardummy;

while(UCSR0A&(1<<RXC0))dummy=UDR0;

}

intuart_putch(charch,FILE*stream)

{

if(ch=='\n')uart_putch('\r',stream);

while(!(UCSR0A&(1<<UDRE0)));UDR0=ch;

return0;

}

intuart_getch(FILE*stream)

{

unsignedcharch;

while(!(UCSR0A&(1<<RXC0)));ch=UDR0;

/*EchotheOutputBacktoterminal*/uart_putch(ch,stream);

returnch;

}

voidansi_cl(void)

{

//ANSIclearscreen:cl=\E[H\E[Jputchar(27);

putchar('[');

putchar('H');putchar(27);putchar('[');

putchar('J');

}

voidansi_me(void)

{

//ANSIturnoffallattribute:me=\E[0mputchar(27);

putchar('[');

putchar('0');

putchar('m');

}

#endif

voidSPI_Write(uint16_taddr,uint8_tdata)

{

//ActivatetheCSpinSPI_PORT&=~(1<<SPI_CS);

//StartWiznetW5100WriteOpCodetransmissionSPDR=WIZNET_WRITE_OPCODE;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//StartWiznetW5100AddressHighBytestransmissionSPDR=(addr&0xFF00)>>8;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//StartWiznetW5100AddressLowBytestransmissionSPDR=addr&0x00FF;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//StartDatatransmissionSPDR=data;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//CSpinisnotactiveSPI_PORT|=(1<<SPI_CS);

}

unsignedcharSPI_Read(uint16_taddr)

{

//ActivatetheCSpinSPI_PORT&=~(1<<SPI_CS);

//StartWiznetW5100ReadOpCodetransmissionSPDR=WIZNET_READ_OPCODE;

//Waitfortransmissioncomplete

while(!(SPSR&(1<<SPIF)));

//StartWiznetW5100AddressHighBytestransmissionSPDR=(addr&0xFF00)>>8;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//StartWiznetW5100AddressLowBytestransmissionSPDR=addr&0x00FF;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//SendDummytransmissionforreadingthedataSPDR=0x00;

//Waitfortransmissioncompletewhile(!(SPSR&(1<<SPIF)));

//CSpinisnotactiveSPI_PORT|=(1<<SPI_CS);

return(SPDR);

}

voidW5100_Init(void)

{

//EthernetSetup

unsignedcharmac_addr[]={0x00,0x16,0x36,0xDE,0x58,0xF6};uns

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论