WebClient. Не создается соединение
- Войдите на сайт для отправки комментариев
Втр, 01/12/2015 - 15:12
Привет всем.
В програмировании я начинающий, немного обо всем.
Планировалось использовать 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; ?>
А чего говорит-то? "connection failed"? из 52 строки? Или другое чего?
Как проверить что говорит?
Соединение идет через Eternet
У Вас в программе стоит куча
Serial
.print
'ов. Что выводит в Serial? Вы смотрите?Почитайте мои экзарсисы тут, может пригодиться. Там тоже клиент не поднимал подключение.
Выводил :
Failed to configure Ethernet using DHCP
connecting...
connection failld
Расшарил wi-fi соединение - появилось соединение (выводил connected), но программа не работала: данные не писались в файл, управление светодиодом не работало.
Но через пол часа этот же код перестал подключаться к сайту: подключается 1-раз, потом connection failld.
Совсем сбивает с толку то, что пол часа соединение проходило без проблем
inspiritus, как именно держать SD CS на единице? Просто выводим единицу на 4 (в моем случае) пин?
digitalWrite();
Единица - высокий логический ровень (HIGH). Ноль - низкий логический уровень (LOW).
Основная ошибка - это то, что нужно сделать сайт доступным для локальной сети. Здесь подробно про это: http://www.denwer.ru/faq/shared.html
Работающий скетч:
Сервер остался без изменений