Hardware Reference
In-Depth Information
Before you can write your program, you need to
establish some basic information about how your
Ethernet module will connect to the Internet. Just as you
did in Chapter 3, you'll need the device's Media Access
Control (MAC) address. That's the hardware address of
your Ethernet controller. The Arduino Ethernet modules
have a six-byte address on the back, written in hexadeci-
mal notation, that you can use. If the sticker's missing
for any reason, you can make up your own MAC address,
or use the generic one you find in the examples below.
You'll also need to know the router's address (aka the
gateway address because your router is the gateway to
the rest of the Internet), as well as the address that your
device will use on the router's subnet.
Ethernet module—as long as no other device connected to
the router is using the same address.
When a router assigns addresses to its connected devices,
it masks part of the address space so that those devices
can use only addresses in the same subnet as the router
itself. For example, if the router is going to assign only
addresses in the range 192.168.1.2 through 192.168.1.254,
it masks out the top three numbers (octets). This is
called the netmask , or subnet mask . In your PC's network
settings, you'll see it written as a full network address, like
so: 255.255.255.0 . With the Ethernet module, you'll assign
it similarly.
Once you know your MAC address, your router's address,
your IP address, and your subnet mask, you're ready to go.
X
Your device's IP address will be similar to your router's
address, probably using the same three numbers for the
start of the address, but a different number for the last.
For example, if your router's local address is 192.168.1.1,
you can use an address like 192.168.1.20 for your
/*
Web Server
Context: Arduino
Try It
To get started, you
need to include
the SPI library and the Ethernet library
to control the module. You also need
to initialize a variable to hold a server
instance. The server will run on port 80,
just as most web servers do.
*/
#include <SPI.h>
#include <Ethernet.h>
8 Change these to match your own device
and network.
You also need four variables for the
MAC address, IP address, gateway
address, and subnet mask. These last
four will be arrays of bytes, one byte for
each byte in the respective addresses.
Server server(80);
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 };
IPAddress gateway( 192,168,1,1 );
IPAddress subnet( 255,255,255,0 );
IPAddress ip( 192,168,1,20 );
In the setup() method, you'll start
the Ethernet module and the
server. Open the serial connection as
well, for debugging purposes.
8
void setup()
{
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.begin(9600);
}
 
Search WWH ::




Custom Search