WebClient. Не создается соединение

AlexB
Offline
Зарегистрирован: 01.12.2015

Привет всем. 

В програмировании я начинающий, немного обо всем.

Планировалось использовать arduino ethernet как WebClient локального сервера, созданного с помощью denver. C ардуино поступают значения некоторой переменной, которые записываются в файл ard.txt; а с сервера - управление диодом: вкл - 1 в вайле data.txt; выкл - 0.

Сосбвенно проблема: Не создается Eternet соединение. 

скетч:

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

byte mac[] = { 0xDF, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

//IPAddress server(127,0,0,1);  // numeric IP for Google (no DNS)
char server[] = "www.test1.ru";    // name address for Google (using DNS)

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

// 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:
  //Ethernet.begin(mac);
  Serial.begin(9600);
  pinMode(9, OUTPUT);
  digitalWrite(9, LOW);
  while (!Serial){}
  if (Ethernet.begin(mac)==0) {
  Serial.println("Failed to configure Ethernet using DHCP");  
  Ethernet.begin(mac, ip);
  // give the Ethernet shield a second to initialize:
 delay (1000);

  // if you get a connection, report back via serial:
//Serial.print("My IP address: ");
//  Serial.println(Ethernet.localIP());
Serial.println("connecting...");}
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
 // Serial.println("connecting...");
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /?temp=2 HTTP/1.1");
    client.println("Host: www.test1.ru");
    client.println("Connection: close");
    client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
    
   if (c == '0') { digitalWrite(9, LOW); } 
   if (c == '1') { digitalWrite(9, HIGH); }

  }

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

Сервер: 

<?php
$TheFile2 = "ard.txt";
$Date = date("Y-m-d H:i:s");   //считываем дату и время с сервера
$Open = fopen ($TheFile2, "a") or die("can't open file");
$S1 =  $_GET['temp'];
fwrite ($Open, "$Date\t$S1\n");
fclose($Open);
$myFile = "data.txt";
$fh = fopen($myFile, 'r') or die("can't open file");
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
		
?>

 

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

А чего говорит-то? "connection failed"? из 52 строки? Или другое чего?

AlexB
Offline
Зарегистрирован: 01.12.2015

Как проверить что говорит? 

Соединение идет через Eternet 

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

У Вас в программе стоит куча Serial.print'ов. Что выводит в Serial? Вы смотрите?

inspiritus
Offline
Зарегистрирован: 17.12.2012

Почитайте мои экзарсисы тут, может пригодиться. Там тоже клиент не поднимал подключение.

AlexB
Offline
Зарегистрирован: 01.12.2015

Выводил :

Failed to configure Ethernet using DHCP

connecting...

connection failld

Расшарил wi-fi соединение - появилось соединение (выводил connected), но программа не работала: данные не писались в файл, управление светодиодом не работало. 

Но через пол часа этот же код перестал  подключаться к сайту: подключается 1-раз, потом connection failld.

Совсем сбивает с толку то, что пол часа соединение проходило без проблем

AlexB
Offline
Зарегистрирован: 01.12.2015

inspiritus, как именно держать SD CS на единице? Просто выводим единицу на 4 (в моем случае) пин?

Jeka_M
Jeka_M аватар
Offline
Зарегистрирован: 06.07.2014

digitalWrite();

Единица - высокий логический ровень (HIGH). Ноль - низкий логический уровень (LOW).

AlexB
Offline
Зарегистрирован: 01.12.2015

Основная ошибка - это то, что нужно сделать сайт доступным для локальной сети. Здесь подробно про это: http://www.denwer.ru/faq/shared.html

Работающий скетч:

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

byte mac[] = {0x54, 0x34, 0x41, 0x30, 0x30, 0x31 };
EthernetClient client;
IPAddress server (*,*,*,*);    // ip вашего компьютера, а за одно и сервера
byte ip[] = {192, 168, 0, 2 };        // ip адрес ethernet shielda

void setup() {
  Serial.begin(9600);
  pinMode(9, OUTPUT);
  digitalWrite(9, LOW);
  while (!Serial){}
  if (Ethernet.begin(mac)==0) {
  Serial.println("Failed to configure Ethernet using DHCP");  
  Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
 delay (1000);
 Serial.println(Ethernet.localIP());
}
void loop()
{
  int r3=random(20);
  String r34=String(r3); //перевод числа в строку
  Serial.println("connecting...");
  if (client.connect (server, 80)) {
    Serial.println("connected");
    Serial.println(r34);
    // Make a HTTP request:
   client.print("GET /?temp=");
   client.println(r34);
   client.println(" HTTP/1.1"); 
   // client.println("GET /?temp=2 HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("Connection: close");
    client.println();
    client.println(); 
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
 delay(50);
 while  (client.available()) {
    char c = client.read();
    Serial.print(c);
    if (c == '0') { digitalWrite(9, LOW); } 
   if (c == '1') { digitalWrite(9, HIGH); }
  }

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

Сервер остался без изменений