The program is supposed to send Temperature and IR sensor data to Thingspeak. So the first few commands work smoothly and sends the data quickly and it appears on the website, but somewhere along the middle it just stop and the same error appears along the next few loops:
- at command => AT+CIPMUX=1 OYI
- at command => AT+CIPSTART=0,"TCP","api.thingspeak.com",80 OYI
- at command => AT+CIPSEND=0,59 Fail
- at command => AT+CIPCLOSE=0 Fail
Once in 5 loop the connection is successful without any lags, and then the same issue persists. Below is the code. (I worry if it has anything to do with the delay ms):
#include <SimpleDHT.h>
#include <SoftwareSerial.h>
#define RX 2
#define TX 3
// for DHT11,
// VCC: 5V or 3V
// GND: GND
// DATA: 8
int pinDHT11 = 8;
SimpleDHT11 dht11(pinDHT11);
// for IR Sensor
int irPin=7;
int count=0;
boolean state = true;
String AP = "wifiname"; // AP NAME
String PASS = "password"; // AP PASSWORD
String API = "API KEY"; // Write API KEY
String HOST = "api.thingspeak.com";
String PORT = "80";
String field1 = "field1";
String field2 = "field2";
int countTrueCommand;
int countTimeCommand;
boolean found = false;
int valDHTSensor = 1;
SoftwareSerial esp8266(RX,TX);
void setup() {
Serial.begin(9600);
pinMode(irPin, INPUT); //IR Pin
esp8266.begin(115200);
sendCommand("AT",5,"OK");
sendCommand("AT+CWMODE=1",5,"OK");
sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");
}
void loop() {
valDHTSensor = getSensorData();
if (!digitalRead(irPin) && state){
count++;
state = false;
Serial.println(count);
}
if (digitalRead(irPin)){
state = true;
delay(1500);
}
Serial.print("count: " );
Serial.println(count);
String getData = "GET /update?api_key="+ API +"&"+ field1 +"="+String(valDHTSensor)+"&"+ field2 +"="+String(count);
sendCommand("AT+CIPMUX=1",5,"OK");
sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");
esp8266.println(getData);delay(20000);countTrueCommand++;
sendCommand("AT+CIPCLOSE=0",5,"OK");
}
int getSensorData(){
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
dht11.read(&temperature, &humidity, NULL);
Serial.print("Temperature: ");
Serial.println(temperature);
return int(temperature);
}
void sendCommand(String command, int maxTime, char readReplay[]) {
Serial.print(countTrueCommand);
Serial.print(". at command => ");
Serial.print(command);
Serial.print(" ");
while(countTimeCommand < (maxTime*1))
{
esp8266.println(command);//at+cipsend
if(esp8266.find(readReplay))//ok
{
found = true;
break;
}
countTimeCommand++;
}
if(found == true)
{
Serial.println("OYI");
countTrueCommand++;
countTimeCommand = 0;
}
if(found == false)
{
Serial.println("Fail");
countTrueCommand = 0;
countTimeCommand = 0;
}
found = false;
}