我的初始项目是调用一个Web服务,它将使用Arduino Uno和ESP8266向我发送JSON响应。根据响应,它将激活或停用电磁阀。
但是我正在努力从服务器接收答案。因此,我使用的URL将发送JSON响应:http://jsonplaceholder.typicode.com/posts/1
这是我正在使用的架构:
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial ESP8266(10, 11);
String NomduReseauWifi = "wifiname";
String MotDePasse = "password";
String cmd;
String server = "jsonplaceholder.typicode.com";
String uri = "/posts/1";
/***********************************/
/* INIT */
/*********************************/
void setup() {
Serial.begin(115200);
ESP8266.begin(115200);
Serial.println();
//Clear some garbage that may be printed to the serial console
reset();
connectWifi();
httppost();
}
/******************************/
/* LOOP */
/*****************************/
void loop() {
while (Serial.available()) // forward data from monitor to esp
ESP8266.write(Serial.read());
while (ESP8266.available()) // forward data from esp to monitor
Serial.write(ESP8266.read());
delay(1000);
}
/*********************************/
/* ESP8266 INITIALIZATION */
/*******************************/
void reset() {
Serial.println("RESETING!");
ESP8266.println("AT+RST");
delay(1000);
if (ESP8266.find("OK") ) Serial.println("Module Reset");
}
/***************************************/
/* WIFI INITIALIZATION */
/**************************************/
void connectWifi() {
Serial.println("************************Connection***************************");
String cmd = "AT+CWJAP=\"" + NomduReseauWifi + "\",\"" + MotDePasse + "\"";
ESP8266.println(cmd);
delay(3000);
if (ESP8266.find("OK")) {
Serial.println("Connected!");
} else {
connectWifi();
Serial.println("Cannot connect to wifi");
}
}
/*************************************************/
/* CALL THE URL AND TRY TO SHOW THE ANSWER */
/************************************************/
void httppost() {
ESP8266.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");
//start a TCP connection.
delay(500);
if ( ESP8266.find("OK")) {
Serial.println("TCP connection ready");
}
delay(3000);
cmd = "GET /posts/1\r\n";
cmd += "Host: jsonplaceholder.typicode.com\r\n\r\n";
String sendCmd = "AT+CIPSEND=";
//determine the number of caracters to be sent.
ESP8266.print(sendCmd);
Serial.println(cmd.length());
ESP8266.println(52);
delay(200);
StaticJsonBuffer<200> jsonBuffer;
if (ESP8266.find(">")) {
Serial.println("Sending..");
ESP8266.print(cmd);
if (ESP8266.find("SEND OK")) {
Serial.println("Packet sent");
while (ESP8266.available() > 0) {
//Serial.println(ESP8266.read());
String line = ESP8266.readStringUntil('\r');
JsonObject& root = jsonBuffer.parseObject(line);
//Serial.println(line);
if (!root.success()) {
Serial.println("parseObject() failed");
return;
} else {
Serial.println("result: ");
Serial.println((const char*)root["title"]);
}
}
}
// close the connection
ESP8266.println("AT+CIPCLOSE");
}
}
我想做的是什么?
谢谢。