Hello, could you please help me set up communication for HC-12 and ESP01 together on Arduino UNO?
My goal is to receive a message from HC-12 and send it to Thinspeak. I have the wiring correctly. The code below works for both receiving news from the HC-12 and sending a message to ThinkSpeak, but they do not work together.
ESP even initializes and connects to the wifi, then the HC-12 receives the message, but ESP can no longer send the message to the web. When I comment out the HC12.begin () line, sending to ThinkSpeak works without problems.
I read that the SoftwareSerial Library can work for multiple software serial ports, but only one can receive data at a time. So should I stop receiving HC-12 or ESP? How?
Thank you for your help.
#include <SoftwareSerial.h>
String MsgBuf = "";
unsigned long millisThinkSpeak = 0;
// HC-12
SoftwareSerial HC12(3, 2);
#define pinSet 4
// ESP8266
SoftwareSerial SerialESP(8,9);
int countTimeCommand;
boolean found = false;
void setup() {
Serial.begin(9600);
//Begin ESP8266
SerialESP.begin(115200);
sendATtoESP("AT",5,"OK");
sendATtoESP("AT+CWMODE=1",5,"OK");
sendATtoESP("AT+CWJAP=\"XXXXXXXXXX\",\"XXXXXXXXXX\"",20,"OK");
//Begin HC-12
pinMode(pinSet, OUTPUT);
digitalWrite(pinSet, HIGH);
delay(100);
HC12.begin(9600);
}
void loop(){
unsigned long millisTime=millis();
//HC-12
while (HC12.available()) {
char MsgChar = HC12.read(); // read every byte
MsgBuf += char(MsgChar); // byte to buffer
if (MsgChar == '\n') { //if end of message do..
Serial.println(MsgBuf);
//decode Msg and save to variable
MsgBuf = "";
}
}
//ESP - ThinkSpeak every minute
if (millisTime-millisThinkSpeak > 60000) {
millisThinkSpeak=millisTime;
SerialESP.flush();
sendATtoESP("AT+CIPSTART=\"TCP\",\"184.106.153.149\",80", 10,"OK");
String MsgTS = "GET /update?api_key=";
MsgTS += "QM1DIPJTK8LEOP1Y";
MsgTS +="&field1=";
MsgTS += String ("10"); //variable from HC-12
MsgTS += "\r\n\r\n";
String SizeTS = "AT+CIPSEND=";
SizeTS += MsgTS.length();
sendATtoESP(SizeTS,10,"OK");
if(SerialESP.find(">")){
sendATtoESP(MsgTS,20,"OK");
}
else{
Serial.println("Message don't send");
sendATtoESP("AT+CIPCLOSE",5,"OK");
}
}
}
void sendATtoESP(String command, int maxTime, char readReplay[]) {
Serial.print("Command to ESP: ");
Serial.print(command);
Serial.print(" ");
while(countTimeCommand < (maxTime*1)){
SerialESP.println(command);//at+cipsend
if(SerialESP.find(readReplay)){//ok
found = true;
break;
}
countTimeCommand++;
}
if(found == true) {
Serial.println("--OK--");
countTimeCommand = 0;
}
if(found == false) {
Serial.println("--Fail--");
countTimeCommand = 0;
}
found = false;
}