Hello all,
I would like to control the arduino nano with esp8266 via serial (rx/tx)
Im uploaded the arduinoESP IDE webserver exampe to the ESP-01, but changed GPIO control to Serial.println.
At the arduino (nano) side, im uploaded a basic Serial.readString program.
My problem is, when arduino nano serial monitor print the ESP string, its print 3 time.
I mean ESP send oncethis:
Serial.println("on"),
then Arduino serial monitor show this:
on
on
on
Any idea?
Arduino code:
int ledPin = 13;
String readString;
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
}
void loop() {
while (Serial.available()) {
delay(3);
char c = Serial.read();
readString += c;
}
if (readString.length() >0) {
Serial.println(readString);
if (readString == "on")
{
digitalWrite(ledPin, HIGH);
}
if (readString == "off")
{
digitalWrite(ledPin, LOW);
}
readString="";
}
}
ESP code:
#include <ESP8266WiFi.h>
const char* ssid = "***";
const char* password = "***";
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
// prepare GPIO2
pinMode(2, OUTPUT);
digitalWrite(2, 0);
// 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(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
//Serial.println("new client");
while(!client.available()){
delay(1);
}
String req = client.readStringUntil('\r');
//Serial.println(req);
client.flush();
// Match the request
int val;
if (req.indexOf("/gpio/0") != -1){
val = 0;
Serial.println("on");
}
else if (req.indexOf("/gpio/1") != -1){
val = 1;
Serial.println("off");
}
else {
//Serial.println("invalid request");
client.stop();
return;
}
// Set GPIO2 according to the request
digitalWrite(2, val);
client.flush();
// Prepare the response
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
s += (val)?"high":"low";
s += "</html>\n";
// Send the response to the client
//client.print(s);
//delay(1);
//Serial.println("Client disonnected");
}