Hi all,
General idea is to use my Arduino Uno project of gas sensor monitoring (simple one just MQ2 sensor display) and connect it to ESP to display data on web page on internal wifi network.
I have upload the following code to ESP and simple following code to Arduino. The ESP connects to the wifi. Displays the page with title, but no data. The pins are connected to 8 and 9 as stated in the codes. I am sure there is something wrong with serial communication, but can not figure it out.
I see on IDE serial monitor that Uno sending data, but they are not picked up by ESP.
Thank you so much for help!
---- ESP code ----
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
SoftwareSerial espSerial(8, 9); // RX, TX
const char* ssid = "*****";
const char* password = "*****";
WiFiServer server(80);
void setup() {
Serial.begin(9600);
espSerial.begin(9600);
delay(10);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
//server.on("/", handleRoot);
server.begin();
Serial.println("Server started");
}
void loop() {
WiFiClient client = server.available();
if (client) {
Serial.println("New client");
String currentLine = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (c == '\n') {
if (currentLine.length() == 0) {
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head><title>Sensor Data</title></head>");
client.println("<body>");
client.println("<h1>Sensor Data</h1>");
client.println("<p>");
// Read sensor data from Arduino
espSerial.println("read_sensor_data"); // Send command to Arduino
String sensorData = "";
while (espSerial.available()) {
char c = espSerial.read();
if (c != '\n') {
sensorData += c;
}
}
client.println(sensorData); // Print sensor data to web page
client.println("</p>");
client.println("</body>");
client.println("</html>");
break;
} else {
currentLine = "";
}
} else if (c != '\r') {
currentLine += c;
}
}
}
client.stop();
Serial.println("Client disconnected");
}
}
---- arduino code ----
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8, 9); // RX, TX
int sensorPin = A0;
void setup() {
Serial.begin(9600); // Initialize hardware serial for debugging
mySerial.begin(9600); // Initialize software serial for ESP8266
}
void loop() {
int sensorValue = analogRead(sensorPin);
Serial.print("sensor_data=");
Serial.println(sensorValue);
delay(1000);
}