#include <SoftwareSerial.h>
#define DEBUG true
int connectionId = -1;
SoftwareSerial esp32(7, 6);
String espmode = "3";
String SSid = "BSJ"; // enter your SSID here
String password = "batool"; // password
void wifisetup(String mode, String ssid, String pass);
void st_server(String HI, String Data, String HIcolor);
void setup() {
pinMode(12, OUTPUT);
pinMode(10, OUTPUT);
Serial.begin(9600);
esp32.begin(9600);
digitalWrite(10, LOW);
delay(1000);
wifisetup(espmode, SSid, password);
delay(1000);
digitalWrite(10, HIGH);
}
String heading = "Internet of Things";
String color = "blue";
String dataSend = "hello world";
void loop() {
digitalWrite(10, LOW);
delay(1000);
st_server(heading, dataSend, color);
delay(1000);
digitalWrite(10, HIGH);
}
// 1 - send data
String sendData(String command, const unsigned long timeout, boolean debug) {
String response = "";
if(debug){
Serial.println(command);
}
esp32.print(command);//send the read char
unsigned long time = millis();
while ((time+timeout) > millis()) {
while (esp32.available()) {
char c = esp32.read();
response += c;
}
}
if (debug) {
Serial.println(response);
}
return response;
}
// 2 - connectivity
void wifisetup(String mode, String ssid, String pass) {
sendData("AT\r\n", 2000, DEBUG); // reset
String mode0 = "AT+CWMODE=";
mode0 += mode;
mode0 += "\r\n";
sendData(mode0, 2000, DEBUG);
String ssidset = "AT+CWJAP=\"";
ssidset += ssid;
ssidset += "\",\"";
ssidset += pass;
ssidset += "\"";
ssidset += "\r\n";
sendData(ssidset, 10000, DEBUG);
delay(900);
sendData("AT+CIFSR\r\n", 4000, DEBUG);// get ip
sendData("AT+CIPMUX=1\r\n", 2000, DEBUG);//configure for multiple connections
sendData("AT+CIPSERVER=1,80\r\n", 2000, DEBUG);//turn on port 80
sendData("AT+CIPSTO=1000\r\n", 1000, DEBUG);
return;
}
// 3 - placeholder for server function
void st_server(String HI, String Data, String HIcolor) {
if(!esp32.available()){
return;
}
if(esp32.find("+IPD,")){
delay(1000);
int connectionId = (esp32.read())-48;
String webpage = "<head></head><body bgcolor=\"";
webpage += HIcolor;
webpage += "\"><h1>";
webpage += HI;
webpage += "</h1>";
String cipSend = "AT+CIPSEND=";
cipSend += connectionId;
cipSend += ",";
cipSend += webpage.length();
cipSend += "\r\n";
sendData(cipSend, 2000, DEBUG);
sendData(webpage, 2000, DEBUG);
String Data1 = Data;
cipSend = "AT+CIPSEND=";
cipSend += connectionId;
cipSend += ",";
cipSend += Data1.length();
cipSend += "\r\n";
sendData(cipSend, 1000, DEBUG);
sendData(Data1, 1000, DEBUG);
}
String closeCommand = "AT+CIPCLOSE=";
closeCommand += connectionId;//append connection id
closeCommand += "\r\n";
sendData(closeCommand, 3000, DEBUG);
return;
}