Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* Send one SMS through SIM7600 using AT commands.
* SIM7600 RXD -> ESP32 GPIO16 (TX)
* SIM7600 TXD -> ESP32 GPIO15 (RX)
*/
#include <Arduino.h>
HardwareSerial modem(2);
constexpr int MODEM_RX = 15;
constexpr int MODEM_TX = 16;
constexpr uint32_t MODEM_BAUD = 115200;
const char PHONE_NUMBER[] = "+8615381188302";
const char SMS_TEXT[] = "kincony";
// Read modem responses and mirror them to the USB serial port.
bool waitFor(const char *expected, uint32_t timeoutMs) {
String response;
uint32_t start = millis();
while (millis() - start < timeoutMs) {
while (modem.available()) {
char c = modem.read();
Serial.write(c);
response += c;
if (response.indexOf(expected) >= 0) {
return true;
}
if (response.indexOf("ERROR") >= 0) {
return false;
}
}
delay(1);
}
Serial.println("\n[Timeout]");
return false;
}
bool sendAT(const String &command,
const char *expected = "OK",
uint32_t timeoutMs = 3000) {
while (modem.available()) {
Serial.write(modem.read());
}
Serial.print("\n>> ");
Serial.println(command);
modem.print(command);
modem.print('\r');
return waitFor(expected, timeoutMs);
}
void setup() {
Serial.begin(115200);
modem.begin(MODEM_BAUD, SERIAL_8N1, MODEM_RX, MODEM_TX);
Serial.println("\nWaiting for SIM7600...");
// Allow time for module startup and network registration.
delay(15000);
bool modemReady = false;
for (int i = 0; i < 10; i++) {
if (sendAT("AT")) {
modemReady = true;
break;
}
delay(1000);
}
if (!modemReady) {
Serial.println("No modem response. Check power, baud rate and UART pins.");
return;
}
if (!sendAT("ATE0")) return;
if (!sendAT("AT+CPIN?", "+CPIN: READY")) {
Serial.println("SIM card is not ready.");
return;
}
// Print signal strength and registration status for diagnosis.
sendAT("AT+CSQ");
sendAT("AT+CREG?");
sendAT("AT+CEREG?");
// Configure SMS text mode and GSM character set.
if (!sendAT("AT+CMGF=1")) return;
if (!sendAT("AT+CSCS=\"GSM\"")) return;
String command = String("AT+CMGS=\"") + PHONE_NUMBER + "\"";
if (!sendAT(command, ">", 10000)) {
Serial.println("SMS input prompt was not received.");
return;
}
modem.print(SMS_TEXT);
modem.write((uint8_t)0x1A); // Ctrl+Z submits the SMS.
// Do not retry automatically: this avoids duplicate messages.
if (waitFor("+CMGS:", 120000)) {
Serial.println("\nSMS submitted successfully.");
} else {
Serial.println("\nSMS failed or result is unknown. Check modem output.");
}
}
void loop() {
// UART bridge for manual AT-command debugging.
while (modem.available()) {
Serial.write(modem.read());
}
while (Serial.available()) {
modem.write(Serial.read());
}
}