esp01 не может получить запрос на получение от приложения Android для включения / выключения светодиода, также код ответа является нулевым, даже если запрос отправлен. При повторном подключении системы Arduino все предыдущие неудачные запросы отображаются мгновенно на последовательном мониторе. Раньше он работал правильно, но раньше также была задержка. Я прилагаю код Arduino и Android ниже. Пожалуйста, помогите.
Код Arduino -
#include <SoftwareSerial.h>
#define DEBUG true
int led =11;
int ldr = A0;
int threshold=300;
int connectionId;
boolean iotLogic = true;
SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
// This means that you need to connect the TX line from the esp to the Arduino's pin 2
// and the RX line from the esp to the Arduino's pin 3
void setup()
{
Serial.begin(115200);
esp8266.begin(115200); // your esp's baud rate might be different
pinMode(led,OUTPUT);
digitalWrite(led,LOW);
sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
sendCommand("AT+CWMODE=3\r\n",2000,DEBUG); // configure as access point
sendCommand("AT+CWJAP=\"PKS\",\"91101132\"\r\n",2000,DEBUG);
delay(3000);
sendCommand("AT+CIFSR\r\n",2000,DEBUG); // get ip address
sendCommand("AT+CIPMUX=1\r\n",2000,DEBUG); // configure for multiple connections
sendCommand("AT+CIPSERVER=1,80\r\n",2000,DEBUG); // turn on server on port 80
Serial.println("Server Ready");
}
void loop()
{
int sensorval=analogRead(ldr);
if(esp8266.available()) // check if the esp is sending a message
{
if(esp8266.find("+IPD,"))
{
delay(1000); // wait for the serial buffer to fill up (read all the serial data)
// get the connection id so that we can then disconnect
connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
// the ASCII decimal value and 0 (the first decimal number) starts at 48
if(esp8266.find("IOT=")){// advance cursor to "pin="
int iot= esp8266.read()-48;
Serial.println(iot);
if(iot==1){
iotLogic=true;
}
else if(iot==0){
iotLogic=false;
}
}
if(iotLogic){
if(sensorval>threshold){
digitalWrite(led,LOW);
}
else{
digitalWrite(led,HIGH);
}
}
else{
esp8266.find("pin=");
int val=esp8266.read()-48;
Serial.println(val);
if(val==1){
digitalWrite(led,HIGH);
}
else{
digitalWrite(led,LOW);
}
}
// build string that is send back to device that is requesting pin toggle
String content;
content = "Pin ";
content += led;
content += " is ";
if(digitalRead(led))
{
content += "ON";
}
else
{
content += "OFF";
}
sendHTTPResponse(connectionId,content);
// make close command
String closeCommand = "AT+CIPCLOSE=";
closeCommand+=connectionId; // append connection id
closeCommand+="\r\n";
sendCommand(closeCommand,1000,DEBUG); // close connection
}
}
}
/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
String response = "";
int dataSize = command.length();
char data[dataSize];
command.toCharArray(data,dataSize);
esp8266.write(data,dataSize); // send the read character to the esp8266
if(debug)
{
Serial.println("\r\n====== HTTP Response From Arduino ======");
Serial.write(data,dataSize);
Serial.println("\r\n========================================");
}
long int time = millis();
while( (time+timeout) > millis())
{
while(esp8266.available())
{
// The esp has data so display its output to the serial window
char c = esp8266.read(); // read the next character.
response+=c;
}
}
if(debug)
{
Serial.println(response);
}
return response;
}
/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{
// build HTTP response
String httpResponse;
String httpHeader;
// HTTP Header
httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
httpHeader += "Content-Length: ";
httpHeader += content.length();
httpHeader += "\r\n";
httpHeader +="Connection: keep-alive\r\n\r\n";
httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
sendCIPData(connectionId,httpResponse);
}
/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(int connectionId, String data)
{
String cipSend = "AT+CIPSEND=";
cipSend += connectionId;
cipSend += ",";
cipSend +=data.length();
cipSend +="\r\n";
sendCommand(cipSend,1000,DEBUG);
sendData(data,1000,DEBUG);
}
/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
String response = "";
esp8266.print(command); // send the read character to the esp8266
long int time = millis();
while( (time+timeout) > millis())
{
while(esp8266.available())
{
// The esp has data so display its output to the serial window
char c = esp8266.read(); // read the next character.
response+=c;
}
}
if(debug)
{
Serial.print(response);
}
return response;
}
Код Android
package com.example.asjuh.automatedsystem;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class MainActivity extends Activity implements View.OnClickListener {
public final static String PREF_IP = "PREF_IP_ADDRESS";
public final static String PREF_PORT = "PREF_PORT_NUMBER";
// declare buttons and text inputs
private ToggleButton buttonPin2;
private Switch IOTbutton;
private EditText editTextIPAddress, editTextPortNumber;
// shared preferences objects used to save the IP address and port so that the user doesn't have to
// type them next time he/she opens the app.
SharedPreferences.Editor editor;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("HTTP_HELPER_PREFS", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
// assign buttons
IOTbutton = (Switch)findViewById(R.id.switch1);
buttonPin2 = (ToggleButton)findViewById(R.id.toggleButton2);
// assign text inputs
editTextIPAddress = (EditText)findViewById(R.id.editTextIPAddress);
editTextPortNumber = (EditText)findViewById(R.id.editTextPortNumber);
// set button listener (this class)
buttonPin2.setOnClickListener(this);
IOTbutton.setOnClickListener(this);
// get the IP address and port number from the last time the user used the app,
// put an empty string "" is this is the first time.
editTextIPAddress.setText(sharedPreferences.getString(PREF_IP,""));
editTextPortNumber.setText(sharedPreferences.getString(PREF_PORT,""));
}
@Override
public void onClick(View view) {
// get the pin number
String parameterValue = "";
String parameter="";
// get the ip address
String ipAddress = editTextIPAddress.getText().toString().trim();
// get the port number
String portNumber = editTextPortNumber.getText().toString().trim();
// save the IP address and port for the next time the app is used
editor.putString(PREF_IP, ipAddress); // set the ip address value to save
editor.putString(PREF_PORT, portNumber); // set the port number to save
editor.commit(); // save the IP and PORT
// get the pin number from the button that was clicked
if(view.getId()==IOTbutton.getId()){
parameter="IOT";
if(IOTbutton.getText().equals("ON")){
parameterValue="1";
}
else{
parameterValue="0";
}
}
else if(view.getId() == buttonPin2.getId()) {
parameter="pin";
if(buttonPin2.getText().equals("ON")){
parameterValue="1";
}
else{
parameterValue="0";
}
}
if(ipAddress.length()>0 && portNumber.length()>0) {
HttpGetRequest htp= new HttpGetRequest(this);
htp.execute("http://"+ipAddress+":"+portNumber+"/?"+parameter+"="+parameterValue);
}
}
public class HttpGetRequest extends AsyncTask<String,Void,String>{
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 30000;
public static final int CONNECTION_TIMEOUT = 30000;
private Context mContext;
String result;
public HttpGetRequest(Context context) {
//Relevant Context should be provided to newly created components (whether application context or activity context)
//getApplicationContext() - Returns the context for all activities running in application
mContext = context.getApplicationContext();
}
@Override
protected String doInBackground(String... params) {
String stringUrl = params[0];
try {
URL myUrl = new URL(stringUrl);
//Create a connection
HttpURLConnection connection =(HttpURLConnection)
myUrl.openConnection();
//Set methods and timeouts
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setDoInput(true);
connection.setDoOutput(true);
//Connect to our url
connection.connect();
//Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
//Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
//Check if the line we are reading is not null
String inputLine;
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
//Set our result equal to our stringBuilder
result = stringBuilder.toString();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String r) {
//Print the response code as toast popup
Toast.makeText(mContext, "Response code: " + r,
Toast.LENGTH_SHORT).show();
}
@Override
protected void onPreExecute() {
Toast.makeText(mContext, "Going for the network call..", Toast.LENGTH_SHORT).show();
}
}
}