Hello.
With a sim800l module and an arduino, I want to send an SMS to a specific number at a certain time of the day containing the information that an esp collects from a temperature and humidity sensor. The function of sending SMS is working correctly, but the message I receive is as follows:
Tå@A@É@ÑOÉ@éAT+CMGF=1
AT+CMGS="xxxxxxxxxx"
Temperature: 33.51
Humidity: 16.02
AC Connected
And this is the program:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <SoftwareSerial.h>
//#include<ESP8266WebServer.h>
#include <PubSubClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h>
#include <WiFiClientSecure.h>
#include <time.h>
const String FirmwareVer={"1.4.7"};
#define URL_fw_Version "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
#define URL_fw_Bin "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
const char* host = "raw.githubusercontent.com";
const int httpsPort = 443;
#define rxPin D6
#define txPin D5
SoftwareSerial mySerial(rxPin,txPin);
#define ssid "Ang-Sim"
#define pass "qwerty2580"
//// UDP
WiFiUDP UDP;
IPAddress local_ip(192, 168, 100, 1);
IPAddress gateway(192, 168, 100, 1);
IPAddress subnet(255, 255, 255, 0);
#define UDP_PORT 4210
//ESP8266WebServer server(80);
const char* wifi = "SRV-TSC";
const char* password = "Cer@toLimited141";
const String prefix = "/angizeh/toossab/1/4";
const char* mqtt_topic = "/angizeh/toossab/1/4";
const char* clientID = "AirHumidityNode12";
const char* mqttServerName = "xxxxxxxxxxxxx";
const int mqttport = 1883;
const char* mqttuser = "xxxxxxxxxxxxxxxxx";
const char* mqttpass = "xxxxxxxxxxxxx";
WiFiClient wclient;
PubSubClient client(wclient);
String topic = "";
String message = "";
String message01,message02, toDigit;
String getValue(String data, char separator, int index);
float airTemperatureA = 0.0, airTemperatureB = 0.0 ,airTemperatureReal = 0.0, airHumidityA = 0.0,airHumidityB = 0.0, airHumidityReal = 0.0;
int dataA , dataReal;
// UDP Buffer
char packet[255];
char reply[] = "Packet received!";
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
int ACState = 1;
int newACState = 1;
int cnt=10;
int cnt2=10;
int nodeDisconnectCnt=2;
int timezone = 4.5 * 3600 ;
int dst = 0;
int hour;
int minute;
int second;
int trigger = 1;
static unsigned long timer4 = millis();
//static unsigned long timer3 = millis();
static unsigned long timer2 = millis();
//static unsigned long timer = millis();
const String PHONE = "9xxxxxxxxxxx";
const String PHONE2 = "9xxxxxxxxxxx";
void setup()
{
delay(1300);
//ESP.wdtEnable(0);
// Setup serial port
Serial.begin(115200);
Serial.println();
// Begin Access Point
Serial.println("UDP server\nStarting access point...");
WiFi.mode(WIFI_AP_STA);
WiFi.softAPConfig(local_ip, gateway, subnet);
WiFi.softAP(ssid, pass);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
// Begin listening to UDP port
UDP.begin(UDP_PORT);
Serial.print("Listening on UDP port ");
Serial.println(UDP_PORT);
STA();
configTime(timezone, dst, "pool.ntp.org","time.nist.gov");
//پیکربندی ارتباط سریال ماژول
mySerial.begin(9600);
Serial.println("Initializing...");
//delay(1000);
mySerial.begin(9600); //Define boadrate of serial communication
mySerial.println("AT+CMGF=1");
delay(2000);
}
void loop()
{
time_t now = time(nullptr);
struct tm* p_tm = localtime(&now);
hour = p_tm->tm_hour;
minute = p_tm->tm_min;
second = p_tm->tm_sec;
if (hour == 18 && minute == 59 && second == 0) {
sendingData();
trigger = 0;
}
if (hour == 19 && minute == 6 && 15>second>0) {
if (trigger = 1){
trigger = 0;
sendingData();
}
}
if (hour == 23 && minute == 59) {
trigger = 1;
}
if (WiFi.status() == WL_CONNECTED){
// server.handleClient();
ESP.wdtFeed();
if (millis() - timer4 > 60000) {
repeatedCall();
timer4 = millis();
}
if (!client.connected()){
reconnect();
}else{
packet[0] = '\0';
receiveUDP();
delay(1000);
if (getValue(packet,',',0) == "nodeA") {
Serial.print("Message is: "); Serial.println("Node A");
message02 = packet;
// Serial.println(packet);
// Serial.print("12");
// Serial.print(",");
Serial.print("Temperature: ");
Serial.println(getValue(message02,',',1));
toDigit = getValue(message02,',',1);
airTemperatureReal = toDigit.toFloat();
if (airTemperatureA != airTemperatureReal){
airTemperatureA = airTemperatureReal;
dataPublish();
Serial.println("Published");
}
Serial.print("Humidity: ");
Serial.println(getValue(message02,',',2));
toDigit = getValue(message02,',',2);
airHumidityReal = toDigit.toFloat();
if (airHumidityA != airHumidityReal){
airHumidityA = airHumidityReal;
timer2 = millis();
dataPublish();
// client.publish(toCharArray("/angizeh/toossab/1/4/Humidity"), toCharArray(String(airHumidityA)));
Serial.println("Published");
}
Serial.println(getValue(message02,',',3));
toDigit = getValue(message02,',',3);
if (toDigit.length() > 0)
{
dataReal = toDigit.toFloat();
dataA = dataReal;
newACState = dataA;
Serial.println("Humidity Published");
}
if (ACState != newACState){
ACState = newACState;
Serial.println("UDP packet received ");
if (ACState == 1){
//client.publish(toCharArray("/angizeh/toossab/1/4/SMSSending"), toCharArray("Sending SMS 1"));
phone1Config();
mySerial.print("AC Connected"); //محتوای ارسالی
delay(100);
mySerial.write(0x1A);
Serial.println ("AC Connected");
delay(5000);
phone2Config();
mySerial.print("AC Connected"); //محتوای ارسالی
delay(100);
mySerial.write(0x1A);
Serial.println ("AC Connected");
delay(1000);
}
if (ACState == 0) {
// client.publish(toCharArray("/angizeh/toossab/1/4/SMSSending"), toCharArray("Sending SMS 0"));
phone1Config();
mySerial.print("AC Disconnected"); //محتوای ارسالی
delay(100);
mySerial.write(0x1A);
Serial.println ("AC Disconnected");
delay(5000);
phone2Config();
mySerial.print("AC Disconnected"); //محتوای ارسالی
delay(100);
mySerial.write(0x1A);
Serial.println ("AC Disconnected");
delay(1000);
}
}
}
else {
client.publish(toCharArray("/angizeh/toossab/1/4/nodeAState"), toCharArray("Disconnected"));
dataPublish();
}
}
Serial.printf("Available RAM: %d\n", ESP.getFreeHeap());
//updateSerial();
} else{
Serial.println("no connection");
checkWifi();
}
yield();
}
void updateSerial()
{
delay(500);
while (Serial.available())
{
mySerial.write(Serial.read());//هرچه در سریال مانیتور نوشته شود به ماژول ارسال میشود
}
while(mySerial.available())
{
Serial.write(mySerial.read());//هرچه از ماژول دریافت شود در سریال مانیتور نوشته میشود
}
}
void STA()
{
WiFi.begin(wifi, password);
while (WiFi.status() != WL_CONNECTED){
static unsigned long connectionTimer = millis();
delay(100);
Serial.print(".");
if (millis() - connectionTimer > 15000){
connectionTimer = millis();
ESP.wdtEnable(0);
while(1);
}
}
Serial.println();
Serial.print(".....Connect to the WiFi and open the IP address given below.....");
Serial.println("IP address:-");
Serial.println(WiFi.localIP());
// server.on ("/", [] () {server.send(200, "text/plain", "HELLO THERE");});
// server.begin();
Serial.print("connecting...");
client.setServer(mqttServerName, mqttport);
client.setCallback(onMessageArrived);
//
while (!client.connected()){
delay(1000);
Serial.println("Connecting To Server ...");
if (client.connect(clientID, mqttuser, mqttpass, toCharArray(prefix + "/Will"), 1, true, toCharArray("Bye"), true))
{
Serial.println("Connected To Server");
}
else
{
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
break;
}
}
client.publish(toCharArray("/angizeh/toossab/1/4/ESPState"), toCharArray("turn on"));
}
char* toCharArray(String str) {
return &str[0];
}
void onMessageArrived(char* t, byte* m, unsigned int length) {
topic = String(t);
message = String((char*)m);
message = message.substring(0, length);
if (message == "HELLO") {
Serial.println("Hello client");
Serial.println("Hello server");
}
}
void reconnect() {
client.setServer(mqttServerName, mqttport);
client.setCallback(onMessageArrived);
if (!client.connected()) {
while (!client.connected()) {
Serial.print("MQTT..");
delay(1000);
if (client.connect(clientID, mqttuser, mqttpass, toCharArray(prefix + "/Will"), 1, true, toCharArray("Disconnected"), true)) {
client.setCallback(onMessageArrived);
Serial.println("MQTT connected");
} else { error(); }
}
}
client.loop();
delay(1000);
}
void error() { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); }
void receiveUDP(){
int packetSize = UDP.parsePacket();
if (packetSize) {
Serial.print("Received packet! Size: ");
Serial.println(packetSize);
int len = UDP.read(packet, 255);
if (len > 0){
packet[len] = '\0';
}
Serial.print("Packet received: ");
Serial.println(packet);
}
for(int i=0;i<UDP_TX_PACKET_MAX_SIZE;i++) packetBuffer[i] = 0;
}
String getValue (String data, char separator, int index) {
int found = 0;
int strIndex[] = { 0, -1 };
int maxIndex = data.length();
for (int i = 0; i <= maxIndex && found <= index; i ++) {
if (data.charAt(i) == separator || i == maxIndex) {
found ++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i + 1 : i;
}
}
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
void dataPublish (){
if (!client.connected()) {
reconnect();
} else {
client.publish(toCharArray("/angizeh/toossab/1/4/Temperature"), toCharArray(String(airTemperatureA)));
client.publish(toCharArray("/angizeh/toossab/1/4/Humidity"), toCharArray(String(airHumidityA)));
if (dataA == 1){
client.publish(toCharArray("/angizeh/toossab/1/4/ACPower"), toCharArray("1"));
}
if (dataA == 0){
client.publish(toCharArray("/angizeh/toossab/1/4/ACPower"), toCharArray("0"));
}
}
}
void FirmwareUpdate()
{
WiFiClientSecure client;
client.setInsecure();
if (!client.connect(host, httpsPort)) {
Serial.println("Connection failed");
return;
}
client.print(String("GET ") + URL_fw_Version + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
//Serial.println("Headers received");
break;
}
}
String payload = client.readStringUntil('\n');
payload.trim();
if(payload.equals(FirmwareVer) )
{
Serial.println("Device already on latest firmware version "+FirmwareVer);
}
else
{
Serial.println("New firmware detected");
ESPhttpUpdate.setLedPin(LED_BUILTIN, LOW);
t_httpUpdate_return ret = ESPhttpUpdate.update(client, URL_fw_Bin);
switch (ret) {
case HTTP_UPDATE_FAILED:
Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
break;
case HTTP_UPDATE_NO_UPDATES:
Serial.println("HTTP_UPDATE_NO_UPDATES");
break;
case HTTP_UPDATE_OK:
Serial.println("HTTP_UPDATE_OK");
break;
}
}
}
void repeatedCall(){
// save the last time you blinked the LED
FirmwareUpdate();
}
void checkWifi (){
while (WiFi.status() != WL_CONNECTED){
ESP.wdtFeed();
ESP.wdtDisable();
delay(500);
Serial.print(".");
delay(500);
cnt--;
if(cnt==0){
ESP.wdtDisable();
#ifdef SOFT_WATCHDOG
ESP.wdtEnable(0);
#endif
while(1);
}
}
}
void sendingData(){
phone1Config();
mySerial.print("Temperature: ");
delay(100);
mySerial.println(airTemperatureReal); //محتوای ارسالی
delay(100);
mySerial.print("Humidity: ");
delay(100);
mySerial.println(airHumidityReal);
delay(100);
if (dataA == 1){
mySerial.print("AC Connected");
}
if (dataA == 0){
mySerial.print("AC Disconnected");
}
mySerial.write(0x1A);
delay(5000);
Serial.println ("AC Connected");
phone2Config();
mySerial.print("Temperature: ");
delay(100);
mySerial.println(airTemperatureReal); //محتوای ارسالی
delay(100);
mySerial.print("Humidity: ");
delay(100);
mySerial.println(airHumidityReal);
delay(100);
if (dataA == 1){
mySerial.print("AC Connected");
}
if (dataA == 0){
mySerial.print("AC Disconnected");
}
mySerial.write(0x1A);
delay(1000);
Serial.println ("AC Connected");
}
void phone1Config (){
mySerial.print("AT+CMGF=1\r");
delay(1000);
//client.publish(toCharArray("/angizeh/toossab/1/4/ACPower"), toCharArray("Disconnected"));
mySerial.print("AT+CMGS=\""+PHONE+"\"\r");
delay(500);
}
void phone2Config (){
mySerial.print("AT+CMGF=1\r");
delay(1000);
//client.publish(toCharArray("/angizeh/toossab/1/4/ACPower"), toCharArray("Disconnected"));
mySerial.print("AT+CMGS=\""+PHONE2+"\"\r");
delay(500);
}
Sometimes the correct SMS is sent, but sometimes it arrives as above. I had this problem many times with sim800 but I could not solve it. Thank you for your guidance.