I'm testing the Ethernet shield with an Arduino Uno, and I'm getting a DHCP error just using the example sketch.
#include <SPI.h>
#include <Ethernet.h>
byte MACaddress[] = { 0x90, 0xAD, 0xDA, 0x0D, 0x96, 0xFE };
EthernetClient client;
void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
// Start the Ethernet connection:
if (Ethernet.begin(MACaddress) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
for(;;)
;
}
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
Serial.println();
}
void loop() {
}
I've opened the router administration page, and I can see it gave the Arduino an IP address, associated with the MAC address. I've also tried a static IP address in the code (Ethernet.begin(MACaddress, IPaddress)), but it won't work either.
I can't ping the shield IP address that shows in the router administrator page.
What is wrong with just this simple code?
Everything is out of the box, the Arduino and the shield. I haven't done anything with them, just connected the shield to the Arduino and sent the code. It seems everything is working fine, the LEDs are blinking for both boards.
These loops are useless.. Could you try something like:
#if defined(ARDUINO) && ARDUINO > 18
#include <SPI.h>
#endif
#include <Ethernet.h>
#include <EthernetDHCP.h>
// MAC Address
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
const char* ip_to_str(const uint8_t*);
// Initialize the Ethernet server library
Server server(8080);
void setup()
{
Serial.begin(9600);
Serial.println("Attempting to obtain a DHCP lease...");
// Initiate a DHCP session. The argument is the MAC (hardware) address that
// you want your Ethernet shield to use. This call will block until a DHCP
// lease has been obtained. The request will be periodically resent until
// a lease is granted, but if there is no DHCP server on the network or if
// the server fails to respond, this call will block forever.
// Thus, you can alternatively use polling mode to check whether a DHCP
// lease has been obtained, so that you can react if the server does not
// respond (see the PollingDHCP example).
EthernetDHCP.begin(mac);
// Since we're here, it means that we now have a DHCP lease, so we print
// out some information.
const byte* ipAddr = EthernetDHCP.ipAddress();
const byte* gatewayAddr = EthernetDHCP.gatewayIpAddress();
const byte* dnsAddr = EthernetDHCP.dnsIpAddress();
Serial.println("A DHCP lease has been obtained.");
Serial.print("My IP address is ");
Serial.println(ip_to_str(ipAddr));
Serial.print("Gateway IP address is ");
Serial.println(ip_to_str(gatewayAddr));
Serial.print("DNS IP address is ");
Serial.println(ip_to_str(dnsAddr));
// Start the server
server.begin();
}
void loop()
{
// You should periodically call this method in your loop(): It will allow
// the DHCP library to maintain your DHCP lease, which means that it will
// periodically renew the lease and rebind if the lease cannot be renewed.
// Thus, unless you call this somewhere in your loop, your DHCP lease might
// expire, which you probably do not want :-)
EthernetDHCP.maintain();
// listen for incoming clients
Client client = server.available();
if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
// Some misc. HTML
client.println("<title>Arduino Control Panel</title>");
client.println("<center><h1>Control Panel</h1></center>");
client.println("<p></p>");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
client.print("Analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(analogRead(analogChannel));
client.println("<br />");
}
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}
// Just a utility function to nicely format an IP address.
const char* ip_to_str(const uint8_t* ipAddr)
{
static char buf[16];
sprintf(buf, "%d.%d.%d.%d\0", ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]);
return buf;
}
I'm not sure what you mean by "I've also tried a static IP address in the code". If you simply replaced
if (Ethernet.begin(MACaddress) == 0) {
with
if (Ethernet.begin(MACaddress, myIP) == 0) {
the result may be unpredictable, because there is no return value.
Read
EthernetBegin
Returns
The DHCP version of this function, Ethernet.begin(mac), returns an int: 1 on a successful DHCP connection, 0 on failure. The other versions don't return anything.
have you tried one of the examples with fixed IP's?
Related
I have been trying to setup a web server using Arduino. I have an UNO and a HanRun HR91105A I got off the internet, and I am using a modified version of the WebServer example to test my code. It did in fact work at first. But after setting up port forwarding, the connection suddenly became unstable. It connects and works for a few minutes, then suddenly I can't even ping it. Trying to ping the Arduino results in request time out. Research online suggests 2 possibilities:
1.) All the RAM is used up
2.) Ethernet shield is faulty
Below is my code
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0x44, 0x00, 0x10, 0x20, 0x8C, 0x0A
};
IPAddress ip(192,168,1,90);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(8081);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println("Refresh: 2");
client.println();
client.println("<!DOCTYPE HTML>");
//-----------------Type in outputs below-------------------------------------
client.println("<html>");
client.print("Hello World!");
client.print("<p id='Header'>");
client.print("Sensor Data");
client.println("</p>");
client.print("<p id='Pressure'>");
client.print("Pressure:");
client.println("</p>");
client.print("<p id='Acceleration'>");
client.print("Acceleration:");
client.println("</p>");
client.println("<br /)");
client.println("</html>");
break;
//-----------------End of outputs--------------------------------------------
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
} else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
}
}
Additionally, the arduino does have a static IP, so I'm pretty sure it is not an issue of DHCP lease expiry.
I highly suspect that the shield is faulty as it gets very hot while in operation. Plus it IS a knockoff. But I can't dismiss the possibility that my coding is just inefficient as I am not very experienced. Any help would be appreciated. Thanks.
Your Arduino will opperate unpredictably when RAM is not enough.
In this code, there are many constant string. you should store those strings in FLASH memory to save RAM. In order to to so, use F() macro. For example.
client.println(F("HTTP/1.1 200 OK"));
If your program is big, I recommend to use the shield that equips an embedded web sever (e.g PHPoC Shield)
Hi I am absolute newbee using ENC28J60, I want to upload some data to my seerver (in php) :
I take a php hosting from 0fees and now I can send the data to my server using : http://ashutest123.0fees.us/dataupload1.php?data=somedata and check the uploaded list of data in the table as http://ashutest123.0fees.us/showdata.php ——— u can take a view yourself.
I wrote an arduino code (using Aruino Uno and ENC28J60 module from ebay.in) using UIPEthernet lib
#include <UIPEthernet.h> // Used for Ethernet
// **** ETHERNET SETTING ****
// Arduino Uno pins: 10 = CS, 11 = MOSI, 12 = MISO, 13 = SCK
// Ethernet MAC address - must be unique on your network - MAC Reads T4A001 in hex (unique in your network)
byte mac[] = { 0x54, 0x34, 0x41, 0x30, 0x30, 0x31 };
// For the rest we use DHCP (IP address and such)
EthernetClient client;
char server[] = "ashutest123.0fees.us"; // IP Adres (or name) of server to dump data to
int interval = 5000; // Wait between dumps
void setup() {
Serial.begin(9600);
Ethernet.begin(mac);
Serial.println("Tweaking4All.com - Temperature Drone - v2.0");
Serial.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
Serial.print("IP Address : ");
Serial.println(Ethernet.localIP());
Serial.print("Subnet Mask : ");
Serial.println(Ethernet.subnetMask());
Serial.print("Default Gateway IP: ");
Serial.println(Ethernet.gatewayIP());
Serial.print("DNS Server IP : ");
Serial.println(Ethernet.dnsServerIP());
}
void loop() {
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("-> Connected");
// Make a HTTP request:
client.print( "GET /dataupload1.php?");
client.print("data=");
client.print( "somedata" );
client.println( " HTTP/1.1");
client.print( "Host: " );
client.println(server)
client.println( "Connection: close" );
client.println();
client.println();
client.stop();
}
else {
// you didn't get a connection to the server:
Serial.println("--> connection failed/n");
}
delay(interval);
}
when I run it in serial monitor it shows all ip, dns, gateway etc addresses as 0.0.0.0 ---- seems no dhcp abtained
then shows "connected"
no data goes to my server
Please help me I am in a need of it
Thanks in advance
You might want to try this example code, it might help you alot to understand your problem and where it come from.
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// this check is only needed on the Leonardo:
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
for (;;)
;
}
// print your local IP address:
printIPAddress();
}
void loop() {
switch (Ethernet.maintain())
{
case 1:
//renewed fail
Serial.println("Error: renewed fail");
break;
case 2:
//renewed success
Serial.println("Renewed success");
//print your local IP address:
printIPAddress();
break;
case 3:
//rebind fail
Serial.println("Error: rebind fail");
break;
case 4:
//rebind success
Serial.println("Rebind success");
//print your local IP address:
printIPAddress();
break;
default:
//nothing happened
break;
}
}
void printIPAddress()
{
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
Serial.println();
}
Then I let you edit your code with your custom functions to get all informations you might need.
Note that if you set an hard-coded IP address even in a DHCP range it will be working.
V.
I have been playing with the Arduino Ethernet shield. I can't get it to reliably accept connections when running a webserver type application. When I can't connect to it, I can't ping it. The message I get is "Reply from 192.168.1.14: Destination host unreachable.". Where 192.168.1.14 is the ip of the computer I am trying to connect from. Why would an ip on my local subnet be unreachable? Is the shield not correctly identifying itself on the network? Is there anything I can do in Arduino code?
Here is my code. If you see anything wrong, please let me know.
Update: I plugged it into my main home router instead of a switch and it worked immediately there. At any rate, once I can connect to it, it keep working as long as its powered on.
#include <WString.h>
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDA, 0x02 };
IPAddress ip(192,168,1,177);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
#define DOOR_BUTTON 2
String readString = String(100); //string for fetching data from address
void setup()
{
Serial.begin(9600);
digitalWrite(DOOR_BUTTON, LOW);
pinMode(DOOR_BUTTON, OUTPUT);
// start the Ethernet connection and the server:
Serial.println("Initiaizing ethernet...");
// this uses a fixed address
Ethernet.begin(mac, ip);
// get an address with DHCP
//if (Ethernet.begin(mac) == 0)
// Serial.println("Failed to configure Ethernet using DHCP");
// give the card a second to initialize
delay(1000);
server.begin();
Serial.print("Garage Door Opener Control Ready at IP address ");
Serial.println(Ethernet.localIP());
}
void loop()
{
// command received (one character) '1' - activate garage door button
char cmd = 0; // 1 - pulse button
boolean done = false; // set to indicate that response is complete
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
readString = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
//int i = c;
//Serial.print("(");
//Serial.print(i);
//Serial.print(")");
// store character received in receive string
if (readString.length() < 100) {
readString += (c);
}
// check for end of line
if (c == '\n') {
//Serial.print("Receved line: ");
//Serial.print(readString);
// process line if its the "GET" request
// a request looks like "GET /?1" or "GET /?2"
if (readString.indexOf("GET") != -1) {
if (readString.indexOf("?1") != -1)
cmd = '1';
// check for other commands here. ie turn on light, etc.
//if (readString.indexOf("?2") != -1)
// cmd = '2';
}
// if a blank line was received (just cr lf, length of 2), then its the end of the request
if (readString.length() == 2) {
if (cmd == '1'){
Serial.println("Activate Button");
digitalWrite(DOOR_BUTTON, HIGH);
delay(1000);
digitalWrite(DOOR_BUTTON, LOW);
}
// add other commands here
// send web page back to client
Serial.println("sending web page");
SendWebPage(client);
Serial.println("web page sent");
cmd = 0;
// break out and disconnect. This will tell the browser the request is complete without having to specify content-length
break;
} // end of request reached
// start line over
readString = "";
} // end of line reached
} // end data is available from client
} // end cient is connected
// give the web browser time to receive the data
Serial.println("delay before disconnect");
delay(100);
// close the connection:
client.stop();
Serial.println("client disonnected");
} // end client has been created
}
// send web page
void SendWebPage(EthernetClient client)
{
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
// to specify the length, wooul have to construct the entire string and then get its length
//client.println("Content-Length: 1234");
client.println("Connnection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head>");
client.println("<title>Garage Door Control</title>");
client.println("<style type='text/css'>");
client.println(".label {font-size: 40px; text-align:center;}");
client.println("button {width: 200px; height: 100px; font-size: 40px; -webkit-appearance: none; background-color:white; }");
client.println("</style>");
client.println("<script type='text/javascript'>");
client.println("function OnButtonClicked(parm) { window.location.href=\"X?\" + parm; }");
client.println("</script>");
client.println("</head>");
client.println("<body style=\"background-color:orange\">");
client.println("<div class=\"label\">");
client.println("Garage Door Control<br/><br/>");
// future idea: could read a limit switch on the garage door here and tell the user if the door is currently open or closed
/*
if (digitalRead(DOOR_OPEN_INPUT) == HIGH)
client.println("Door is Open");
else
client.println("Door is Closed");
client.println("<br>");
*/
// door open / close button
client.println("<button onclick=\"OnButtonClicked('1');\">Activate</button><br/>");
// add more buttons here
// button separator
//client.println("<div style=\"height:20px\"></div>");
//client.println("<button onclick=\"OnButtonClicked('2');\">Off</button>");
client.println("</div>");
client.println("</body>");
client.println("</html>");
client.println("");
}
The code specifies IPAddress ip(192,168,1,177); but in the question post you refer to the address 192.168.1.14. sS this a typo or are you just pinging the wrong address?
I am using the example ethernet sketch for a web client that comes bundled with the Arduino software without changing a thing except for the firmware address, which I changed to the one printed on the back of the ethernet shield.
Whenever I connect the Arduino to my network and view the serial monitor, the only message I get is that it "Failed to configure Ethernet using DHCP".
I have setup my Arduino Mega 2560 with an ethernet shield, correctly connecting ports 50 to MISO, 51 to MOSI, 52 to SCK, and 10 to SS (a.k.a. ETHCS as it is printed on the ethernet board).
Do you guys have any idea why this DHCP error would be happening?
Here is my code:
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x73, 0xE4 }; //ethernet mac
IPAddress server(192, 168, 1, 9); //valid server IP in my network
EthernetClient client;
void setup() {
Serial.begin(9600);
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
for(;;)
;
}
delay(1000);
Serial.println("connecting...");
if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /search?q=arduino HTTP/1.0");
client.println();
}
else {
Serial.println("connection failed");
}
}
void loop()
{
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}
}
The solution that fixed this for me was to remove the Micro SD card from the slot, I saw your issue was related to a fault but others having this issue should remove the Micro SD card after turning off the Arduino.
try this code :) it worked for me
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// this check is only needed on the Leonardo:
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
for(;;)
;
}
// print your local IP address:
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
Serial.println();
}
void loop() {
}
I've tested that code yesterday.
My last resource... get rid of the "infinite" loop and back to static IP if DHCP fails.
Could you give this code a try?
#if defined(ARDUINO) && ARDUINO > 18
#include <SPI.h>
#endif
#include <Ethernet.h>
#include <EthernetDHCP.h>
// MAC Address
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
const char* ip_to_str(const uint8_t*);
// Initialize the Ethernet server library
Server server(8080);
void setup()
{
Serial.begin(9600);
Serial.println("Attempting to obtain a DHCP lease...");
// Initiate a DHCP session. The argument is the MAC (hardware) address that
// you want your Ethernet shield to use. This call will block until a DHCP
// lease has been obtained. The request will be periodically resent until
// a lease is granted, but if there is no DHCP server on the network or if
// the server fails to respond, this call will block forever.
// Thus, you can alternatively use polling mode to check whether a DHCP
// lease has been obtained, so that you can react if the server does not
// respond (see the PollingDHCP example).
EthernetDHCP.begin(mac);
// Since we're here, it means that we now have a DHCP lease, so we print
// out some information.
const byte* ipAddr = EthernetDHCP.ipAddress();
const byte* gatewayAddr = EthernetDHCP.gatewayIpAddress();
const byte* dnsAddr = EthernetDHCP.dnsIpAddress();
Serial.println("A DHCP lease has been obtained.");
Serial.print("My IP address is ");
Serial.println(ip_to_str(ipAddr));
Serial.print("Gateway IP address is ");
Serial.println(ip_to_str(gatewayAddr));
Serial.print("DNS IP address is ");
Serial.println(ip_to_str(dnsAddr));
// Start the server
server.begin();
}
void loop()
{
// You should periodically call this method in your loop(): It will allow
// the DHCP library to maintain your DHCP lease, which means that it will
// periodically renew the lease and rebind if the lease cannot be renewed.
// Thus, unless you call this somewhere in your loop, your DHCP lease might
// expire, which you probably do not want :-)
EthernetDHCP.maintain();
// listen for incoming clients
Client client = server.available();
if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
// Some misc. HTML
client.println("<title>Arduino Control Panel</title>");
client.println("<center><h1>Control Panel</h1></center>");
client.println("<p></p>");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
client.print("Analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(analogRead(analogChannel));
client.println("<br />");
}
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}
// Just a utility function to nicely format an IP address.
const char* ip_to_str(const uint8_t* ipAddr)
{
static char buf[16];
sprintf(buf, "%d.%d.%d.%d\0", ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]);
return buf;
}
I have the same problem.
I discovered that the problem it generate with some types of switch because i have two (Encore Model ENH908-NWY Ver 3 and other IntelliNet Model 523301 Rev1).
With the switch Encore the DHCP presents problem, the Ethernet.begin(mac) return 0, but with IntelliNet the process DHCP works without problems.
I have a ADSL Huawei in my home which processes the DHCP requests.
I think that the problem it solve with a ethernet shield r3 but I have not tried that.
I post the code with it I try the DHCP requests.
When I try ethernet shield r3 I come here and tell you.
Greetings!
The property mac is previosly defined as array byte with six Hex.
void networkSetting(){
byte stateNet = 0;
//Se realiza petición DHCP para otros parámetros de Red si no están en memoria ya sea por System o Usuario
if ((EEPROM.read(userConfig) != setted) && (EEPROM.read(systemConf) != setted)) {
//Configurar el Socket solo con Mac
if (Ethernet.begin(mac) == 0){
Serial.println("DHCP not initialized! Try again...");
return;
}
//Verificamos conexión
stateNet = Ethernet.maintain();
//Ponemos bandera de parámetros de Red System seteados si cumple alguna condición
if (stateNet == 0 || stateNet == 2 || stateNet == 4)
{
//Obtenemos parámetros de Red
getNetParams();
//Guardamos parámetros de Red
saveNetParams();
//Seteamos configuración por Sistema
EEPROM.write(systemConf, setted);
} else {
//Resetear Bandera de parámetros de System (Tomará DHCP en el próximo Reinicio)
EEPROM.write(systemConf, 0);
}
} else {
//cargar parámetros de red
loadNetParams();
//Configurar el Socket con los parámetros desde la memoria
Ethernet.begin(mac, ip, gateway, gateway, subnet);
}
//Iniciar el Servidor
server.begin();
//Se envían datos de estado de Red y Port a Puerto Serial
Serial.println("Running as " + String(stateNet) + " in port " + String(port) + "!");
}
I attach captures of the two cases.
The bad test with switch Encore
The good test with switch IntelliNet
Failed to configure Ethernet using DHCP.
Ethernet.begin(mac) always returns 0.
Many people report the exact same problem.
It seems that you must connect to a router, not a switch.
If not you have to make your PC as a server
follow this link to know more--> https://www.youtube.com/watch?v=4xwwV_s9Gik
I have this web client example that gets an IP address via DHCP. It connects to my router at IP address 192.168.0.1 successfully, but then it fails to send a GET HTTP to google.com. Essentially, I cannot allow the traffic from Arduino to go out into the Internet.
I have a Linksys/Cisco E2000 router connected to the Arduino.
My code is below.
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetDHCP.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x78, 0x0B};
byte ip[] = {192, 168, 0, 125};
byte gateway[] = {192, 168, 0, 1};
byte subnet[] = {255,255,255,0};
byte serverLocal[] = { 192,168,0,1 }; // Google
byte serverExternal[] = { 173,194,33,104 }; // Google
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
Client clientLocal(serverLocal, 80);
Client clientExternal(serverExternal, 80);
const char* ip_to_str(const uint8_t*);
void setup() {
Serial.begin(9600);
Serial.println("Attempting to obtain a DHCP lease...");
// Initiate a DHCP session. The argument is the MAC (hardware) address that
// you want your Ethernet shield to use. This call will block until a DHCP
// lease has been obtained. The request will be periodically resent until
// a lease is granted, but if there is no DHCP server on the network or if
// the server fails to respond, this call will block forever.
// Thus, you can alternatively use polling mode to check whether a DHCP
// lease has been obtained, so that you can react if the server does not
// respond (see the PollingDHCP example).
EthernetDHCP.begin(mac);
// Since we're here, it means that we now have a DHCP lease, so we print
// out some information.
const byte* ipAddr = EthernetDHCP.ipAddress();
const byte* gatewayAddr = EthernetDHCP.gatewayIpAddress();
const byte* dnsAddr = EthernetDHCP.dnsIpAddress();
Serial.println("A DHCP lease has been obtained.");
Serial.print("My IP address is ");
Serial.println(ip_to_str(ipAddr));
Serial.print("Gateway IP address is ");
Serial.println(ip_to_str(gatewayAddr));
Serial.print("DNS IP address is ");
Serial.println(ip_to_str(dnsAddr));
// if you get a connection, report back via serial:
if (clientLocal.connect()) {
Serial.println("connected internally");
// Make a HTTP request:
clientLocal.println("GET /index.html HTTP/1.0");
clientLocal.println();
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed internally");
}
// if you get a connection, report back via serial:
if (clientExternal.connect()) {
Serial.println("connected externally");
// Make a HTTP request:
clientExternal.println("GET /search?q=arduino HTTP/1.0");
clientExternal.println();
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed externally");
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (clientLocal.available()) {
char c = clientLocal.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!clientLocal.connected()) {
Serial.println();
Serial.println("disconnecting.");
clientLocal.stop();
}
// if there are incoming bytes available
// from the server, read them and print them:
if (clientLocal.available()) {
char c = clientLocal.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!clientExternal.connected()) {
Serial.println();
Serial.println("disconnecting.");
clientExternal.stop();
// do nothing forevermore:
for(;;)
;
}
}
// Just a utility function to nicely format an IP address.
const char* ip_to_str(const uint8_t* ipAddr)
{
static char buf[16];
sprintf(buf, "%d.%d.%d.%d\0", ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]);
return buf;
}
Here's an example of working code (maybe you used this as a source?). The only differences I could see are the lines:
Serial.begin(9600);
delay(1000);
just before the line:
if (clientLocal.connect()) {
I doubt the additional Serial.begin() has any effect but the delay() may be required (although it's a long shot...)