Saturday, 5 October 2013

Storing Arduino Ethernet Configuration in EEPROM

One of the interesting things about using Ethernet with the Arduino is that you need to set up the hardware address manually. This address (known as the MAC address) is a six byte number that uniquely identifies a device on a network. Usually, network adapters have a hardware assigned MAC which can't be changed, but on the Arduino, it has to be set in software.

Setting the MAC in the software becomes a problem if you want to upload a sketch to multiple Arduinos on the same network. You need to remember to tailor each sketch so that each device has a unique MAC address. Forgetting to do this, or incorrectly duplicating a MAC can cause issues, such as not being able to connect to one or more Arduinos.

One common solution is to store the MAC address in the Arduino's EEPROM, an area of memory that survives after the Arduino has been reset. There are a number of libraries and tutorials around that do this, such as the ones from z900collector, Mitchnicegear and blackcatm. I found that they didn't go far enough, as I also wanted to store the IP configuration in EEPROM as well as the MAC.

Storing both MAC and IP configuration means that the network configuration is independent of the loaded sketch. After initial setup, each Arduino will have its network configuration tied to the hardware, rather than the software. Subsequently, any number of ethernet enabled sketches can be loaded, and as long as they all use the NetEEPROM library, the MAC address and network configuration will remain the same for each sketch on the same hardware.

I've written the NetEEPROM library that stores to EEPROM:
  • a MAC address; and
  • whether DHCP or manual IP configuration is used; and
  • if manual IP configuration is used, the IP address, DNS server address, gateway address and subnet mask.
In addition, there are functions and examples to set the MAC address and network configuration for both DHCP and manual IP configurations.

Initialising the Ethernet adapter to use the stored configuration is simple, it's just requires one line in the setup() function:

NetEeprom.begin();

If there is no network configuration stored in EEPROM and NetEeprom.begin() is called, then the network adapter is set up with a random MAC address and will use DHCP for IP configuration. The randomised configuration is saved to EEPROM so that the same MAC will be used the next time.

I've released the NetEEPROM library on github and entered it into the public domain in the hope that someone will find it useful.