hi i have a nodemcu , a sim800l and a neo 6m gps module, i run this code but when isend sms to sim800l its not read it i think please look mu code and tell me what is the problem and why when i send sms i dont see sms in serial?
code
#define TINY_GSM_MODEM_SIM800
#include <TinyGsmClient.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>
#include <NMEAGPS.h>
// Define serial communication for SIM800L and GPS
SoftwareSerial sim800lSerial(4, 5); // RX, TX for SIM800L
SoftwareSerial gpsSerial(D7, D6); // RX, TX for NEO-6M GPS
// SIM800L and GPRS credentials
#define APN "mcinet"
#define GPRS_USER ""
#define GPRS_PASS ""
// MQTT Broker and Topics
const char* broker = "mqtt.services.abrbit.com";
const char* mqttUser = "37_gpb1"; // Add your MQTT username
const char* mqttPassword = "skrq5kW66RL8slGYDRIIuZ6i3nztkYv73poVElOTpX6rWsRPmpvQwoHzQOihrdbO"; // Add your MQTT password
const char* modeTopic = "rezakarma/mode";
const char* alertTopic = "rezakarma/alert";
const char* liveLocTopic = "rezakarma/liveloc";
// Global variables
String ownerNumber = ""; // Owner phone number
String mode = "RIDE"; // Device mode, default is "RIDE"
bool liveLoc = false; // Live location mode
TinyGsm modem(sim800lSerial);
TinyGsmClient gsmClient(modem);
PubSubClient mqttClient(gsmClient);
// GPS Setup
NMEAGPS gps;
gps_fix fix;
double threshold = 0.0005; // Threshold for detecting location change
double lastLat = 0, lastLng = 0;
// Function to send HTTP notification
void sendHTTPNotification() {
// Ensure GPRS is connected
if (!modem.isGprsConnected()) {
Serial.println("GPRS disconnected. Cannot send HTTP request.");
return;
}
String server = "http://your-api-endpoint.com";
String url = server + "/notify?lat=" + String(fix.latitude(), 6) + "&lng=" + String(fix.longitude(), 6);
modem.sendAT(GF("+HTTPTERM")); // Clean previous sessions
modem.sendAT(GF("+HTTPINIT"));
modem.sendAT(GF("+HTTPPARA=\"CID\",1"));
modem.sendAT(GF("+HTTPPARA=\"URL\",\""), url, GF("\""));
modem.sendAT(GF("+HTTPACTION=0")); // 0 = GET request
// Waiting for response
modem.waitResponse();
modem.sendAT(GF("+HTTPTERM"));
}
// Function to send an SMS
void sendSMS(String number, String text) {
modem.sendSMS(number.c_str(), text.c_str());
}
// Function to make a phone call
void makePhoneCall(String number) {
modem.sendAT(GF("+CALL="), number);
modem.waitResponse();
}
// Function to check if coordinates changed beyond threshold
bool locationChanged() {
double latDiff = abs(fix.latitude() - lastLat);
double lngDiff = abs(fix.longitude() - lastLng);
return (latDiff > threshold || lngDiff > threshold);
}
// Function to handle MQTT messages
void mqttCallback(char* topic, byte* payload, unsigned int length) {
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
if (String(topic) == modeTopic) {
if (message == "MODE:PARK" && ownerNumber != "") {
mode = "PARK";
} else if (message == "MODE:RIDE" && ownerNumber != "") {
mode = "RIDE";
}
} else if (String(topic) == liveLocTopic) {
if (message == "LIVE_LOC:ON") {
liveLoc = true;
} else if (message == "LIVE_LOC:OFF") {
liveLoc = false;
}
}
}
// Function to publish GPS location on MQTT
void publishLocation() {
if (gps.available(gpsSerial)) {
fix = gps.read();
if (fix.valid.location) {
String location = "LAT:" + String(fix.latitude(), 6) + ",LNG:" + String(fix.longitude(), 6);
mqttClient.publish(liveLocTopic, location.c_str());
} else {
mqttClient.publish(liveLocTopic, "LOCATION: NOT AVAILABLE");
}
}
}
// MQTT Reconnect function with username and password
void mqttReconnect() {
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect to the broker with username and password
if (mqttClient.connect("nodemcu-client", mqttUser, mqttPassword)) {
Serial.println("connected");
// Subscribe to topics after connection
mqttClient.subscribe(modeTopic);
mqttClient.subscribe(liveLocTopic);
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// Setup function
void setup() {
// Initialize serial communication
Serial.begin(115200);
sim800lSerial.begin(9600);
gpsSerial.begin(9600);
// Initialize modem and connect to GPRS
modem.restart();
modem.gprsConnect(APN, GPRS_USER, GPRS_PASS);
// Set MQTT server and callback
mqttClient.setServer(broker, 1883);
mqttClient.setCallback(mqttCallback);
// Connect to MQTT broker
mqttReconnect();
}
// Function to handle incoming SMS using AT commands and added debugging
void checkForSMS() {
// Send AT command to check for unread SMS (AT+CMGL="REC UNREAD")
// Serial.println("Checking for unread SMS...");
modem.sendAT(GF("+CMGL=\"REC UNREAD\""));
// Wait for the modem response
if (modem.waitResponse(10000L) == 1) {
// Serial.println("No new SMS.");
return;
}
String response = modem.stream.readStringUntil('\n');
Serial.println("Received response: " + response); // Debugging output
// Parse the response to get the SMS
if (response.indexOf("+CMGL:") != -1) {
Serial.println("New SMS found.");
// Extract the sender number and message content
int senderStart = response.indexOf(",\"") + 2;
int senderEnd = response.indexOf("\",\"", senderStart);
String sender = response.substring(senderStart, senderEnd);
Serial.println("Sender number: " + sender); // Debugging output
// Read the actual message in the next line
String message = modem.stream.readStringUntil('\n');
message.trim(); // Remove any extra spaces or newline characters
Serial.println("Message content: " + message); // Debugging output
// Process the received SMS
processSMS(sender, message);
} else {
Serial.println("No SMS found.");
}
}
// Function to handle incoming SMS commands with debugging
void processSMS(String sender, String message) {
Serial.println("Processing SMS from: " + sender); // Debugging output
if (message.startsWith("SET_OWNER_NUMBER:")) {
ownerNumber = message.substring(17); // Extract the number after "SET_OWNER_NUMBER:"
Serial.println("Owner number set to: " + ownerNumber); // Debugging output
sendSMS(sender, "Owner number set successfully!");
} else if (message == "MODE:PARK" && sender == ownerNumber) {
mode = "PARK";
Serial.println("Mode set to PARK by owner.");
sendSMS(sender, "Mode set to PARK");
} else if (message == "MODE:RIDE" && sender == ownerNumber) {
mode = "RIDE";
Serial.println("Mode set to RIDE by owner.");
sendSMS(sender, "Mode set to RIDE");
} else {
Serial.println("Invalid command or unauthorized sender.");
sendSMS(sender, "Invalid command or sender not authorized.");
}
}
void loop() {
// Check if the device is connected to the GPRS internet
if (!modem.isGprsConnected()) {
Serial.println("GPRS disconnected. Attempting to reconnect...");
if (modem.gprsConnect(APN, GPRS_USER, GPRS_PASS)) {
Serial.println("GPRS reconnected.");
} else {
Serial.println("Failed to reconnect to GPRS.");
// Optionally, retry after a delay
delay(5000);
return; // Exit the loop early if reconnection fails
}
}
// Reconnect to MQTT if needed
if (!mqttClient.connected()) {
mqttReconnect();
}
mqttClient.loop();
// Check for SMS periodically
checkForSMS();
// Check GPS data when mode is PARK
if (mode == "PARK" && gps.available(gpsSerial)) {
fix = gps.read();
if (fix.valid.location && locationChanged()) {
// Location changed, send alert
mqttClient.publish(alertTopic, "ALERT: LOCATION_CHANGED");
sendHTTPNotification();
if (ownerNumber != "") {
makePhoneCall(ownerNumber);
}
// Update last known location
lastLat = fix.latitude();
lastLng = fix.longitude();
}
}
// Publish live location if enabled
if (liveLoc && gps.available(gpsSerial)) {
publishLocation();
}
}
Assistant
Reviewing your code, it seems like you are attempting to handle incoming SMS messages using AT commands and parse the responses. However, you're encountering issues when receiving and reading SMS messages. Here are some potential issues and suggestions to help solve your problem:
AT Command Execution:
Ensure that your AT commands are correct and executing as expected. You are sending AT+CMGL="REC UNREAD" to list unread messages. Make sure your SIM800L module is set to text mode for SMS using AT+CMGF=1. You might want to initialize this in your setup() function right after your modem restarts.
Response Reading:
You are reading the response from the modem using modem.stream.readStringUntil('\n'). This might not capture the entire response if the message is split over multiple lines. Instead, use a loop to read all available characters and construct the full response.
Timeout Handling:
You have a waitResponse(10000L) call with a 10-second timeout. Ensure that this succeeds by checking its returned value correctly. After it returns, you should handle or parse the response data.
Debugging:
Ensure you see the debug output during your initial setup. Check whether you're correctly setting the SIM800L to text mode. Add some initial diagnostics with AT and AT+CMGF=1 to ensure everything starts correctly.
Serial Communication:
Ensure that the SoftwareSerial pins are correctly assigned and connected between the NodeMCU and SIM800L module. Confirm that there are no hardware issues or incorrect wiring.
Correct Command Handling:
Since your code relies on the modem returning full lines with \n, ensure these expectations match what the SIM800L returns for each SMS.
Below is a refined snippet to focus on initialization and correctly setting up the module:
cpp
User
it's not fixed
Assistant
Let's take a more detailed approach to diagnose and hopefully fix the issue you're encountering with reading SMS using the SIM800L.
Step-by-step Troubleshooting
Confirm Hardware Connections:
Double-check the wiring between the NodeMCU and the SIM800L. Ensure your RX and TX are connected correctly and that the power supply to the SIM800L is sufficient (it often requires 4.2V with adequate current, typically around 2A).
SIM800L Configuration Commands:
Ensure the SIM800L has been properly initialized to operate in SMS text mode. Add the configuration commands in setup() as follows:
cpp
modem.restart();
modem.sendAT(GF("+CMGF=1")); // Set SMS to text mode
if (modem.waitResponse(1000) != 1) {
Serial.println("Failed to set text mode for SMS");
return;
}
modem.sendAT(GF("+CNMI=1,1,0,0,0")); // Configure to notify of new incoming SMS
if (modem.waitResponse(1000) != 1) {
Serial.println("Failed to configure new SMS indication");
}
The AT+CNMI command helps by ensuring the module is set to inform you of incoming messages, which can be useful to trigger immediate reads.
AT Command Debugging:
Allow some additional diagnostics and confirms with commands like AT, AT+CSQ (signal quality), and any network/battery status checks (e.g., AT+COPS? for operator, AT+CBC for battery) initially to verify the module is responding:
cpp
modem.sendAT(GF(""));
if (modem.waitResponse(1000) != 1) {
Serial.println("AT test failed, check connections!");
}
modem.sendAT(GF("+CSQ"));
if (modem.waitResponse(1000) != 1) {
Serial.println("Failed to get signal strength");
} else {
// Optional: read and print the signal result
Serial.println(modem.stream.readStringUntil('\n'));
}
Reading SMS:
User
i run basic sms test code and when i send a sms with text "Hello" to device i get this is serial:
code
00:01:50.042 -> +CMTI: "SM",44
Assistant
Receiving +CMTI: "SM",44 indicates that your SIM800L module correctly received a new SMS and is notifying you which memory location this message is stored in. The number 44 specifies the storage index in the SIM memory.
Now you need to retrieve and read the actual message content from the indicated storage location. Here’s how you can adjust your code to read and display the SMS at that specific location:
Code to Read a Specific SMS
You need to use the AT+CMGR command to read the message at the given index:
cpp
#include <SoftwareSerial.h>
SoftwareSerial sim800lSerial(4, 5); // RX, TX for SIM800L
void setup() {
Serial.begin(115200);
sim800lSerial.begin(9600);
delay(1000);
// Initialize SIM800L for SMS Text Mode
sim800lSerial.println("AT");
delay(1000);
outputResponse();
sim800lSerial.println("AT+CMGF=1"); // Set SMS to text mode
delay(1000);
outputResponse();
}
void loop() {
if (sim800lSerial.available()) {
String response = sim800lSerial.readStringUntil('\n');
Serial.println("Received: " + response);
// Check if a new message has arrived and notify
if (response.startsWith("+CMTI:")) {
// Parse the memory index from the response
int indexPosition = response.lastIndexOf(',') + 1;
String indexStr = response.substring(indexPosition);
indexStr.trim(); // Remove any unwanted whitespace
int index = indexStr.toInt(); // Convert index to integer
// Read the message at the specified index
readSMS(index);
}
}
}
void outputResponse() {
if (sim800lSerial.available()) {
while (sim800lSerial.available()) {
Serial.write(sim800lSerial.read());
}
}
}
void readSMS(int index) {
// Send command to read the specific SMS
sim800lSerial.print("AT+CMGR=");
sim800lSerial.println(index);
delay(1000); // Wait for a response
// Output the response from the modem
while (sim800lSerial.available()) {
String smsContent = sim800lSerial.readStringUntil('\n');
Serial.println("SMS Content: " + smsContent);
}
}
User
i run new code you provide i send sms with text "Hello" and i get this response in serial:
It looks like your SIM800L is correctly notifying you of new messages, and you're able to trigger the reading of a specific message from the SIM storage with the AT+CMGR command. However, the output seems to indicate that you are not capturing the actual message content, as seen with the empty SMS Content: line.
Addressing the Issue:
Reading Full Response:
The SMS content might appear in subsequent lines after the initial +CMGR response. Ensure you read all lines until you capture the message content itself.
Code Adjustment for Full Reading:
Adjust your loop to ensure you're retrieving the complete response, including the message content, which usually comes right after the header line that includes metadata (like timestamp, sender, etc.).
Here's an improved version that captures all available lines for a more comprehensive response:
cpp
#include <SoftwareSerial.h>
SoftwareSerial sim800lSerial(4, 5); // RX, TX for SIM800L
void setup() {
Serial.begin(115200);
sim800lSerial.begin(9600);
delay(1000);
// Initialize SIM800L for SMS Text Mode
sim800lSerial.println("AT");
delay(1000);
outputResponse();
sim800lSerial.println("AT+CMGF=1"); // Set SMS to text mode
delay(1000);
outputResponse();
}
void loop() {
if (sim800lSerial.available()) {
String response = sim800lSerial.readStringUntil('\n');
Serial.println("Received: " + response);
// Check if a new message has arrived and notify
if (response.startsWith("+CMTI:")) {
// Parse the memory index from the response
int indexPosition = response.lastIndexOf(',') + 1;
String indexStr = response.substring(indexPosition);
indexStr.trim(); // Remove any unwanted whitespace
int index = indexStr.toInt(); // Convert index to integer
// Read the message at the specified index
readSMS(index);
}
}
}
void outputResponse() {
if (sim800lSerial.available()) {
while (sim800lSerial.available()) {
Serial.write(sim800lSerial.read());
}
}
}
void readSMS(int index) {
// Send command to read the specific SMS
sim800lSerial.print("AT+CMGR=");
sim800lSerial.println(index);
delay(1000); // Wait for a response
// Read all lines till the end of the message content
while (sim800lSerial.available()) {
String line = sim800lSerial.readStringUntil('\n');
line.trim(); // Remove any extra whitespace
if (line.length() > 0) {
Serial.println("SMS Content: " + line);
}
}
}
User
so i want use TinyGsmClient to read sms, what should ido?
Assistant
If you want to use the TinyGsmClient library to read SMS with the SIM800L module, you can do so by leveraging the AT command abstraction that TinyGsm provides. TinyGsm simplifies interactions with GSM modules, but reading SMS still requires interacting with the module's AT command set.
Here's a structured approach using the TinyGsm library to handle SMS reading in a more structured manner:
Initialization & Configuration
Setup Your TinyGsm Environment:
Ensure your environment is correctly set up for the TinyGsm library, including using the appropriate pins for SoftwareSerial.
Use Provided AT Commands:
While TinyGsm provides functionalities for network management and connectivity, SMS handling might still use direct AT commands under the hood.
Code Example Using TinyGsm
Here's how you might integrate TinyGsmClient to read SMS:
cpp
User
code
noIDE-unsaved2024917-24984-1ipoxqj.tw43\sketch_oct17a\sketch_oct17a.ino: In function 'void setup()':
C:\Users\Lenovo\AppData\Local\Temp\.arduinoIDE-unsaved2024917-24984-1ipoxqj.tw43\sketch_oct17a\sketch_oct17a.ino:24:19: error: could not convert '((TinyGsmModem<TinyGsmSim800>*)(& modem))->TinyGsmModem<TinyGsmSim800>::sendAT<const char*>(((const char*)"+CMGF=1"))' from 'void' to 'bool'
24 | if (modem.sendAT(GF("+CMGF=1")) && modem.waitResponse() == 1) {
| ~~~~~~~~~~~~^~~~~~~~~~~~~~~
C:\Users\Lenovo\AppData\Local\Temp\.arduinoIDE-unsaved2024917-24984-1ipoxqj.tw43\sketch_oct17a\sketch_oct17a.ino:31:19: error: could not convert '((TinyGsmModem<TinyGsmSim800>*)(& modem))->TinyGsmModem<TinyGsmSim800>::sendAT<const char*>(((const char*)"+CNMI=1,2,0,0,0"))' from 'void' to 'bool'
31 | if (modem.sendAT(GF("+CNMI=1,2,0,0,0")) && modem.waitResponse() == 1) {
| ~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
exit status 1
Compilation error: could not convert '((TinyGsmModem<TinyGsmSim800>*)(& modem))->TinyGsmModem<TinyGsmSim800>::sendAT<const char*>(((const char*)"+CMGF=1"))' from 'void' to 'bool'
Assistant
The error you're seeing is due to a misunderstanding about the return type of the sendAT() function from the TinyGsm library. The sendAT() function does not return a bool; instead, it returns void. You need to manage the sequence of AT command sending and response checking differently.
Here’s how you can adjust your code to correct these errors:
Corrected Code
Instead of trying to use the return value from sendAT(), call it and then use waitResponse() separately:
cpp
#define TINY_GSM_MODEM_SIM800
#include <TinyGsmClient.h>
#include <SoftwareSerial.h>
// SIM800L RX, TX Pins
SoftwareSerial sim800lSerial(4, 5);
// Set your baud rate
#define SIM800L_BAUD 9600
// Create modem instance
TinyGsm modem(sim800lSerial);
void setup() {
// Initialize device
Serial.begin(115200);
sim800lSerial.begin(SIM800L_BAUD);
// Begin with modem sync
Serial.println("Initializing modem...");
modem.restart();
// Set SIM800L to SMS text mode
modem.sendAT("+CMGF=1"); // Set SMS to text mode
if (modem.waitResponse() == 1) {
Serial.println("SMS Text Mode set.");
} else {
Serial.println("Failed to set SMS Text Mode.");
}
// Optionally setup new message indication
modem.sendAT("+CNMI=1,2,0,0,0"); // Set SMS notification
if (modem.waitResponse() == 1) {
Serial.println("Waiting for new SMS indications.");
} else {
Serial.println("Failed to configure new message indication.");
}
}
void loop() {
// Check for new unread messages
if (checkForUnreadSMS()) {
// Process any new SMS found
processSMS();
}
// Only poll SMS periodically
delay(10000);
}
bool checkForUnreadSMS() {
modem.sendAT("+CMGL=\"REC UNREAD\"");
return (modem.waitResponse(5000L) == 1); // Check if there is an unread SMS
}
void processSMS() {
while (sim800lSerial.available()) {
String response = sim800lSerial.readStringUntil('\n');
response.trim(); // Cleanup whitespace
if (response.startsWith("+CMGL:")) {
// Extract SMS details
int index = response.substring(response.indexOf(",") + 1, response.indexOf(",\"")).toInt();
Serial.print("SMS index: "); Serial.println(index);
String phoneNumber = response.substring(response.indexOf(",\"") + 2, response.lastIndexOf("\","));
Serial.print("Phone Number: "); Serial.println(phoneNumber);
String message = sim800lSerial.readStringUntil('\n');
message.trim(); // Cleanup whitespace
Serial.print("Message: "); Serial.println(message);
// Optionally delete the message after processing
deleteSMS(index);
}
}
}
void deleteSMS(int index) {
modem.sendAT("+CMGD=", String(index).c_str());
if (modem.waitResponse() == 1) {
Serial.println("SMS deleted successfully.");
} else {
Serial.println("Failed to delete SMS.");
}
}
User
i sent a sms with text "hello" to s9m800 but i dont see any result in serial
Assistant
If you're not seeing any output in the serial monitor after sending an SMS to the SIM800L, it might be due to several potential issues. Let's systematically troubleshoot and ensure your setup is configured correctly:
Troubleshooting Steps
Ensure the Module Configuration:
Make sure the SIM800L module is properly powered and initialized. This includes having an adequate power supply as the module can draw significant current during operations.
Check Serial Connections:
Confirm that the SoftwareSerial pins are correctly connected between your NodeMCU and the SIM800L. The typical connections would look something like this:
NodeMCU GPIO4 (D2) to SIM800L TX
NodeMCU GPIO5 (D1) to SIM800L RX
Monitor Initialization:
To ensure the module is initialized correctly, print debug information step-by-step:
Confirm that the module is powered, responding to AT commands, and initialized in SMS Text mode.
Check Network and SIM Status:
Confirm the presence of a SIM card, cellular network registration, and that it's operational (has credit and valid signal).
AT Command Configuration:
Ensure AT+CMGF=1 is sent to configure SMS text mode, and AT+CNMI=1,2,0,0,0 to receive SMS notifications.
Below is a more verbose setup with detailed debug output to ensure each step completes successfully:
Detailed Debug Code
cpp
User
i run new code you provide and i send a sms with test "Hello" and i get this response in serial:
Yes, it looks like your setup is working correctly! The serial output shows that your SIM800L is properly initialized and receiving SMS messages:
Modem Initialization and Setup:
The modem successfully restarted and was set to SMS Text Mode (+CMGF=1).
It was configured to notify you about new SMS messages (+CNMI=1,2,0,0,0).
Receiving SMS:
The modem is receiving and outputs messages via the +CMT response, which is a direct notification that an SMS has been received.
You see the sender's number and the message Hello, meaning the SMS content was successfully retrieved and displayed.
Next Steps
Improving Handling:
You might want to implement processing logic inside readSMS(index) to capture +CMT messages and further handle them.
Ensure you clean up old messages from memory if it's a long-term operation.
Additional Features:
Error Handling: Expand your error handling to include potential response errors from the GSM module.
Memory Management: Consider using AT+CMGD to delete read messages from memory if you want to manage storage.
Advanced Processing: Integrate logic to handle different SMS commands or tasks based on SMS content.
Optimize for Use Case:
If this is part of a larger project, integrate it accordingly and ensure your loop frequency and response management align with other tasks the NodeMCU handles.
It seems like you have successfully established a basic connection and data flow, so you can now build on this foundation for additional features and implementations.
User
so this is my orginal code , so base on solution we found edit my code to read sms properly
code
Assistant
Let's integrate the solution we found into your original code. This involves updating the checkForSMS() function to properly handle unread SMS messages and process them accordingly. I’ll incorporate the necessary adjustments to make sure SMS reading using the TinyGsm library works seamlessly in your setup.
Updated Code
Here's how you can modify your code for proper SMS handling:
cpp
User
i send sms with text "Hello" but i dont get any response in serial
Assistant
If you're not seeing any response in the serial monitor after sending an SMS, it indicates that the code isn't detecting the incoming message properly. Here are some troubleshooting steps and considerations to help resolve the issue:
Troubleshooting Steps
Serial Communication:
Ensure the baud rates are set correctly and match between the NodeMCU and SIM800L, as well as the Serial Monitor.
Confirm that RX and TX pins are correctly connected:
NodeMCU TX (to SIM800L RX)
NodeMCU RX (to SIM800L TX)
Verify Module Initialization:
Ensure the modem is correctly initialized and is responding to basic AT commands.
Add diagnostic checks to verify the module status during the setup phase:
cpp
void setup() {
Serial.begin(115200);
sim800lSerial.begin(9600);
gpsSerial.begin(9600);
Serial.println("Initializing modem...");
if (!modem.restart()) {
Serial.println("Failed to restart modem");
while (true); // Halt execution
}
Serial.println("Setting SMS mode...");
modem.sendAT("+CMGF=1");
if (modem.waitResponse(1000) != 1) {
Serial.println("Failed to set SMS mode.");
} else {
Serial.println("SMS text mode set.");
}
modem.sendAT("+CNMI=1,2,0,0,0");
if (modem.waitResponse(1000) != 1) {
Serial.println("Failed to configure new message indication.");
} else {
Serial.println("New message indication configured.");
}
if (!modem.gprsConnect(APN, GPRS_USER, GPRS_PASS)) {
Serial.println("Failed to connect to GPRS.");
} else {
Serial.println("GPRS connected.");
}
mqttClient.setServer(broker, 1883);
mqttClient.setCallback(mqttCallback);
mqttReconnect();
}
Signal and Network Check:
User
in prevous code you provide i get sms test and i also dhare the response with you but when i asked you to apply solution on my orginal code the new code you provide not get sms, why?
Assistant
Given that the simplified version of the code successfully received SMS messages, but the original integration doesn't work, we need to explicitly focus on a few aspects:
Focus on SMS Handling:
Ensure that the SMS configuration and checking logic in your original code matches what worked in the standalone test.
Separate Initialization Steps:
Make sure that all initialization steps (like setting up SMS modes and configuring notifications) are done correctly and any conflicts with other parts of your code (like the MQTT parts) are avoided.
Debugging Output:
Ensure that there’s enough debugging output to trace through what your setup is doing, especially concerning receiving and reading messages.
Let's attempt to reconcile these differences by ensuring the SMS handling is set up and processed correctly in the larger structure of your code.
cpp
User
it could be because of gprs connection of sim800l ?
Assistant
The GPRS connection itself should not interfere directly with the ability of the SIM800L to receive SMS, as SMS and GPRS are separate functionalities. However, here are some scenarios where GPRS settings might indirectly affect SMS handling or overall performance:
Module Configuration:
If the module is extensively trying (and failing) to connect to the GPRS network, it might not perform other tasks efficiently. Make sure that the attempts to connect to GPRS are not overwhelming the module or blocking other operations.
Power Supply:
GPRS usage requires substantial power, especially when transmitting data. Ensure that your power supply is stable and adequate, supplying 4.0-4.2V with sufficient current (up to 2A) to avoid brownouts or resets that could disrupt service.
AT Command Priorities:
If you are issuing GPRS-related commands frequently or checking connectivity too aggressively in your loop, it might monopolize the serial interface or delay processing other commands like those for SMS.
Network Overhead:
If the module is busy handling network tasks due to frequent or continuous MQTT operations over GPRS, it might struggle to manage incoming SMS interruptions.
To thoroughly test whether GPRS connection issues are impacting SMS receipt, consider a few troubleshooting actions:
Isolating and Testing
Disable GPRS Temporarily:
As a test, for the purpose of isolating, avoid connecting to GPRS in setup() and see if SMS handling starts working consistently. Comment out GPRS connection logic:
cpp
/*
if (modem.gprsConnect(APN, GPRS_USER, GPRS_PASS)) {
Serial.println("GPRS connected successfully");
} else {
Serial.println("GPRS failed to connect");
}
*/
Test SMS in Isolation:
With the above disabled, focus solely on the SMS reading parts to ensure nothing else is affecting the SMS handling logic. If it works without GPRS, you'll have to adjust timing and prioritization.
Enhancing the Current Setup
Once SMS handling without GPRS is consistently reliable, consider:
Increase Delays: Ensure adequate delay in your loop() so the modem has time to process incoming messages and network tasks.
Not yet included in a published release.
void setup() {
// Initialize serial communication for debugging
Serial.begin(115200);
sim800lSerial.begin(9600); // Initialize SIM800L serial interface
gpsSerial.begin(9600); // Initialize GPS serial interface
// Initialize the modem and set it to text mode for SMS
modem.restart();
modem.sendAT(GF("+CMGF=1")); // Set SMS to text mode
modem.waitResponse(); // Wait for the response from SIM800L
if (!modem.gprsConnect(APN, GPRS_USER, GPRS_PASS)) {
Serial.println("Failed to connect to GPRS.");
return;
}
Serial.println("GPRS connected!");
// Set MQTT server and callback
mqttClient.setServer(broker, 1883);
mqttClient.setCallback(mqttCallback);
// Attempt to connect to the MQTT server
mqttReconnect();
}
Add more comprehensive read handling within checkForSMS() to ensure the full response is captured, and validate that the SIM800L is properly communicating. It’s also a good idea to temporarily add more debug statements to ensure the flow is as expected at each critical stage.
If the issue persists after ensuring these configurations, consider conducting manual testing of the SIM800L with a basic sketch to verify its ability to send and receive SMS using SoftwareSerial before integrating with the complete system.
Ensure your checkForSMS() function robustly handles input. Use a loop to read incoming data from the buffer instead of assuming lines end with \n.
cpp
void checkForSMS() {
modem.sendAT(GF("+CMGL=\"REC UNREAD\""));
if (modem.waitResponse(10000L) != 1) {
Serial.println("No new message or failed to read SMS.");
return;
}
// Read available lines till the buffer is empty
while (sim800lSerial.available()) {
String response = sim800lSerial.readStringUntil('\n');
Serial.println("SMS Response: " + response); // Debug output - capture and see what's returned
// Optional processing of response if "+CMGL" exists in the output
}
}
Separate Test Setup:
If issues persist, try separating the complete setup and only test basic SMS functionalities in isolation. Write a minimal sketch that just checks and reads SMS. If this works, it suggests issues at integration, possibly timing or handling UART conflicts.
Basic SMS Test Code:
Here's a smaller, focused program designed to test SMS functionality:
cpp
#include <SoftwareSerial.h>
SoftwareSerial sim800lSerial(4, 5); // RX, TX for SIM800L
void setup() {
Serial.begin(115200);
sim800lSerial.begin(9600);
delay(1000);
sim800lSerial.println("AT");
while (!sim800lSerial.available());
Serial.println(sim800lSerial.readString());
sim800lSerial.println("AT+CMGF=1"); // Set SMS to text mode
delay(1000);
while (sim800lSerial.available()) {
Serial.println(sim800lSerial.readStringUntil('\n'));
}
sim800lSerial.println("AT+CMGL=\"REC UNREAD\"");
}
void loop() {
if (sim800lSerial.available()) {
Serial.println(sim800lSerial.readStringUntil('\n'));
}
delay(500);
}
Consider simplifying the handling and adding more extensive debugging output to exactly see where the process could be failing. If after attempting this, you still cannot read SMS, review power and signal (ensure the SIM has adequate signal and credit for SMS).
If none of these suggestions work, consider verifying that the SIM800L module isn't faulty, which may involve trying another unit.
Explanation:
SET SMS to Text Mode: We ensure that the modem is set to text mode via AT+CMGF=1.
Message Notification: When a new message comes in (+CMTI), we extract the index.
Reading SMS: We read the SMS using the AT+CMGR command and parse the content.
Troubleshooting:
Check Network and SIM Status: Make sure that the SIM card is correctly inserted, has sufficient balance (if needed), and the SIM800L has a good network signal.
Buffer Management: Ensure that you're reading the full response and managing the buffer, especially in real implementations where multiple commands might be queued.
Important Considerations:
Index Handling: Ensure you're managing indices correctly and cleaning up read messages if needed (using AT+CMGD=<index> to delete an SMS).
Error Handling: Confirm that you handle or display error messages returned by AT commands for debugging.
Message Format: Pay attention to how strings are formatted and trimmed, especially when parsing received messages from the buffer.
Points of Consideration:
Multi-line Reading: SMS responses typically involve multiple lines, with metadata on the first line (+CMGR: ...) and the actual message on subsequent lines.
Ensuring Output: The trim() function helps avoid capturing empty or whitespace-only lines, improving readability.
Simultaneous Reading: If necessary, add delays to ensure each byte is processed properly, depending on the response speed of the SIM800L module.
This setup should now reveal the content of your SMS messages in the serial output. You can fine-tune your buffer handling and timing if you're integrating this into a larger system or dealing with a rapidly changing state.
#define TINY_GSM_MODEM_SIM800
#include <TinyGsmClient.h>
#include <SoftwareSerial.h>
// SIM800L RX, TX Pins
SoftwareSerial sim800lSerial(4, 5);
// Set your baud rate
#define SIM800L_BAUD 9600
// Create modem instance
TinyGsm modem(sim800lSerial);
void setup() {
// Initialize device
Serial.begin(115200);
sim800lSerial.begin(SIM800L_BAUD);
// Begin with modem sync
Serial.println("Initializing modem...");
modem.restart();
// Set SIM800L to SMS text mode
if (modem.sendAT(GF("+CMGF=1")) && modem.waitResponse() == 1) {
Serial.println("SMS Text Mode set.");
} else {
Serial.println("Failed to set SMS Text Mode.");
}
// Optionally setup new message indication
if (modem.sendAT(GF("+CNMI=1,2,0,0,0")) && modem.waitResponse() == 1) {
Serial.println("Waiting for new SMS indications.");
}
}
void loop() {
// Check for new unread messages
if (checkForUnreadSMS()) {
// Process any new SMS found
processSMS();
}
// Only poll SMS periodically
delay(10000);
}
bool checkForUnreadSMS() {
modem.sendAT(GF("+CMGL=\"REC UNREAD\""));
return modem.waitResponse(5000L) == 1; // Check if response indicates unread SMS
}
void processSMS() {
while (sim800lSerial.available()) {
String response = sim800lSerial.readStringUntil('\n');
response.trim(); // Cleanup whitespace
if (response.startsWith("+CMGL:")) {
// Extract SMS details
int index = response.substring(response.indexOf(",") + 1, response.indexOf(",\"")).toInt();
Serial.print("SMS index: "); Serial.println(index);
String phoneNumber = response.substring(response.indexOf(",\"") + 2, response.lastIndexOf("\","));
Serial.print("Phone Number: "); Serial.println(phoneNumber);
String message = sim800lSerial.readStringUntil('\n');
message.trim(); // Cleanup whitespace
Serial.print("Message: "); Serial.println(message);
// Optionally delete the message after processing
deleteSMS(index);
}
}
}
void deleteSMS(int index) {
modem.sendAT(GF("+CMGD="), index);
if (modem.waitResponse() == 1) {
Serial.println("SMS deleted successfully.");
} else {
Serial.println("Failed to delete SMS.");
}
}
Explanation:
Modem Initialization: We use TinyGsm functionality for initialization to manage SMS mode and setup indications.
Check for New SMS: The function checkForUnreadSMS() sends the AT+CMGL="REC UNREAD" command to list unread messages and returns true if any are found.
Processing SMS: The response from the modem is parsed to extract SMS index, sender number, and message content using String utilities.
Delete SMS: Once messages are processed, they can be deleted using AT+CMGD=index to ensure storage doesn't fill up.
Important Considerations:
Error Handling: Ensure error outputs are implemented and watched for issues in connectivity and command execution.
Polling Interval: Adjust the delay in your loop according to how frequently you expect to receive messages, balancing resource use and immediacy.
Message Storage: Manage storage efficiently to avoid inflating SIM storage with unprocessed messages.
Key Adjustments:
Separate Calls: Call sendAT() followed by waitResponse() separately, because sendAT() by itself doesn't return a value you can check.
Handling Responses: modem.waitResponse() is used to wait for the response from the module after sending the AT command, and it can return a value you can check.
Command Parameters: In deleteSMS(), ensure the index is properly converted to a String before passing it to sendAT(), because sendAT() expects C-strings or other specific types.
This structure should help avoid the conversion error from your initial setup and facilitate correct compilation.
#define TINY_GSM_MODEM_SIM800
#include <TinyGsmClient.h>
#include <SoftwareSerial.h>
// SIM800L RX, TX Pins
SoftwareSerial sim800lSerial(4, 5);
#define SIM800L_BAUD 9600
TinyGsm modem(sim800lSerial);
void setup() {
Serial.begin(115200);
sim800lSerial.begin(SIM800L_BAUD);
delay(1000); // Delay for setup stabilization
Serial.println("Initializing modem...");
if (!modem.restart()) {
Serial.println("Failed to restart modem, check connections!");
return;
}
Serial.println("Modem started.");
modem.sendAT("+CMGF=1"); // SMS text mode
if (modem.waitResponse(10000L) == 1) {
Serial.println("SMS Text Mode set.");
} else {
Serial.println("Failed to set SMS Text Mode.");
}
modem.sendAT("+CNMI=1,2,0,0,0"); // SMS notifications
if (modem.waitResponse(10000L) == 1) {
Serial.println("Waiting for new SMS indications.");
} else {
Serial.println("Failed to configure new message indication.");
}
}
void loop() {
while (sim800lSerial.available()) {
// Read and print available data in chunks to prevent overflow
String response = sim800lSerial.readStringUntil('\n');
response.trim(); // Cleanup whitespace
if (response.length() > 0) {
Serial.println("Received: " + response);
// Check for SMS arrival
if (response.startsWith("+CMTI:")) {
int indexStart = response.lastIndexOf(',') + 1;
int index = response.substring(indexStart).toInt();
Serial.print("New SMS at index: "); Serial.println(index);
// Read and process message
readSMS(index);
}
}
}
delay(500); // Check periodically for new messages
}
void readSMS(int index) {
modem.sendAT("+CMGR=", String(index).c_str());
if (modem.waitResponse(10000L) == 1) {
while (sim800lSerial.available()) {
String smsContent = sim800lSerial.readStringUntil('\n');
smsContent.trim();
if (smsContent.length() > 0) {
Serial.println("SMS Content: " + smsContent);
}
}
} else {
Serial.println("Failed to read SMS.");
}
}
void outputResponse() {
while (sim800lSerial.available()) {
Serial.write(sim800lSerial.read());
}
}
Further Steps:
Check Serial Monitor Baud Rate: Ensure that your serial monitor is set to 115200 baud to match the Serial.begin line.
Debug Individual Components: If issues persist, test the SIM800L independently with direct AT commands using a separate serial terminal to verify it's operational.
SIM and Signal: Ensure the SIM card is correctly seated, has signal (use AT+CSQ to check signal quality), and confirm with basic connectivity tests AT+COPS? to ensure it registers on the network.
Try with Other Devices: Sometimes, swapping out the NodeMCU or using another SIM800L module helps determine if there's a hardware fault.
Check Power Supply: Ensure your SIM800L is powered adequately, ideally with a stable power source capable of delivering 2A at 4.0-4.2V.
#define TINY_GSM_MODEM_SIM800
#include <TinyGsmClient.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>
#include <NMEAGPS.h>
// Define serial communication for SIM800L and GPS
SoftwareSerial sim800lSerial(4, 5); // RX, TX for SIM800L
SoftwareSerial gpsSerial(D7, D6); // RX, TX for NEO-6M GPS
// SIM800L and GPRS credentials
#define APN "mcinet"
#define GPRS_USER ""
#define GPRS_PASS ""
// MQTT Broker and Topics
const char* broker = "mqtt.services.abrbit.com";
const char* mqttUser = "37_gpb1"; // Add your MQTT username
const char* mqttPassword = "skrq5kW66RL8slGYDRIIuZ6i3nztkYv73poVElOTpX6rWsRPmpvQwoHzQOihrdbO"; // Add your MQTT password
const char* modeTopic = "rezakarma/mode";
const char* alertTopic = "rezakarma/alert";
const char* liveLocTopic = "rezakarma/liveloc";
// Global variables
String ownerNumber = ""; // Owner phone number
String mode = "RIDE"; // Device mode, default is "RIDE"
bool liveLoc = false; // Live location mode
TinyGsm modem(sim800lSerial);
TinyGsmClient gsmClient(modem);
PubSubClient mqttClient(gsmClient);
// GPS Setup
NMEAGPS gps;
gps_fix fix;
double threshold = 0.0005; // Threshold for detecting location change
double lastLat = 0, lastLng = 0;
// Function to send HTTP notification
void sendHTTPNotification() {
// Ensure GPRS is connected
if (!modem.isGprsConnected()) {
Serial.println("GPRS disconnected. Cannot send HTTP request.");
return;
}
String server = "http://your-api-endpoint.com";
String url = server + "/notify?lat=" + String(fix.latitude(), 6) + "&lng=" + String(fix.longitude(), 6);
modem.sendAT(GF("+HTTPTERM")); // Clean previous sessions
modem.sendAT(GF("+HTTPINIT"));
modem.sendAT(GF("+HTTPPARA=\"CID\",1"));
modem.sendAT(GF("+HTTPPARA=\"URL\",\""), url, GF("\""));
modem.sendAT(GF("+HTTPACTION=0")); // 0 = GET request
// Waiting for response
modem.waitResponse();
modem.sendAT(GF("+HTTPTERM"));
}
// Function to send an SMS
void sendSMS(String number, String text) {
modem.sendSMS(number.c_str(), text.c_str());
}
// Function to make a phone call
void makePhoneCall(String number) {
modem.sendAT(GF("+CALL="), number);
modem.waitResponse();
}
// Function to check if coordinates changed beyond threshold
bool locationChanged() {
double latDiff = abs(fix.latitude() - lastLat);
double lngDiff = abs(fix.longitude() - lastLng);
return (latDiff > threshold || lngDiff > threshold);
}
// Function to handle MQTT messages
void mqttCallback(char* topic, byte* payload, unsigned int length) {
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
if (String(topic) == modeTopic) {
if (message == "MODE:PARK" && ownerNumber != "") {
mode = "PARK";
} else if (message == "MODE:RIDE" && ownerNumber != "") {
mode = "RIDE";
}
} else if (String(topic) == liveLocTopic) {
if (message == "LIVE_LOC:ON") {
liveLoc = true;
} else if (message == "LIVE_LOC:OFF") {
liveLoc = false;
}
}
}
// Function to publish GPS location on MQTT
void publishLocation() {
if (gps.available(gpsSerial)) {
fix = gps.read();
if (fix.valid.location) {
String location = "LAT:" + String(fix.latitude(), 6) + ",LNG:" + String(fix.longitude(), 6);
mqttClient.publish(liveLocTopic, location.c_str());
} else {
mqttClient.publish(liveLocTopic, "LOCATION: NOT AVAILABLE");
}
}
}
// MQTT Reconnect function with username and password
void mqttReconnect() {
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect to the broker with username and password
if (mqttClient.connect("nodemcu-client", mqttUser, mqttPassword)) {
Serial.println("connected");
// Subscribe to topics after connection
mqttClient.subscribe(modeTopic);
mqttClient.subscribe(liveLocTopic);
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// Setup function
void setup() {
// Initialize serial communication
Serial.begin(115200);
sim800lSerial.begin(9600);
gpsSerial.begin(9600);
// Initialize modem and connect to GPRS
modem.restart();
modem.gprsConnect(APN, GPRS_USER, GPRS_PASS);
// Set MQTT server and callback
mqttClient.setServer(broker, 1883);
mqttClient.setCallback(mqttCallback);
// Connect to MQTT broker
mqttReconnect();
}
// Function to handle incoming SMS using AT commands and added debugging
void checkForSMS() {
// Send AT command to check for unread SMS (AT+CMGL="REC UNREAD")
// Serial.println("Checking for unread SMS...");
modem.sendAT(GF("+CMGL=\"REC UNREAD\""));
// Wait for the modem response
if (modem.waitResponse(10000L) == 1) {
// Serial.println("No new SMS.");
return;
}
String response = modem.stream.readStringUntil('\n');
Serial.println("Received response: " + response); // Debugging output
// Parse the response to get the SMS
if (response.indexOf("+CMGL:") != -1) {
Serial.println("New SMS found.");
// Extract the sender number and message content
int senderStart = response.indexOf(",\"") + 2;
int senderEnd = response.indexOf("\",\"", senderStart);
String sender = response.substring(senderStart, senderEnd);
Serial.println("Sender number: " + sender); // Debugging output
// Read the actual message in the next line
String message = modem.stream.readStringUntil('\n');
message.trim(); // Remove any extra spaces or newline characters
Serial.println("Message content: " + message); // Debugging output
// Process the received SMS
processSMS(sender, message);
} else {
Serial.println("No SMS found.");
}
}
// Function to handle incoming SMS commands with debugging
void processSMS(String sender, String message) {
Serial.println("Processing SMS from: " + sender); // Debugging output
if (message.startsWith("SET_OWNER_NUMBER:")) {
ownerNumber = message.substring(17); // Extract the number after "SET_OWNER_NUMBER:"
Serial.println("Owner number set to: " + ownerNumber); // Debugging output
sendSMS(sender, "Owner number set successfully!");
} else if (message == "MODE:PARK" && sender == ownerNumber) {
mode = "PARK";
Serial.println("Mode set to PARK by owner.");
sendSMS(sender, "Mode set to PARK");
} else if (message == "MODE:RIDE" && sender == ownerNumber) {
mode = "RIDE";
Serial.println("Mode set to RIDE by owner.");
sendSMS(sender, "Mode set to RIDE");
} else {
Serial.println("Invalid command or unauthorized sender.");
sendSMS(sender, "Invalid command or sender not authorized.");
}
}
void loop() {
// Check if the device is connected to the GPRS internet
if (!modem.isGprsConnected()) {
Serial.println("GPRS disconnected. Attempting to reconnect...");
if (modem.gprsConnect(APN, GPRS_USER, GPRS_PASS)) {
Serial.println("GPRS reconnected.");
} else {
Serial.println("Failed to reconnect to GPRS.");
// Optionally, retry after a delay
delay(5000);
return; // Exit the loop early if reconnection fails
}
}
// Reconnect to MQTT if needed
if (!mqttClient.connected()) {
mqttReconnect();
}
mqttClient.loop();
// Check for SMS periodically
checkForSMS();
// Check GPS data when mode is PARK
if (mode == "PARK" && gps.available(gpsSerial)) {
fix = gps.read();
if (fix.valid.location && locationChanged()) {
// Location changed, send alert
mqttClient.publish(alertTopic, "ALERT: LOCATION_CHANGED");
sendHTTPNotification();
if (ownerNumber != "") {
makePhoneCall(ownerNumber);
}
// Update last known location
lastLat = fix.latitude();
lastLng = fix.longitude();
}
}
// Publish live location if enabled
if (liveLoc && gps.available(gpsSerial)) {
publishLocation();
}
}
#define TINY_GSM_MODEM_SIM800
#include <TinyGsmClient.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>
#include <NMEAGPS.h>
// Define serial communication for SIM800L and GPS
SoftwareSerial sim800lSerial(4, 5); // RX, TX for SIM800L
SoftwareSerial gpsSerial(D7, D6); // RX, TX for NEO-6M GPS
// SIM800L and GPRS credentials
#define APN "mcinet"
#define GPRS_USER ""
#define GPRS_PASS ""
// MQTT Broker and Topics
const char* broker = "mqtt.services.abrbit.com";
const char* mqttUser = "37_gpb1"; // Your MQTT username
const char* mqttPassword = "skrq5kW66RL8slGYDRIIuZ6i3nztkYv73poVElOTpX6rWsRPmpvQwoHzQOihrdbO"; // Your MQTT password
const char* modeTopic = "rezakarma/mode";
const char* alertTopic = "rezakarma/alert";
const char* liveLocTopic = "rezakarma/liveloc";
// Global variables
String ownerNumber = ""; // Owner phone number
String mode = "RIDE"; // Device mode, default is "RIDE"
bool liveLoc = false; // Live location mode
TinyGsm modem(sim800lSerial);
TinyGsmClient gsmClient(modem);
PubSubClient mqttClient(gsmClient);
// GPS Setup
NMEAGPS gps;
gps_fix fix;
double threshold = 0.0005; // Threshold for detecting location change
double lastLat = 0, lastLng = 0;
// Function to send HTTP notification
void sendHTTPNotification() {
if (!modem.isGprsConnected()) {
Serial.println("GPRS disconnected. Cannot send HTTP request.");
return;
}
String server = "http://your-api-endpoint.com";
String url = server + "/notify?lat=" + String(fix.latitude(), 6) + "&lng=" + String(fix.longitude(), 6);
modem.sendAT(GF("+HTTPTERM"));
modem.sendAT(GF("+HTTPINIT"));
modem.sendAT(GF("+HTTPPARA=\"CID\",1"));
modem.sendAT(GF("+HTTPPARA=\"URL\",\""), url, GF("\""));
modem.sendAT(GF("+HTTPACTION=0"));
modem.waitResponse();
modem.sendAT(GF("+HTTPTERM"));
}
// Function to send an SMS
void sendSMS(String number, String text) {
modem.sendSMS(number.c_str(), text.c_str());
}
// Function to make a phone call
void makePhoneCall(String number) {
modem.sendAT(GF("+CALL="), number);
modem.waitResponse();
}
// Function to check if coordinates changed beyond threshold
bool locationChanged() {
double latDiff = abs(fix.latitude() - lastLat);
double lngDiff = abs(fix.longitude() - lastLng);
return (latDiff > threshold || lngDiff > threshold);
}
// Function to handle MQTT messages
void mqttCallback(char* topic, byte* payload, unsigned int length) {
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
if (String(topic) == modeTopic) {
if (message == "MODE:PARK" && ownerNumber != "") {
mode = "PARK";
} else if (message == "MODE:RIDE" && ownerNumber != "") {
mode = "RIDE";
}
} else if (String(topic) == liveLocTopic) {
if (message == "LIVE_LOC:ON") {
liveLoc = true;
} else if (message == "LIVE_LOC:OFF") {
liveLoc = false;
}
}
}
// Function to publish GPS location on MQTT
void publishLocation() {
if (gps.available(gpsSerial)) {
fix = gps.read();
if (fix.valid.location) {
String location = "LAT:" + String(fix.latitude(), 6) + ",LNG:" + String(fix.longitude(), 6);
mqttClient.publish(liveLocTopic, location.c_str());
} else {
mqttClient.publish(liveLocTopic, "LOCATION: NOT AVAILABLE");
}
}
}
// MQTT Reconnect function with credentials
void mqttReconnect() {
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
if (mqttClient.connect("nodemcu-client", mqttUser, mqttPassword)) {
Serial.println("connected");
mqttClient.subscribe(modeTopic);
mqttClient.subscribe(liveLocTopic);
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
sim800lSerial.begin(9600);
gpsSerial.begin(9600);
modem.restart();
modem.sendAT("+CMGF=1");
modem.waitResponse(1000);
modem.sendAT("+CNMI=1,2,0,0,0");
modem.waitResponse(1000);
if (modem.gprsConnect(APN, GPRS_USER, GPRS_PASS)) {
Serial.println("GPRS connected successfully");
} else {
Serial.println("GPRS failed to connect");
}
mqttClient.setServer(broker, 1883);
mqttClient.setCallback(mqttCallback);
mqttReconnect();
}
// Function to check for and process new SMS messages
void checkForSMS() {
while (sim800lSerial.available()) {
String line = sim800lSerial.readStringUntil('\n');
line.trim();
if (line.startsWith("+CMTI:")) {
int indexStart = line.lastIndexOf(',') + 1;
int index = line.substring(indexStart).toInt();
Serial.print("New SMS at index: "); Serial.println(index);
readSMS(index);
}
}
}
void readSMS(int index) {
modem.sendAT("+CMGR=", String(index).c_str());
if (modem.waitResponse(10000L) == 1) {
while (sim800lSerial.available()) {
String smsContent = sim800lSerial.readStringUntil('\n');
smsContent.trim();
if (smsContent.length() > 0) {
Serial.println("SMS Content: " + smsContent);
}
}
} else {
Serial.println("Failed to read SMS.");
}
}
void loop() {
if (!modem.isGprsConnected()) {
Serial.println("GPRS disconnected. Attempting to reconnect...");
if (modem.gprsConnect(APN, GPRS_USER, GPRS_PASS)) {
Serial.println("GPRS reconnected.");
} else {
Serial.println("Failed to reconnect to GPRS.");
delay(5000);
return;
}
}
if (!mqttClient.connected()) {
mqttReconnect();
}
mqttClient.loop();
checkForSMS();
if (mode == "PARK" && gps.available(gpsSerial)) {
fix = gps.read();
if (fix.valid.location && locationChanged()) {
mqttClient.publish(alertTopic, "ALERT: LOCATION_CHANGED");
sendHTTPNotification();
if (ownerNumber != "") {
makePhoneCall(ownerNumber);
}
lastLat = fix.latitude();
lastLng = fix.longitude();
}
}
if (liveLoc && gps.available(gpsSerial)) {
publishLocation();
}
}
Modifications & Explanation:
SMS Notification Configuration:
Added configuration using AT+CNMI=1,2,0,0,0 in setup(), enabling message notifications.
Reading SMS:
Implemented the checkForSMS() and readSMS() functions to check for new SMS and read them based on their index. Messages are read using AT+CMGR=<index>.
Debug Messages:
Integrated a variety of Serial.println() statements for key actions in setup and execution to aid debugging and understanding message flow.
SMS Handling Loop:
Each loop iteration checks for and processes new SMS messages. This is integral for continuous operation, especially if you're handling multiple concurrent tasks in the loop.
This integration assumes your environment setup is complete and operational, including network, SMS services, and proper module power. Adjust indices or handling logic based on further testing and your application needs.
Verify the SIM card has network access and is properly registered. You can use commands like AT+CSQ to check signal quality and AT+CREG? for network registration status.
Ensure the device is within a GSM signal range and the SIM card is functional (e.g., check it's not locked with a PIN).
Debugging Steps:
Add extra debugging to checkForSMS() to verify any incoming data from the SIM800L.
cpp
void checkForSMS() {
while (sim800lSerial.available()) {
String line = sim800lSerial.readStringUntil('\n');
line.trim();
Serial.println("Debug: Incoming line: " + line);
if (line.startsWith("+CMTI:")) {
int indexStart = line.lastIndexOf(',') + 1;
int index = line.substring(indexStart).toInt();
Serial.print("New SMS at index: "); Serial.println(index);
readSMS(index);
}
}
}
Testing and Isolation:
As a test, simplify the code to only manage SMS and confirm the SIM800L is receiving SMS:
cpp
#include <TinyGsmClient.h>
#include <SoftwareSerial.h>
SoftwareSerial sim800lSerial(4, 5); // RX, TX for SIM800L
#define SIM800L_BAUD 9600
TinyGsm modem(sim800lSerial);
void setup() {
Serial.begin(115200);
sim800lSerial.begin(SIM800L_BAUD);
Serial.println("Initializing modem...");
if (!modem.restart()) {
Serial.println("Failed to restart modem");
while (true);
}
Serial.println("Setting SMS mode...");
modem.sendAT("+CMGF=1");
modem.waitResponse(1000);
modem.sendAT("+CNMI=1,2,0,0,0");
modem.waitResponse(1000);
}
void loop() {
while (sim800lSerial.available()) {
String line = sim800lSerial.readStringUntil('\n');
Serial.println("Received line: " + line);
}
delay(500);
}
This basic test will help you see if any message-related output is being generated.
Further Considerations:
Hardware Check: Ensure the SIM800L is powered correctly, as it may require a stable 4.0-4.2V supply with adequate current (up to 2A).
SIM Card: Ensure no PIN lock is active, and the card is not faulty or expired.
Cross-verify on Another Board: If possible, test the SIM800L with another board or setup to rule out hardware failure.
Adjustments and diversification of testing procedures should help identify whether the issue is in the signal reception, hardware setup, or software logic.
#define TINY_GSM_MODEM_SIM800
#include <TinyGsmClient.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>
#include <NMEAGPS.h>
// Define serial communication for SIM800L and GPS
SoftwareSerial sim800lSerial(4, 5); // RX, TX for SIM800L
SoftwareSerial gpsSerial(D7, D6); // RX, TX for NEO-6M GPS
// SIM800L and GPRS credentials
#define APN "mcinet"
#define GPRS_USER ""
#define GPRS_PASS ""
// MQTT Broker and Topics
const char* broker = "mqtt.services.abrbit.com";
const char* mqttUser = "37_gpb1"; // Your MQTT username
const char* mqttPassword = "skrq5kW66RL8slGYDRIIuZ6i3nztkYv73poVElOTpX6rWsRPmpvQwoHzQOihrdbO"; // Your MQTT password
const char* modeTopic = "rezakarma/mode";
const char* alertTopic = "rezakarma/alert";
const char* liveLocTopic = "rezakarma/liveloc";
// Global variables
String ownerNumber = ""; // Owner phone number
String mode = "RIDE"; // Device mode, default is "RIDE"
bool liveLoc = false; // Live location mode
TinyGsm modem(sim800lSerial);
TinyGsmClient gsmClient(modem);
PubSubClient mqttClient(gsmClient);
// GPS Setup
NMEAGPS gps;
gps_fix fix;
double threshold = 0.0005; // Threshold for detecting location change
double lastLat = 0, lastLng = 0;
// Function to send HTTP notification
void sendHTTPNotification() {
if (!modem.isGprsConnected()) {
Serial.println("GPRS disconnected. Cannot send HTTP request.");
return;
}
String server = "http://your-api-endpoint.com";
String url = server + "/notify?lat=" + String(fix.latitude(), 6) + "&lng=" + String(fix.longitude(), 6);
modem.sendAT(GF("+HTTPTERM"));
modem.sendAT(GF("+HTTPINIT"));
modem.sendAT(GF("+HTTPPARA=\"CID\",1"));
modem.sendAT(GF("+HTTPPARA=\"URL\",\""), url, GF("\""));
modem.sendAT(GF("+HTTPACTION=0"));
modem.waitResponse();
modem.sendAT(GF("+HTTPTERM"));
}
// Function to send an SMS
void sendSMS(String number, String text) {
modem.sendSMS(number.c_str(), text.c_str());
}
// Function to make a phone call
void makePhoneCall(String number) {
modem.sendAT(GF("+CALL="), number);
modem.waitResponse();
}
// Function to check if coordinates changed beyond threshold
bool locationChanged() {
double latDiff = abs(fix.latitude() - lastLat);
double lngDiff = abs(fix.longitude() - lastLng);
return (latDiff > threshold || lngDiff > threshold);
}
// Function to handle MQTT messages
void mqttCallback(char* topic, byte* payload, unsigned int length) {
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
if (String(topic) == modeTopic) {
if (message == "MODE:PARK" && ownerNumber != "") {
mode = "PARK";
} else if (message == "MODE:RIDE" && ownerNumber != "") {
mode = "RIDE";
}
} else if (String(topic) == liveLocTopic) {
if (message == "LIVE_LOC:ON") {
liveLoc = true;
} else if (message == "LIVE_LOC:OFF") {
liveLoc = false;
}
}
}
// Function to publish GPS location on MQTT
void publishLocation() {
if (gps.available(gpsSerial)) {
fix = gps.read();
if (fix.valid.location) {
String location = "LAT:" + String(fix.latitude(), 6) + ",LNG:" + String(fix.longitude(), 6);
mqttClient.publish(liveLocTopic, location.c_str());
} else {
mqttClient.publish(liveLocTopic, "LOCATION: NOT AVAILABLE");
}
}
}
// MQTT Reconnect function with credentials
void mqttReconnect() {
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
if (mqttClient.connect("nodemcu-client", mqttUser, mqttPassword)) {
Serial.println("connected");
mqttClient.subscribe(modeTopic);
mqttClient.subscribe(liveLocTopic);
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
sim800lSerial.begin(9600);
gpsSerial.begin(9600);
Serial.println("Initializing modem...");
if (!modem.restart()) {
Serial.println("Failed to restart modem");
return;
}
Serial.println("Setting SMS mode...");
modem.sendAT("+CMGF=1");
modem.waitResponse(1000);
Serial.println("Configuring new message notifications...");
modem.sendAT("+CNMI=1,2,0,0,0");
modem.waitResponse(1000);
if (modem.gprsConnect(APN, GPRS_USER, GPRS_PASS)) {
Serial.println("GPRS connected successfully");
} else {
Serial.println("GPRS failed to connect");
}
mqttClient.setServer(broker, 1883);
mqttClient.setCallback(mqttCallback);
mqttReconnect();
}
// Function to check for and process new SMS messages
void checkForSMS() {
while (sim800lSerial.available()) {
String line = sim800lSerial.readStringUntil('\n');
line.trim();
Serial.println("Debug: Incoming line: " + line);
if (line.startsWith("+CMTI:")) {
int indexStart = line.lastIndexOf(',') + 1;
int index = line.substring(indexStart).toInt();
Serial.print("New SMS at index: "); Serial.println(index);
readSMS(index);
}
}
}
void readSMS(int index) {
modem.sendAT("+CMGR=", String(index).c_str());
if (modem.waitResponse(10000L) == 1) {
while (sim800lSerial.available()) {
String smsContent = sim800lSerial.readStringUntil('\n');
smsContent.trim();
if (smsContent.length() > 0) {
Serial.println("SMS Content: " + smsContent);
}
}
} else {
Serial.println("Failed to read SMS.");
}
}
void loop() {
if (!modem.isGprsConnected()) {
Serial.println("GPRS disconnected. Attempting to reconnect...");
if (modem.gprsConnect(APN, GPRS_USER, GPRS_PASS)) {
Serial.println("GPRS reconnected.");
} else {
Serial.println("Failed to reconnect to GPRS.");
delay(5000);
return;
}
}
if (!mqttClient.connected()) {
mqttReconnect();
}
mqttClient.loop();
checkForSMS();
if (mode == "PARK" && gps.available(gpsSerial)) {
fix = gps.read();
if (fix.valid.location && locationChanged()) {
mqttClient.publish(alertTopic, "ALERT: LOCATION_CHANGED");
sendHTTPNotification();
if (ownerNumber != "") {
makePhoneCall(ownerNumber);
}
lastLat = fix.latitude();
lastLng = fix.longitude();
}
}
if (liveLoc && gps.available(gpsSerial)) {
publishLocation();
}
}
Key Points:
Configuration: The modem's SMS configuration (+CMGF=1, +CNMI=1,2,0,0,0) is checked explicitly in setup().
SMS Reading: The logic for reading SMS messages is emphasized with more debug information. Ensure the lines are processed correctly.
Modular Testing: Make sure this section runs without interference from other functions or modules. This may require isolating GSM functionality initially if issues persist.
Debugging:
Run the above code and observe the serial output for any incoming SMS indication (+CMTI:) and ensure it reads the message by looking for the debug lines suggesting receipt and processing.
If you continue having problems,:
Check that nothing else in the loop is interfering with SMS handling (like GPS readings or network reconnect tasks).
Ensure the NodeMCU is capable of handling all tasks with adequate power and load handling.
Prioritize Tasks: Check how time is spent within loop(), optimizing task management between network tasks (like MQTT or HTTP) and SMS checks.
Handle Concurrent Operations: Carefully manage how often GPRS status is checked or requested in your loop to avoid swamping the communication with excessive GPRS commands versus SMS commands.
Ultimately, based on these tests and adjustments, you'll gather insights into how coexistence of these functionalities needs to be balanced for smooth operation without one aspect hindering the other.