D
D
DVoropaev2017-07-26 12:28:31
Arduino
DVoropaev, 2017-07-26 12:28:31

How to set up ethernet on arduino so that it can be used as a client?

The example is taken from here.
Here is the code itself:

#include <UIPEthernet.h>
#include <ethernet_comp.h>
#include <UIPClient.h>
#include <Dhcp.h>
#include <Dns.h>
#include <UIPUdp.h>


byte mac[] = {  0x94, 0xDE, 0x80, 0x3A, 0x90, 0xC9 }; //MAC-адрес Arduino
const unsigned long postingInterval = 600000;  // интервал между отправками
                                               // данных - 10 минут
// IP-адрес, назначаемый Ethernet shield:
byte ip[] = { 192, 168, 43, 230 };   
// IP-адрес, dns сервера:
byte sdns[] = { 192, 168, 43, 1 };   
// адрес шлюза:
byte gateway[] = { 192, 168, 43, 1 };
// маска:
byte subnet[] = { 255, 255, 255, 0 };
 
IPAddress server(94,19,113,221); // IP сервера
//IPAddress server(91,122,49,168); // IP сервера
EthernetClient client;
unsigned long lastConnectionTime = 0;   // время последней передачи данных
boolean lastConnected = false;          // состояние подключения
char replyBuffer[160];
 
void setup()
  {
  Serial.begin(9600);
  // Ethernet connection:
  Ethernet.begin(mac,ip,sdns,gateway,subnet);
  // секунда для инициализации Ethernet
  delay(1000);
  //первое соединение через 15 секунд после запуска
  lastConnectionTime = millis()-postingInterval+15000;
}
 
void loop()
  {
  //если не подключены, и прошло определенное время, то делаем замер,
  //переподключаемся и отправляем данные
  if (!client.connected() && (millis() - lastConnectionTime > postingInterval))
    {
    //формирование HTTP-запроса
    memset(replyBuffer, 0, sizeof(replyBuffer));
    strcpy(replyBuffer,"ID=");
    //Конвертируем MAC-адрес
    for (int k=0; k<6; k++)
      {
      int b1=mac[k]/16;
      int b2=mac[k]%16;
      char c1[2],c2[2];
 
      if (b1>9) c1[0]=(char)(b1-10)+'A';
      else c1[0] = (char)(b1) + '0';
      if (b2>9) c2[0]=(char)(b2-10)+'A';
      else c2[0] = (char)(b2) + '0';
 
      c1[1]='\0';
      c2[1]='\0';
 
      strcat(replyBuffer,c1);
      strcat(replyBuffer,c2);
      }
   strcat(replyBuffer,"&");
   strcat(replyBuffer,"3351C4BA0200003B");
   strcat(replyBuffer,"=");
   char temp[3];
   double tmpd=(analogRead(A0)*5.0/1024)*100-273.15;
   int tmpi=int(tmpd);
   itos(tmpi,temp);
   strcat(replyBuffer,temp);
   strcat(replyBuffer,'\0');
   //отправляем запрос
   httpRequest();
   }
  //храним последнее состояние подключения
  lastConnected = client.connected();
  }
// функция отправки запроса
void httpRequest() {
  if (client.connect(server, 80))
    {
    // send the HTTP POST request:
    client.println("POST http://narodmon.ru/post.php HTTP/1.0");
    client.println("Host: narodmon.ru");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(len(replyBuffer));
    client.println();
    client.println(replyBuffer);
    client.println();
    lastConnectionTime = millis();
    }
  else
    {
    client.stop();
    }
  }
 
// размер данных
int len(char *buf)
{
  int i=0;
  do
    {
    i++;
    } while (buf[i]!='\0');
  return i;
}
// функция int to string
void itos(int n, char bufp[3]) //
{
  char buf[3]={'0','0','\0'};
  int i = 1;
  while (n > 0)
    {
    buf[i] = (n % 10)+48;
    i--;
    n /= 10;
    }
  for (i=0; i<3; i++)
    bufp[i]=buf[i];
  }

Board - Arduino Mega, Arduino Uno (tried on both)
as an adapter - enc28j60
20130814093820798.JPG
dhcp is enabled on the router.
When you turn on the arduino, the green indicator on the adapter (on the ehternet port itself) lights up for a few seconds, then goes out for half a second, then the yellow indicator lights up briefly, then everything goes out, and nothing happens.
The ip addresses in the sketch are written in accordance with the network address, network mask, and router address. No new devices appear in the admin panel of the router.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vanyamba-electronics, 2017-08-02
@vanyamba-electronics

When DHCP is enabled, the address is assigned to the client by the router upon connection. And in this case, it is initialized with the static address 192.168.43.230.
See how the ENC28J60 is initialized in the following sketch .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question