Ethernet Library

PIC32MX family of microcontrollers feature an embedded Ethernet controller module. The Ethernet controller is a bus master module that interfaces with an off-chip Physical Layer (PHY) to implement a complete Ethernet node in a system.

It provides the modules needed to implement a 10/100 Mbps Ethernet node using an external PHY chip. In order to offload the CPU from moving packet data to and from the module, internal descriptor-based DMA engines are included in the controller.

The Ethernet Controller consists of the following modules:

Ethernet library supports :

  Important :

Library Routines

Ethernet_Init

Prototype

void Ethernet_Init(unsigned char *mac, unsigned char *ip, unsigned long configuration);

Returns

Nothing.

Description

This is MAC module routine. It initializes Ethernet controller. This function is internaly splited into 2 parts to help linker when coming short of memory.

Ethernet controller settings (parameters not mentioned here are set to default):

  • RAM buffer read/write pointers in auto-increment mode.
  • receive filters set to default: CRC + MAC Unicast + MAC Broadcast in OR mode.
  • flow control with TX and RX pause frames in full duplex mode.
  • maximum packet size is set to 1536.
  • Back-to-Back Inter-Packet Gap: 0x15 in full duplex mode; 0x12 in half duplex mode.
  • Non-Back-to-Back Inter-Packet Gap: 0x0012 in full duplex mode; 0x0C12 in half duplex mode.
  • half duplex loopback disabled.
  • LED configuration: default (LEDA-link status, LEDB-link activity).

Parameters:

  • mac: RAM buffer containing valid MAC address.
  • ip: RAM buffer containing valid IP address.
  • configuration: ethernet duplex mode switch. Valid values:
    • _ETHERNET_HALFDUPLEX
    • _ETHERNET_FULLDUPLEX
    • _ETHERNET_SPEED_10
    • _ETHERNET_SPEED_100
    • _ETHERNET_DEFAULT_MAC - if this flag is used, default MAC address written in the MCU is used
    • _ETHERNET_CUSTOM_MAC - if this flag is used, the MAC address in the routine is used
    • _ETHERNET_AUTO_NEGOTIATION
    • _ETHERNET_MANUAL_NEGOTIATION
  Note : If a DHCP server is to be used, IP address should be set to 0.0.0.0.
Requires Nothing.
Example
#define Ethernet_HALFDUPLEX     0
#define Ethernet_FULLDUPLEX     1

unsigned char myMacAddr[6] = {0x00, 0x14, 0xA5, 0x76, 0x19, 0x3f}; // my MAC address	
unsigned char myIpAddr     = {192, 168,   1, 60 };  // my IP addr

Ethernet_Init(myMacAddr, myIpAddr, _ETHERNET_AUTO_NEGOTIATION);

Ethernet_SetPHYInit

Prototype

void Ethernet_SetPHYInit(void(*PHYInit_Ptr)(void))

Returns

Nothing.

Description

