Hi All,
Im a newbie in Arduino. Need your advise on how i can fix my problem in my code. I have a \n function in both Ethernet and GSM codes that seems to conflict with each other. When i try to add this GSM \n line to my sketch, my page is not working:
incoming = mySerial.readStringUntil('\n');
I am not familiar with GSM coding, so I am not sure what the solution will be. Can you help me figure out the solution to this? Here's my sketch.
//For ethernet
#include <SPI.h>
#include <Ethernet.h>
//For relay
#include <Wire.h>
#include <Relay.h>
//For Temp
#include <OneWire.h>
#include <DallasTemperature.h>
//For GSM
#include <SoftwareSerial.h>
#include <EEPROM.h>
//For GSM---------------------------------------------------------------------------------
SoftwareSerial mySerial(2, 3);
String allowedNumber; // To store the allowed phone number from the SIM's phonebook
//-----------------------------------------------------------------------------------------
int passFlag = 0;
int passFlag1 = 0;
int passFlag2 = 0;
int passFlag3 = 0;
//Millis timeout---------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
//Batt pin---------------------------------------------------------------------------------
#define SIGNAL_PIN A0 //battery level monitoring using 4.7K & 2.2K ohm resistor
//-----------------------------------------------------------------------------------------
//Temp Pin---------------------------------------------------------------------------------
#define ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float temp;
//-----------------------------------------------------------------------------------------
//Batt computation-------------------------------------------------------------------------
float adc_voltage = 0.0;
float in_voltage = 0.0;
float R1 = 30000.0;
float R2 = 7500.0;
float ref_voltage = 5.0;
int adc_value = 0;
//-----------------------------------------------------------------------------------------
//Ethernet---------------------------------------------------------------------------------
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1, 12);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
//-----------------------------------------------------------------------------------------
// Relay state and pin---------------------------------------------------------------------
String relay1State1 = "OFF";
String relay2State2 = "OFF";
const int TempCon= 6;
const int ChgRlyCon = 7;
//-----------------------------------------------------------------------------------------
// Client variables------------------------------------------------------------------------
char linebuf[160];
int charcount=0;
boolean authentificated=false;
//-----------------------------------------------------------------------------------------
void dashboardPage(EthernetClient &client) {
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Content-Type: text/html"));
client.println(F("Connnection: close"));
client.println();
client.println(F("<!DOCTYPE HTML><html><style>body {background-image: url(\"https://geloautomationworks.files.wordpress.com/2023/09/bg-2.png\"); background-size: 100vw 100vh; background-repeat: no-repeat; text-align: center; font-family: \"Trebuchet MS\", Arial;}</style>"));
client.println(F("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"));
client.println(F("<script>"));
client.println(F("setInterval(function()"));
client.println(F("{"));
client.println(F("getReadingsVals();"));
client.println(F("}, 3000);"));
client.println(F("function getReadingsVals()"));
client.println(F("{"));
client.println(F("var xhttp = new XMLHttpRequest();"));
client.println(F("xhttp.onreadystatechange = function()"));
client.println(F("{"));
client.println(F("if(this.readyState == 4 && this.status == 200)"));
client.println(F("{"));
client.println(F("document.getElementById(\"ReadingsVals\").innerHTML = this.responseText;"));
client.println(F("}"));
client.println(F("};"));
client.println(F("xhttp.open(\"GET\", \"readReadings\", true);"));
client.println(F("xhttp.send();"));
client.println(F("var xhttp = new XMLHttpRequest();"));
client.println(F("xhttp.onreadystatechange = function()"));
client.println(F("{"));
client.println(F("if(this.readyState == 4 && this.status == 200)"));
client.println(F("{"));
client.println(F("document.getElementById(\"BatteryVals\").innerHTML = this.responseText;"));
client.println(F("}"));
client.println(F("};"));
client.println(F("xhttp.open(\"GET\", \"readBattery\", true);"));
client.println(F("xhttp.send();"));
client.println(F("}"));
client.println(F("</script>"));
client.println(F("</head>"));
client.println(F("<body>"));
client.println(F("<h1>Automated Remote Monitoring and Control of Power and Temperature</h1>"));
client.println(F("<h1>applying IoT</h>"));
client.println(F("<br>"));
client.println(F("</br>"));
client.println(F("<h3>SERVER TEMPERATURE</h3>"));
client.println(F("<br>"));
client.println(F("<span id =\"ReadingsVals\">"));
client.println(F(""));
client.println(F("</span>"));
client.println(F("<a href=\"/ACON\"><button>ON</button></a>  "));
client.println(F("<a href=\"/ACOFF\"><button>OFF</button></a>"));
client.println(F("<br>"));
client.println(F("</br>"));
client.println(F("<h3>SERVER BATTERY LEVEL</h3>"));
client.println(F("<br>"));
client.println(F("<span id =\"BatteryVals\">"));
client.println(F(""));
// Generates buttons to control the relay
client.println(F("</span>"));
client.println(F("<a href=\"/DCON\"><button>ON</button></a>  "));
client.println(F("<a href=\"/DCOFF\"><button>OFF</button></a></center>"));
client.println(F("<br>"));
client.println(F("</br>"));
client.println(F("<center><a href=\"/\">Refresh</a>"));
client.println(F("</body></html>"));
}
void SendAuthentificationpage(EthernetClient &client)
{
client.println(F("HTTP/1.1 401 Authorization Required"));
client.println(F("WWW-Authenticate: Basic realm=\"Secure Area\""));
client.println(F("Content-Type: text/html"));
client.println("Connnection: close");
client.println();
client.println(F("<!DOCTYPE HTML>"));
client.println(F("<HTML> <HEAD> <TITLE>Error</TITLE>"));
client.println(F(" </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML>"));
}
void AJAX_request(EthernetClient &client)
{
client.println(F("<font face =\"radioland\", size = \"15\", color= \"black\">"));
client.println(temp);
client.println(F("°C"));
client.println(F("</font>"));
client.println(F("</br>"));
if(relay1State1 == "ON"){
client.println(F("Aircon is <font color=\"green\"’>ON</font>"));
}
else if(relay1State1 == "OFF") {
client.println(F("Aircon is <font color=\"red\">OFF</font>"));
}
client.println(F("<br>"));
client.println(F("</br>"));
}
void BATT_request(EthernetClient &client)
{
client.println(F("<font face =\"radioland\", size = \"15\", color= \"black\">"));
client.println(in_voltage);
client.println(F("V"));
client.println(F("</font>"));
client.println(F("</br>"));
if(relay2State2 == "ON") {
client.println(F("Battery is <font color=\"green\">CHARGING</font>"));
}
else if(relay2State2 == "OFF") {
client.println(F("Battery is <font color=\"red\">NOT CHARGING</font>"));
}
client.println(F("<br>"));
client.println(F("</br>"));
}
void setup()
{
// For GSM
Serial.begin(9600);
mySerial.begin(9600);
Serial.println("Setup starts.");
mySerial.println("AT"); // Initialize the module
delay(1000);
mySerial.println("AT+CMGF=1"); // Set SMS mode to text
delay(1000);
mySerial.println("AT+CNMI=1,2,0,0,0"); // Configure how SMS notifications are handled
delay(1000);
mySerial.println("AT+CSMP=49,167,0,0");
delay(1000);
// Clear SIM800L's buffer.
while (mySerial.available()) mySerial.read();
allowedNumber = getPhoneNumberFromPhonebook();
Serial.println("Setup ends.");
//---------------------------------------------------------------------------------------
//For ethernet
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
//---------------------------------------------------------------------------------------
//For relay pins
pinMode(ChgRlyCon, OUTPUT);
digitalWrite(ChgRlyCon, LOW);
pinMode(TempCon, OUTPUT);
digitalWrite(TempCon, LOW);
//---------------------------------------------------------------------------------------
}
//-------------------------------------------------------------------------------------------
void loop() {
//----GSM------------------------------------------------------------------------------------
if (mySerial.available())
Serial.write(mySerial.read());
if (Serial.available())
mySerial.write(Serial.read());
// listen for incoming clients
//------------------------------------------------------------------------------------------
//----TEMP SENSOR---------------------------------------------------------------------------
sensors.requestTemperatures(); // Send the command to get temperatures
temp = sensors.getTempCByIndex(0);
sensors.requestTemperatures(); // Send the command to get temperatures
temp = sensors.getTempCByIndex(0);
//------------------------------------------------------------------------------------------
//----BATT SENSOR---------------------------------------------------------------------------
// Why "byIndex"?
// You can have more than one IC on the same bus.
// 0 refers to the first IC on the wire
// Read the Analog Input
adc_value = analogRead(SIGNAL_PIN);
// Determine voltage at ADC input
adc_voltage = (adc_value * ref_voltage) / 1024.0;
// Calculate voltage at divider input
in_voltage = adc_voltage / (R2 / (R1 + R2)) ;
//------------------------------------------------------------------------------------------
//----FOR GSM--------------------------------------------------------------------------------------
String phoneNumber = "";
String command = "";
String incoming = "";
if (mySerial.available()) {
incoming = mySerial.readStringUntil('\n');
Serial.print("Init read: "); Serial.println(line);
if (incoming.startsWith("+CMT:")) { // Check if a new SMS is received
phoneNumber = extractPhoneNumber(incoming); // Extract the phone number.
command = mySerial.readStringUntil('\n'); // This will read the actual message.
Serial.print("Sender: "); Serial.println(phoneNumber);
Serial.print("Command: "); Serial.println(command);
if (allowedNumber == phoneNumber) {
command.trim();
Serial.print("Authorized! ");
if (command.equalsIgnoreCase("AC ON")) {
digitalWrite(TempCon, HIGH);
relay1State1 = "ON";
sendSMS("AC has been turned on via text");
}
else if (command.equalsIgnoreCase("AC OFF")) {
digitalWrite(TempCon, LOW);
relay1State1 = "OFF";
sendSMS("AC has been turned ooff via text");
}
else if (command.equalsIgnoreCase("DC ON")) {
digitalWrite(ChgRlyCon, HIGH);
relay2State2 = "ON";
sendSMS("Charging of battery has been turned on via text");
}
else if (command.equalsIgnoreCase("DC OFF")) {
digitalWrite(ChgRlyCon, LOW);
relay2State2 = "OFF";
sendSMS("Charging of battery has been turned off via text");
}
else {
sendSMS("Unknown command: " + command);
}
}
}
}
//------------------------------------------------------------------------------------------------
//----BASIC AUTHENTICATION------------------------------------------------------------------
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
memset(linebuf, 0, sizeof(linebuf));
charcount = 0;
authentificated = false;
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
linebuf[charcount] = c;
if (charcount < sizeof(linebuf) - 1) charcount++;
Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the HTTP request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// decide what to do
if (strstr(linebuf, "Authorization: Basic") > 0 && strstr(linebuf, "YWRtaW46RGF5d2Fsa2VyQDAwMg==") > 0)
authentificated = true;
if (strstr(linebuf, "readReadings") > 0) {
AJAX_request(client);
}
else if (strstr(linebuf, "readBattery") > 0) {
BATT_request(client);
}
else if (authentificated) {
dashboardPage(client);
if (strstr(linebuf, "GET /ACON") > 0 && authentificated) {
digitalWrite(TempCon, HIGH);
relay1State1="ON";
sendSMS("AC HAS BEEN TURNED ON BY ADMIN");
}
else if (strstr(linebuf, "GET /ACOFF") > 0 && authentificated) {
digitalWrite(TempCon, LOW);
relay1State1="OFF";
sendSMS("AC HAS BEEN TURNED OFF BY ADMIN");
}
else if (strstr(linebuf, "GET /DCON") > 0 && authentificated) {
digitalWrite(ChgRlyCon, HIGH);
relay2State2="ON";
sendSMS("CHARGING THE BATTERY HAS BEEN CONNECTED BY ADMIN");
}
else if (strstr(linebuf, "GET /DCOFF") > 0 && authentificated) {
digitalWrite(ChgRlyCon, LOW);
relay2State2="OFF";
sendSMS("CHARGING THE BATTERY HAS BEEN DISCONNECTED BY ADMIN");
}
}
else {
SendAuthentificationpage(client);
}
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
} else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
}
//------------------------------------------------------------------------------------------
//----TEMP CONDITION------------------------------------------------------------------------
if( temp >= 35){
digitalWrite(TempCon, HIGH);
relay1State1 = "ON";
if(passFlag == 0){
sendSMS("AIRCON HAS BEEN TURNED ON");
passFlag = 1;
passFlag1 = 0;
}
}
if (temp <= 29){
digitalWrite(TempCon, LOW);
relay1State1 = "OFF";
if(passFlag1 == 0){
sendSMS("AIRCON HAS BEEN TURNED OFF");
passFlag1 = 1;
passFlag = 0;
}
//------------------------------------------------------------------------------------------
//----BATT CONDITION------------------------------------------------------------------------
//--------------------------- bms 0, batt lt 13.4v--------------
if(in_voltage >= 15){
digitalWrite(ChgRlyCon, LOW);
relay2State2 = "OFF";
if(passFlag2 == 0){
sendSMS("CHARGING THE BATTERY HAS BEEN DISCONNECTED");
passFlag2 = 1;
passFlag3 = 0;
}
}
//--------------------------- bms 0, batt is charged at 13.4V -------
if(in_voltage <= 6){
digitalWrite(ChgRlyCon, HIGH);
relay2State2 = "ON";
if(passFlag3 == 0){
sendSMS("CHARGING THE BATTERY HAS BEEN CONNECTED");
passFlag3 = 1;
passFlag2 = 0;
}
}
}
}
//----------------------------------------------------------------------------------------------
String getPhoneNumberFromPhonebook() {
String response = "";
mySerial.println("AT+CPBR=1"); // Read the first entry in phonebook
delay(1000);
if (mySerial.available()) {
response = mySerial.readStringUntil('\n');
}
response = mySerial.readStringUntil('\n');
response.trim();
if (response.startsWith("+CPBR:")) {
response = extractPhoneNumber(response);
return response;
}
else {
return "No Valid contact."; // Return empty string if phonebook entry not found
}
}
void sendSMS(String message) {
mySerial.print("AT+CMGS=\"");
mySerial.print(allowedNumber);
mySerial.println("\"");
delay(500);
mySerial.print(message);
delay(500);
mySerial.write(26); // Send Ctrl+Z character to indicate the end of the message
// Clear SIM800L's buffer.
while (mySerial.available()) mySerial.read();
delay(1000);
}
String extractPhoneNumber(String line) {
int firstQuote = line.indexOf('"');
int secondQuote = line.indexOf('"', firstQuote + 1);
String phoneNumber = line.substring(firstQuote + 1, secondQuote);
// Replace "+63" with "0"
phoneNumber.replace("+63", "0");
return phoneNumber;
}
Thank you.