Помогите с W5100 EthernetClient

VaDoSiQ
VaDoSiQ аватар
Offline
Зарегистрирован: 19.01.2017

Здравствуйте, взял стандартную библиотеку шилда W5100 EthernetClient. В общем мне нужно передавать данные каждых 30 секунд, на свой сервер, ардуинка отправляет серверу мои данные один раз(успешно), а потом намертво отказывается это делать вновь. Подскажите, как реализовать отправку данных каждых 30 секунд в этом скетче? Спасибо.

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "www.example.com";
IPAddress ip(10, 10, 1, 167);
EthernetClient client;

void setup() {
  Serial.begin(9600);
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP.");
    Ethernet.begin(mac, ip);
  }
  delay(1000);
  Serial.println("Connecting...");
  
  if (client.connect(server, 80)) {
    Serial.println("Connected.");

    client.println("GET /add.php?value=12345 HTTP/1.1");
    client.println("Host: www.example.com");
    client.println("Connection: close");
    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();
    while (true);
  }
}

 

b707
Offline
Зарегистрирован: 26.05.2017

VaDoSiQ - так чего ж удивительного, вы запихнули отправку запроса в функцию setup(). которая выполняется только один раз

DetSimen
DetSimen аватар
Offline
Зарегистрирован: 25.01.2017

можно и так оставить, но спаять на 555 таймере одновибратор, который будет раз в 30 секунд на ардуню reset подавать

sadman41
Offline
Зарегистрирован: 19.10.2016

DetSimen пишет:

можно и так оставить, но спаять на 555 таймере одновибратор, который будет раз в 30 секунд на ардуню reset подавать

Чего мелочиться, пусть дергает за ввод электричества в помещение...

nik182
Offline
Зарегистрирован: 04.05.2015

А не проще раз в 30 секунд setup вызывать? Ведь пока ни кто не запретил кажется?

sadman41
Offline
Зарегистрирован: 19.10.2016

Из лупа сетап вызывать? Тоже неплохая идея.

vitalikost
Offline
Зарегистрирован: 28.11.2014
  

//проверяем не прошел ли нужный интервал, если прошел то
  if(currentMillis - previousMillis > interval) {
    // сохраняем время последнего переключения
    previousMillis = currentMillis; 
 
     
      // if you get a connection, report back via serial:
      if (client.connect(server, 3000)) {
        Serial.println("connected");
        // Make a HTTP request:
        client.println("GET /add.php?value=12345" HTTP/1.1");
    //    client.println("Host: 192.168.5.33");
        client.println("Connection: close");
        client.println();
      } 
      else {
        // kf you didn't get a connection to the server:
        Serial.println("connection failed");
      }


  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println("Stop Disconect");
    client.stop();

 
  } 
  

 

vitalikost
Offline
Зарегистрирован: 28.11.2014

Вот циляком, данные с dht11

 

/*
  Web client
 
 This sketch connects to a website (http://www.google.com)
 using an Arduino Wiznet Ethernet shield. 
 
 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 
 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe, based on work by Adrian McEwen
 
 */

#include <SPI.h>
//#include <Ethernet.h>
#include <UIPEthernet.h>//enc28j60

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "192.168.5.33";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,5,50);

// 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;

#include "DHT.h"

#define DHTPIN 35     // what pin we're connected to

// Uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11 
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

DHT dht(DHTPIN, DHTTYPE);

long previousMillis = 0;        // храним время последнего переключения светодиода
 
long interval = 60000*5; //


#include <Wire.h>
#include <Adafruit_BMP085.h>
Adafruit_BMP085 bmp;

void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  
  dht.begin();
  bmp.begin();
  // 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:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  Serial.println(Ethernet.localIP());  
  
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");
  
  float h = dht.readHumidity();
 // float t = dht.readTemperature();
  float t = bmp.readTemperature();
  char chartemp1[10],chartemp2[10];
  dtostrf(t, 5, 2, chartemp1);
  dtostrf(h, 5, 2, chartemp2);
  String srt1(chartemp1);
  String srt2(chartemp2);
  
  // if you get a connection, report back via serial:
  if (client.connect(server, 3000)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /add?t="+srt1+"&h="+srt2+ " HTTP/1.1");
    client.println("Host: 192.168.5.33");
    client.println("Connection: close");
    client.println();
  } 
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available 
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }



  // здесь будет код, который будет работать постоянно
  // и который не должен останавливаться на время между переключениями свето
  unsigned long currentMillis = millis();
  
  //проверяем не прошел ли нужный интервал, если прошел то
  if(currentMillis - previousMillis > interval) {
    // сохраняем время последнего переключения
    previousMillis = currentMillis; 
 
    // если светодиод не горит, то зажигаем, и наоборот

      float h = dht.readHumidity();
//      float t = dht.readTemperature();
      float t = bmp.readTemperature();
      char chartemp1[10],chartemp2[10];
      dtostrf(t, 5, 2, chartemp1);
      dtostrf(h, 5, 2, chartemp2);
      String srt1(chartemp1);
      String srt2(chartemp2);
      
      // if you get a connection, report back via serial:
      if (client.connect(server, 3000)) {
        Serial.println("connected");
        // Make a HTTP request:
        client.println("GET /add?t="+srt1+"&h="+srt2+ " HTTP/1.1");
        client.println("Host: 192.168.5.33");
        client.println("Connection: close");
        client.println();
      } 
      else {
        // kf you didn't get a connection to the server:
        Serial.println("connection failed");
      }


  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println("Stop Disconect");
    client.stop();

 
  } 
  
}