Ethernet devices all require two unique identifying addresses so they can operate on a TCP/IP network: an IP address, and a "MAC" address. The two addresses operate at different layers of the network, and although many people are familiar with IP addresses, MAC addresses are often considered a bit more mysterious. Even if you've set up computer networks before, it's likely you've never had to set or worry about MAC addresses until now.

But with Arduino and other microcontrollers, it's normal to have to configure the MAC address as well as the IP address when connecting them to a network.

Setting the MAC address in your sketch

MAC addresses need to be unique on the network, so with Arduino-compatible boards you usually need to configure their MAC address in the sketch. To see an example, launch the Arduino IDE and look in the menu File > Examples > Ethernet > WebServer to see the following code starting at line 21:

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1, 177);

Later in the sketch those values are used when the Ethernet connection is initialised:

  Ethernet.begin( mac, ip );

You can choose to specify the IP address as shown, or just pass in the MAC address and use DHCP to obtain the address.

Selecting a MAC address manually

Some devices come with a sticker on them showing a MAC address that's been assigned. If that's the case, easy: just put it into the sketch and you're done.

Mostly though you'll need to make up your own MAC address, and it's important that you create a valid address.

As you can see in the example above, a MAC address is a series of 6 hexadecimal values. Some parts of the address have a specific meaning: for example, the first three bytes represent the Organisationally Unique Identifier (OUI) while the last three bytes represent the specific Network Interface Controller (NIC). Specific bits within the OUI are also used to signify different modes, such as unicast or multicast.

To be on the safe side, it's best to leave the first byte statically set to "0xDE" as in the example and modify the rest of the address. That way you know you're not setting an unusual mode that may cause problems.

And here's the big problem: what address do you set? Where can you obtain one so you're sure it's unique?

Generally, you can just make up an address and it'll work. The chances of you picking the same MAC address as some other device on your network is ridiculously small, so if you start with the example MAC address shown above and just start incrementing it from the end you'll generally be OK. Your next device could be 0xDE 0xAD 0xBE 0xEF 0xFE 0xEE, for example. Then your third would end in 0xEF, the fourth in 0xF0, and so on.

Just keep a record of the addresses you've used so you don't double them up and you'll be fine.

Related Articles: