Hardware Reference
In-Depth Information
Connecting to the Network and Retrieving an IP via DHCP
Thanks to the wonders of DHCP, connecting to the network with the Arduino
Ethernet shield is a snap. Before showing you the code, let's look at what is
going to happen. At the top of your program, you should include the serial
peripheral interface (SPI) and Ethernet libraries, define the MAC address of your
Ethernet shield (it will be on a sticker on the shield), and create an instance of
EthernetServer . Within the setup() , you begin an Ethernet session with the
MAC address you've defined and start the web server. You can optionally sup-
ply a static IP address when initiating the Ethernet session, but by leaving that
argument out, the Arduino will connect via DCHP and return the assigned IP
address via the serial terminal. You can then use that IP address to connect to
Arduino and view the web page it will be hosting.
Replying to a Client Response
The main loop is responsible for a number of actions. To handle moving through
all these various action states, a number of “state variables” are used throughout
the loop to keep track of what actions have been performed and what still needs
to happen for successful communication with the client to take place.
The Arduino will always be checking for client connections (from your laptop,
for example) to the server. When a client connects, the Arduino replies with two
things: the HTTP response header and the HTML-formatted web page that was
requested. The response header tells your browser what kind of information is
about to be sent. When you have tried to visit a nonexistent web page, you've
probably gotten the dreaded “404 Response.” The 404 header indicates to the
browser that the server could not find the requested page. A “200 Response,”
in contrast, indicates that the request has been received and that the HTML
will be transmitted to the browser. So, on the Arduino, you want to send a “200
Response” to the browser and follow that up with a definition of the Content-
Type (HTML, in this case). This complete header looks like this:
HTTP/1.1 200 OK
Content-Type: text/html
This header must be followed by a blank line, then the content of your HTML
page that you wrote earlier. This same program is also used to reply to GET
requests. To identify GET requests, you need to look for the question mark char-
acter in the URL that specifies what parameters have been selected and sent. If
the ? is found, the program waits until it receives a variable name. In the case
of the HTML you wrote earlier, the command for LED control is an L , and the
command for the speaker frequency adjustment is an S . Depending on which
of these is in the URL, the program parses integers out of the URL and controls
Search WWH ::




Custom Search