WebClient.ino 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. Web client
  3. This sketch connects to a website (http://www.google.com)
  4. using an Arduino Wiznet Ethernet shield.
  5. Circuit:
  6. * Ethernet shield attached to pins 10, 11, 12, 13
  7. created 18 Dec 2009
  8. by David A. Mellis
  9. modified 9 Apr 2012
  10. by Tom Igoe, based on work by Adrian McEwen
  11. */
  12. #include <SPI.h>
  13. #include <Ethernet2.h>
  14. // Enter a MAC address for your controller below.
  15. // Newer Ethernet shields have a MAC address printed on a sticker on the shield
  16. byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  17. // if you don't want to use DNS (and reduce your sketch size)
  18. // use the numeric IP instead of the name for the server:
  19. //IPAddress server(74,125,232,128); // numeric IP for Google (no DNS)
  20. char server[] = "www.google.com"; // name address for Google (using DNS)
  21. // Set the static IP address to use if the DHCP fails to assign
  22. IPAddress ip(192, 168, 0, 177);
  23. // Initialize the Ethernet client library
  24. // with the IP address and port of the server
  25. // that you want to connect to (port 80 is default for HTTP):
  26. EthernetClient client;
  27. void setup() {
  28. // Open serial communications and wait for port to open:
  29. Serial.begin(9600);
  30. while (!Serial) {
  31. ; // wait for serial port to connect. Needed for Leonardo only
  32. }
  33. // start the Ethernet connection:
  34. if (Ethernet.begin(mac) == 0) {
  35. Serial.println("Failed to configure Ethernet using DHCP");
  36. // no point in carrying on, so do nothing forevermore:
  37. // try to congifure using IP address instead of DHCP:
  38. Ethernet.begin(mac, ip);
  39. }
  40. // give the Ethernet shield a second to initialize:
  41. delay(1000);
  42. Serial.println("connecting...");
  43. // if you get a connection, report back via serial:
  44. if (client.connect(server, 80)) {
  45. Serial.println("connected");
  46. // Make a HTTP request:
  47. client.println("GET /search?q=arduino HTTP/1.1");
  48. client.println("Host: www.google.com");
  49. client.println("Connection: close");
  50. client.println();
  51. }
  52. else {
  53. // kf you didn't get a connection to the server:
  54. Serial.println("connection failed");
  55. }
  56. }
  57. void loop()
  58. {
  59. // if there are incoming bytes available
  60. // from the server, read them and print them:
  61. if (client.available()) {
  62. char c = client.read();
  63. Serial.print(c);
  64. }
  65. // if the server's disconnected, stop the client:
  66. if (!client.connected()) {
  67. Serial.println();
  68. Serial.println("disconnecting.");
  69. client.stop();
  70. // do nothing forevermore:
  71. while (true);
  72. }
  73. }