Синхронизация времени Arduino через интернет.
Добавлено: Пт апр 29, 2016 08:35:40
Подскажите, пожалуйста...
Хочу синхронизировать время модуля часов реального времени RTC DS1302, подключенного к Arduino с Ethernet-шилдом, который, в свою очередь, подключен к роутер с выходом в интернет. Решение вижу в отправке GET-запроса к любому сайту, например к http://www.google.com и парсинга ответа.
Есть скетч, который отправляет GET-запрос и выводит ответ в последовательный порт:
Но не все так просто. Судя по скетчу, Arduino с Ethernet-шилдом настраиваются как Client, для того чтобы выполнить обращение к сайту. А мне нужно, чтобы после выполнения запроса и парсинга ответа, Arduino с Ethernet-шилдом становились Server-ом. Подскажите, пожалуйста, как это сделать?
Полный код:
Хочу синхронизировать время модуля часов реального времени RTC DS1302, подключенного к Arduino с Ethernet-шилдом, который, в свою очередь, подключен к роутер с выходом в интернет. Решение вижу в отправке GET-запроса к любому сайту, например к http://www.google.com и парсинга ответа.
Есть скетч, который отправляет GET-запрос и выводит ответ в последовательный порт:
Спойлер
Код: Выделить всё
/*
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>
// 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[] = "www.mail.ru"; // name address for Google (using DNS)
// Set the static IP address to use if the DHCP fails to assign
//IPAddress ip(192, 168, 1, 33);
// 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:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac/*, ip*/);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET /search?q=arduino HTTP/1.1");
client.println("Host: www.mail.ru");
client.println("Connection: close");
client.println();
} else {
// if 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);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
while (true);
}
}
Но не все так просто. Судя по скетчу, Arduino с Ethernet-шилдом настраиваются как Client, для того чтобы выполнить обращение к сайту. А мне нужно, чтобы после выполнения запроса и парсинга ответа, Arduino с Ethernet-шилдом становились Server-ом. Подскажите, пожалуйста, как это сделать?
Полный код:
Спойлер
Код: Выделить всё
#include <SD.h>
#include <RTC.h>
#include <SPI.h>
#include <Ethernet.h>
// =====
RTC time;
File myFile;
boolean MARKER_PWM = false;
char DATA_PWM[4];
char i;
// =====
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
char serv[] = "www.mail.ru"; // name address for Google (using DNS)
EthernetClient client;
EthernetServer server(8888);
// ===========
void setup()
{
// =====
Serial.begin(9600);
// ========
while (!Serial)
{
; // wait for serial port to connect. Needed for native USB port only
}
// ========
Serial.print("Initializing SD card...");
pinMode(4, OUTPUT);
if (!SD.begin(4))
{
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// =====
delay(1000);
if (Ethernet.begin(mac) == 0)
{
Serial.println("Failed to configure Ethernet using DHCP");
for(;;);
}
Serial.println(Ethernet.localIP());
server.begin();
pinMode(5, OUTPUT);
// =====
delay(300);
time.begin(RTC_DS1302,2,5,3); // 10-2, 12-3,13-5
//time.settime(0,42,14,26,4,16,2); // сек, мин, час, число, месяц, год, день недели*/
// =====
pinMode(11, OUTPUT);
// =====
delay(1000);
Serial.println("connecting...");
if (client.connect(serv, 80))
{
Serial.println("connected");
client.println("GET /search?q=arduino HTTP/1.1");
client.println("Host: www.mail.ru");
client.println("Connection: close");
client.println();
}
else
{
Serial.println("connection failed");
}
// =====
}
// ===========
void loop()
{
// =============
if (client.available())
while (client.connected())
{
if (client.available())
{
char c = client.read();
Serial.print(c);
if (!client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
while (true);
}
}
}
// =============
EthernetClient client = server.available();
if (client)
{//Serial.println("new client");
while (client.connected())
{
if (client.available())
{
char c = client.read();
// =========
if (c == '[')
{
memset (DATA_PWM,' ',4);
MARKER_PWM = true;
i = 0;
return;
}
// =========
if ((MARKER_PWM == true) && (i < 5) && (c != ']'))
{
DATA_PWM[i] = c;
i = i + 1;
}
// =========
if ((MARKER_PWM == true) && (i >= 5))
{
memset (DATA_PWM, ' ', 4);
i = 0;
}
// =========
if (c == ']')
{
MARKER_PWM = false;
i = 0;
Serial.println(DATA_PWM);
client.println(DATA_PWM);
analogWrite(11, atoi(DATA_PWM));
myFile = SD.open("DATALOG.txt", FILE_WRITE);
if (myFile)
{
Serial.print("Writing to log file...");
myFile.print(time.gettime("d-m-Y, H:i:s, D")); // выводим время
myFile.print(" : Change PWM value to: "); // выводим время
myFile.println(DATA_PWM);
myFile.close();
Serial.println("done.");
}
else
{
Serial.println("error opening log file");
}
}
// =========
}
}
}
}
// ===========
/*
*/