By default, the Ethernet library implementation initializes the PHY SMSC 8720A chip (present on the mikroElektronika's MultiMedia Board for PIC32MX7).
If the user wants initialization for some other PHY module, this routine can be used to pass a pointer to the custom PHY initialization routine.

Parameters:

  • TEthernet_PHYInit_Ptr: pointer to the custom PHY initialization routine.
Requires Nothing.
Example
Ethernet_SetPHYInit(&Phy_Init);

Ethernet_Set_Default_PHY

Prototype

void Ethernet_Set_Default_PHY();

Returns

Nothing.

Description

initializes the PHY SMSC 8720A chip (present on the mikroElektronika's MultiMedia Board for PIC32MX7) to the library default.

Parameters:

  • None.
Requires Nothing.
Example
Ethernet_Set_Default_PHY();

Ethernet_Enable

Prototype

void Ethernet_Enable(unsigned char enFlt);

Returns

Nothing.

Description

This is MAC module routine. This routine enables appropriate network traffic on the MCU's internal Ethernet module by the means of it's receive filters (unicast, multicast, broadcast, crc). Specific type of network traffic will be enabled if a corresponding bit of this routine's input parameter is set. Therefore, more than one type of network traffic can be enabled at the same time. For this purpose, predefined library constants (see the table below) can be ORed to form appropriate input value.

Parameters:

  • enFlt: network traffic/receive filter flags. Each bit corresponds to the appropriate network traffic/receive filter:
  • Bit Mask Description Predefined library const
    0 0x01 MAC Broadcast traffic/receive filter flag. When set, MAC broadcast traffic will be enabled. _Ethernet_BROADCAST
    1 0x02 MAC Multicast traffic/receive filter flag. When set, MAC multicast traffic will be enabled. _Ethernet_MULTICAST
    2 0x04 not used none
    3 0x08 MAC Unicast traffic/receive filter flag. When set, MAC unicast traffic will be enabled. _Ethernet_UNICAST
    4 0x10 not used none
    5 0x20 not used none
    6 0x40 CRC check flag. When set, packets with invalid CRC field will be discarded. _Ethernet_CRC
    7 0x80 not used none

      Note :
    • Advanced filtering available in the MCU's internal Ethernet module such as Pattern Match, Magic Packet and Hash Table can not be enabled by this routine.
      Additionaly, all filters, except CRC, enabled with this routine will work in OR mode, which means that packet will be received if any of the enabled filters accepts it.
    • This routine will change receive filter configuration on-the-fly. It will not, in any way, mess with enabling/disabling receive/transmit logic or any other part of the MCU's internal Ethernet module.
      The MCU's internal Ethernet module should be properly cofigured by the means of Ethernet_Init routine.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
Ethernet_Enable(_Ethernet_CRC | _Ethernet_UNICAST); // enable CRC checking and Unicast traffic

Ethernet_Disable

Prototype

void Ethernet_Disable(unsigned char disFlt);

Returns

Nothing.

Description

This is MAC module routine. This routine disables appropriate network traffic on the MCU's internal Ethernet module by the means of it's receive filters (unicast, multicast, broadcast, crc). Specific type of network traffic will be disabled if a corresponding bit of this routine's input parameter is set. Therefore, more than one type of network traffic can be disabled at the same time. For this purpose, predefined library constants (see the table below) can be ORed to form appropriate input value.

Parameters:

  • disFlt: network traffic/receive filter flags. Each bit corresponds to the appropriate network traffic/receive filter:
  • Bit Mask Description Predefined library const
    0 0x01 MAC Broadcast traffic/receive filter flag. When set, MAC broadcast traffic will be enabled. _Ethernet_BROADCAST
    1 0x02 MAC Multicast traffic/receive filter flag. When set, MAC multicast traffic will be enabled. _Ethernet_MULTICAST
    2 0x04 not used none
    3 0x08 MAC Unicast traffic/receive filter flag. When set, MAC unicast traffic will be enabled. _Ethernet_UNICAST
    4 0x10 not used none
    5 0x20 not used none
    6 0x40 CRC check flag. When set, packets with invalid CRC field will be discarded. _Ethernet_CRC
    7 0x80 not used none

      Note :
    • Advance filtering available in the MCU's internal Ethernet module such as Pattern Match, Magic Packet and Hash Table can not be disabled by this routine.
    • This routine will change receive filter configuration on-the-fly. It will not, in any way, mess with enabling/disabling receive/transmit logic or any other part of the MCU's internal Ethernet module.
    • The MCU's internal Ethernet module should be properly cofigured by the means of Ethernet_Init routine.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
Ethernet_Disable(_Ethernet_CRC | _Ethernet_UNICAST); // disable CRC checking and Unicast traffic

Ethernet_doPacket

Prototype

unsigned char Ethernet_doPacket();

Returns

  • 0 - upon successful packet processing (zero packets received or received packet processed successfully).
  • 1 - upon reception error or receive buffer corruption. Ethernet controller needs to be restarted.
  • 2 - received packet was not sent to us (not our IP, nor IP broadcast address).
  • 3 - received IP packet was not IPv4.
  • 4 - received packet was of type unknown to the library.

Description

This is MAC module routine. It processes next received packet if such exists. Packets are processed in the following manner:

  • ARP & ICMP requests are replied automatically.
  • upon TCP request the Ethernet_UserTCP function is called for further processing.
  • upon UDP request the Ethernet_UserUDP function is called for further processing.
  Note : Ethernet_doPacket must be called as often as possible in user's code.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
if (Ethernet_doPacket() == 0) { // process received packets
  ...
}

Ethernet_putByte

Prototype

void Ethernet_putByte(unsigned char v);

Returns

Nothing.

Description

This is MAC module routine. It stores one byte at current write location.

Parameters:

  • v: value to store
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
char data_;
...
Ethernet_putByte(data_); // put an byte into buffer

Ethernet_putBytes

Prototype

void Ethernet_putBytes(unsigned char *ptr, unsigned int n);

Returns

Nothing.

Description

This is MAC module routine. It stores requested number of bytes into RAM at current write location.

Parameters:

  • ptr: RAM buffer containing bytes to be written into RAM.
  • n: number of bytes to be written.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
char *buffer =  "mikroElektronika";	 
...
Ethernet_putBytes(buffer, 16); // put an RAM array into buffer

Ethernet_putConstBytes

Prototype

void Ethernet_putConstBytes(const unsigned char *ptr, unsigned int n);

Returns

Nothing.

Description

This is MAC module routine. It stores requested number of const bytes into RAM at current write location.

Parameters:

  • ptr: const buffer containing bytes to be written into RAM.
  • n: number of bytes to be written.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
const char *buffer =  "mikroElektronika";	 
...
Ethernet_putConstBytes(buffer, 16); // put a const array into buffer

Ethernet_putString

Prototype

unsigned int Ethernet_putString(unsigned char *ptr);

Returns

Number of bytes written into RAM.

Description

This is MAC module routine. It stores whole string (excluding null termination) into RAM at current write location.

Parameters:

  • ptr: string to be written into RAM.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
char *buffer =  "mikroElektronika";	 
...
Ethernet_putString(buffer); // put a RAM string into buffer

Ethernet_putConstString

Prototype

unsigned int Ethernet_putConstString(const unsigned char *ptr);

Returns

Number of bytes written into RAM.

Description

This is MAC module routine. It stores whole const string (excluding null termination) into RAM at current write location.

Parameters:

  • ptr: const string to be written into RAM.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
const char *buffer =  "mikroElektronika"; 
...
Ethernet_putConstString(buffer); // put a const string into buffer

Ethernet_getByte

Prototype

unsigned char Ethernet_getByte();

Returns

Byte read from RAM.

Description

This is MAC module routine. It fetches a byte from address pointed to by current read location.

Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
char buffer; 
...
buffer = Ethernet_getByte(); // read a byte from buffer

Ethernet_getBytes

Prototype

void Ethernet_getBytes(unsigned char *ptr, unsigned long addr, unsigned int n);

Returns

Nothing.

Description

This is MAC module routine. It fetches requested number of bytes from RAM from address pointed to by current read location. If value of 0xFFFF is passed as the address parameter, the reading will start from current read location.

Parameters:

  • ptr: buffer for storing bytes read from RAM.
  • addr: RAM start address. Valid values: 0..8192.
  • n: number of bytes to be read.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
char buffer[16];	 
...
Ethernet_getBytes(buffer, 0x100, 16); // read 16 bytes, starting from address 0x100

Ethernet_UserTCP

Prototype

unsigned int Ethernet_UserTCP(unsigned char *remoteHost, unsigned int remotePort, unsigned int localPort, unsigned int reqLength, TEthPktFlags *flags);

Returns

  • 0 - there should not be a reply to the request.
  • Length of TCP/HTTP reply data field - otherwise.

Description

This is TCP module routine. It is internally called by the library. The user accesses to the TCP/HTTP request by using some of the Ethernet_get routines. The user puts data in the transmit buffer by using some of the Ethernet_put routines. The function must return the length in bytes of the TCP/HTTP reply, or 0 if there is nothing to transmit. If there is no need to reply to the TCP/HTTP requests, just define this function with return(0) as a single statement.

Parameters:

  • remoteHost: client's IP address.
  • remotePort: client's TCP port.
  • localPort: port to which the request is sent.
  • reqLength: TCP/HTTP request data field length.
  • flags: structure consisted of two bit fields :
    typedef struct {
      unsigned canCloseTCP: 1;  // flag which closes socket
      unsigned isBroadcast: 1;  // flag which denotes that the IP package has been received via subnet broadcast address (not used for PIC16 family)
    } TEthPktFlags;
    
  •   Note : The function source code is provided with appropriate example projects. The code should be adjusted by the user to achieve desired reply.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example

This function is internally called by the library and should not be called by the user's code.

Ethernet_UserUDP

Prototype

unsigned int Ethernet_UserUDP(unsigned char *remoteHost, unsigned int remotePort, unsigned int destPort, unsigned int reqLength, TEthPktFlags *flags);

Returns

  • 0 - there should not be a reply to the request.
  • Length of UDP reply data field - otherwise.

Description

This is UDP module routine. It is internally called by the library. The user accesses to the UDP request by using some of the Ethernet_get routines. The user puts data in the transmit buffer by using some of the Ethernet_put routines. The function must return the length in bytes of the UDP reply, or 0 if nothing to transmit. If you don't need to reply to the UDP requests, just define this function with a return(0) as single statement.

Parameters:

  • remoteHost: client's IP address.
  • remotePort: client's port.
  • destPort: port to which the request is sent.
  • flags: structure consisted of two bit fields :
    typedef struct {
      unsigned canCloseTCP: 1;  // flag which closes TCP socket (not relevant to UDP)
      unsigned isBroadcast: 1;  // flag which denotes that the IP package has been received via subnet broadcast address (not used for PIC16 family)
    } TEthPktFlags;
    
      Note : The function source code is provided with appropriate example projects. The code should be adjusted by the user to achieve desired reply.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example

This function is internally called by the library and should not be called by the user's code.

Ethernet_getIpAddress

Prototype

unsigned char * Ethernet_getIpAddress();

Returns Pointer to the global variable holding IP address.
Description

This routine should be used when DHCP server is present on the network to fetch assigned IP address.

  Note : User should always copy the IP address from the RAM location returned by this routine into it's own IP address buffer. These locations should not be altered by the user in any case!
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
unsigned char ipAddr[4];  // user IP address buffer
...	
memcpy(ipAddr, Ethernet_getIpAddress(), 4); // fetch IP address

Ethernet_getGwIpAddress

Prototype

unsigned char * Ethernet_getGwIpAddress();

Returns Pointer to the global variable holding gateway IP address.
Description

This routine should be used when DHCP server is present on the network to fetch assigned gateway IP address.

  Note : User should always copy the IP address from the RAM location returned by this routine into it's own gateway IP address buffer. These locations should not be altered by the user in any case!
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
unsigned char gwIpAddr[4];  // user gateway IP address buffer
...	
memcpy(gwIpAddr, Ethernet_getGwIpAddress(), 4); // fetch gateway IP address 

Ethernet_getDnsIpAddress

Prototype

unsigned char * Ethernet_getDnsIpAddress

Returns Pointer to the global variable holding DNS IP address.
Description

This routine should be used when DHCP server is present on the network to fetch assigned DNS IP address.

  Note : User should always copy the IP address from the RAM location returned by this routine into it's own DNS IP address buffer. These locations should not be altered by the user in any case!
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
unsigned char dnsIpAddr[4];  // user DNS IP address buffer
...	
memcpy(dnsIpAddr, Ethernet_getDnsIpAddress(), 4); // fetch DNS server address 

Ethernet_getIpMask

Prototype

unsigned char * Ethernet_getIpMask()

Returns Pointer to the global variable holding IP subnet mask.
Description

This routine should be used when DHCP server is present on the network to fetch assigned IP subnet mask.

  Note : User should always copy the IP address from the RAM location returned by this routine into it's own IP subnet mask buffer. These locations should not be altered by the user in any case!
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
unsigned char IpMask[4];  // user IP subnet mask buffer
...	
memcpy(IpMask, Ethernet_getIpMask(), 4); // fetch IP subnet mask

Ethernet_confNetwork

Prototype

void Ethernet_confNetwork(char *ipMask, char *gwIpAddr, char *dnsIpAddr);

Returns Nothing.
Description

Configures network parameters (IP subnet mask, gateway IP address, DNS IP address) when DHCP is not used.

Parameters:

  • ipMask: IP subnet mask.
  • gwIpAddr gateway IP address.
  • dnsIpAddr: DNS IP address.
  Note : The above mentioned network parameters should be set by this routine only if DHCP module is not used. Otherwise DHCP will override these settings.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
unsigned char ipMask[4]    = {255, 255, 255,  0 };  // network mask (for example : 255.255.255.0)
unsigned char gwIpAddr[4]  = {192, 168,   1,  1 };  // gateway (router) IP address
unsigned char dnsIpAddr[4] = {192, 168,   1,  1 };  // DNS server IP address
...	
Ethernet_confNetwork(ipMask, gwIpAddr, dnsIpAddr); // set network configuration parameters

Ethernet_arpResolve

Prototype

unsigned char *Ethernet_arpResolve(unsigned char *ip, unsigned char tmax);

Returns
  • MAC address behind the IP address - the requested IP address was resolved.
  • 0 - otherwise.
Description

This is ARP module routine. It sends an ARP request for given IP address and waits for ARP reply. If the requested IP address was resolved, an ARP cash entry is used for storing the configuration. ARP cash can store up to 3 entries. For ARP cash structure refer to __EthernetPrivate.mpas header file in the compiler's Uses folder.

Parameters:

  • ip: IP address to be resolved.
  • tmax: time in seconds to wait for an reply.
  Note : The Ethernet services are not stopped while this routine waits for ARP reply. The incoming packets will be processed normaly during this time.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
unsigned char IpAddr[4]  = {192, 168,   1,  1 };  // IP address
...	
Ethernet_arpResolve(IpAddr, 5); // get MAC address behind the above IP address, wait 5 secs for the response

Ethernet_sendUDP

Prototype

unsigned char Ethernet_sendUDP(unsigned char *destIP, unsigned int sourcePort, unsigned int destPort, unsigned char *pkt, unsigned int pktLen);

Returns
  • 1 - UDP packet was sent successfully.
  • 0 - otherwise.
Description

This is UDP module routine. It sends an UDP packet on the network.

Parameters:

  • destIP: remote host IP address.
  • sourcePort: local UDP source port number.
  • destPort: destination UDP port number.
  • pkt: packet to transmit.
  • pktLen: length in bytes of packet to transmit.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
unsigned char IpAddr[4]  = {192, 168,   1,  1 };  // remote IP address
...	
Ethernet_sendUDP(IpAddr, 10001, 10001, "Hello", 5); // send Hello message to the above IP address, from UDP port 10001 to UDP port 10001 

Ethernet_dnsResolve

Prototype

unsigned char *Ethernet_dnsResolve(unsigned char *host, unsigned char tmax);

Returns
  • pointer to the location holding the IP address - the requested host name was resolved.
  • 0 - otherwise.
Description

This is DNS module routine. It sends an DNS request for given host name and waits for DNS reply. If the requested host name was resolved, it's IP address is stored in library global variable and a pointer containing this address is returned by the routine. UDP port 53 is used as DNS port.

Parameters:

  • host: host name to be resolved.
  • tmax: time in seconds to wait for an reply.

The above mentioned network parameters should be set by this routine only if DHCP module is not used. Otherwise DHCP will override these settings.

  Note :
  • The Ethernet services are not stopped while this routine waits for DNS reply. The incoming packets will be processed normaly during this time.
  • User should always copy the IP address from the RAM location returned by this routine into it's own resolved host IP address buffer. These locations should not be altered by the user in any case!
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
unsigned char * remoteHostIpAddr[4];	// user host IP address buffer
...
// SNTP server:
// Zurich, Switzerland: Integrated Systems Lab, Swiss Fed. Inst. of Technology
// 129.132.2.21: swisstime.ethz.ch
// Service Area: Switzerland and Europe	
memcpy(remoteHostIpAddr, Ethernet_dnsResolve("swisstime.ethz.ch", 5), 4);

Ethernet_initDHCP

Prototype

unsigned char Ethernet_initDHCP(unsigned char tmax);

Returns
  • 1 - network parameters were obtained successfully.
  • 0 - otherwise.
Description

This is DHCP module routine. It sends an DHCP request for network parameters (IP, gateway, DNS addresses and IP subnet mask) and waits for DHCP reply. If the requested parameters were obtained successfully, their values are stored into the library global variables.

These parameters can be fetched by using appropriate library IP get routines:

UDP port 68 is used as DHCP client port and UDP port 67 is used as DHCP server port.

Parameters:

  • tmax: time in seconds to wait for an reply.
  Note :
  • The Ethernet services are not stopped while this routine waits for DNS reply. The incoming packets will be processed normaly during this time.
  • When DHCP module is used, global library variable Ethernet_userTimerSec is used to keep track of time. It is user responsibility to increment this variable each second in it's code.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
...	
Ethernet_initDHCP(5); // get network configuration from DHCP server, wait 5 sec for the response 
...

Ethernet_doDHCPLeaseTime

Prototype

unsigned char Ethernet_doDHCPLeaseTime();

Returns
  • 0 - lease time has not expired yet.
  • 1 - lease time has expired, it's time to renew it.
Description

This is DHCP module routine. It takes care of IP address lease time by decrementing the global lease time library counter. When this time expires, it's time to contact DHCP server and renew the lease.

Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
while(1) {	
  ...
  if(Ethernet_doDHCPLeaseTime())
    ... // it's time to renew the IP address lease                  
}

Ethernet_renewDHCP

Prototype

unsigned char Ethernet_renewDHCP(unsigned char tmax);

Returns
  • 1 - upon success (lease time was renewed).
  • 0 - otherwise (renewal request timed out).
Description

This is DHCP module routine. It sends IP address lease time renewal request to DHCP server.

Parameters:

  • tmax: time in seconds to wait for an reply.
Requires

Ethernet module has to be initialized. See Ethernet_Init.

Example
while(1) {	
  ...
  if(Ethernet_doDHCPLeaseTime())
    Ethernet_renewDHCP(5); // it's time to renew the IP address lease, with 5 secs for a reply                  
  ...  
}
Copyright (c) 2002-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code