Веб-сервер Arduino Datalogger не может подключиться к клиенту

У меня есть Arduino mega с экраном Ethernet + SD-карта, на котором работает регистратор данных датчика с датчиком DHT22, записывающим данные датчика на SD-карту. Я пытаюсь реализовать веб-сервер для чтения этих данных с SD-карты. Я сделал программу, используя примеры Arduino, но она не может подключиться к клиенту. Я проверил IP-адрес своего компьютера, к которому подключен Ethernet-шилд: 192.168.0.107. Часть регистратора данных программы работает отлично, и даже с реализованным веб-сервером код не выдает ошибок при компиляции или отправке файла в arduino.

Основная проблема в том, что программа никогда не заходит в ИФ (клиент) потому что есть? нет клиента.

Вот код:

#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp.h>
#include <SD.h>
#include <DHT.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,0,107);
//IPAddress dns1(192,168,0,1);
//IPAddress gateway(192,168,0,1);
//IPAddress subnet(255,255,255,0);
EthernetServer server(80);

#define DHTPIN 7     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)

DHT dht(DHTPIN, DHTTYPE);

const int chipSelect = 4;

void setup() {
  // put your setup code here, to run once:
    dht.begin();
    Ethernet.begin(mac, ip);
    server.begin();
    Serial.begin(9600);
    digitalWrite(10, HIGH);

    Serial.print("server is at ");
    Serial.println(Ethernet.localIP());


    Serial.print("Initializing SD card...");
    if (!SD.begin(chipSelect)) {
      Serial.println("Card failed, or not present");
      return;
    }
       Serial.println("card initialized.");
       Serial.println("DHT22 Logging sensor data:!"); 
}

void loop() {
  // put your main code here, to run repeatedly:
  // Wait beetween reading sensors
  delay(4444);
  //Reading sensor data
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  float f = dht.readTemperature();

   // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

// Compute heat index
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(t, h);

  File dataFile = SD.open("datalog.CSV", FILE_WRITE);
  //writing sensor data to sd card
  if (dataFile) {

      dataFile.print((float)f);
      dataFile.print(" , ");
      dataFile.println((float)h);
      dataFile.close();
      // print to the serial port too:
      Serial.print("Temperature = ");
      Serial.println(f);
      Serial.print("Humidity = ");
      Serial.println(h);
    } 
    // if the file isn't open, pop up an error:
    else {
      Serial.println("error opening datalog.CSV");
    }

EthernetClient client = server.available();
  if (client) {
    Serial.println("client availble");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        Serial.println("connected");
        char c = client.read(); // Client data readed
        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();
          client.println("<br />");
          client.print("Arduino powered webserver");
          client.println("<br />");
          client.print("Serving temperature and humidity values from a DHT22 sensor");
          client.println("<br />");
          client.print(f);
          client.println("<br />");
          client.print("Humidity (%): ");
          client.print(h);       
          client.println("<br />");
          Serial.println("kikkihiiri");
          break;
        }

        if (c == '\n') {
          // last character on line received
          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(5);
    // close the connection:
    client.stop();
    Serial.println("Client disconnected");
  }


}

Я довольно новичок в этом деле, поэтому любая помощь будет принята с благодарностью!


person Jussi    schedule 13.03.2016    source источник


Ответы (1)


Удалите эту строку из setup:

digitalWrite(10, HIGH);

Вы делаете это после того, как Ethernet начал управлять этим выводом для интерфейса SPI (совместно с SD).

Кроме того, я думаю, что я бы предложил переместить Serial.begin выше, но, вероятно, там все в порядке.

person slash-dev    schedule 13.03.2016