My esp8266 receives the text and sends it to the host, but when I send text from sirial, the ESP does not see it.

while (Serial.available() > 0) { read_s = Serial.readString(); } 

read_s is always empty

arduino.uno

 void setup() { Serial.begin(115200); pinMode(7,OUTPUT); pinMode(2,INPUT_PULLUP); } void loop() { boolean butt = digitalRead(2); Serial.println("est"); delay(10000); } void temp(){ } void led(){ digitalWrite(13,LOW); delay(100); digitalWrite(13,HIGH); } 

esp8266.uno

 #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> const char* ssid = ""; const char* password = ""; String wmail ="" ; String read_s; HTTPClient request; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(100); } } void loop() { while (Serial.available() > 0) { read_s = Serial.readString(); } if (WiFi.status() == WL_CONNECTED) { HTTPClient request; String get_ = "https://dj-hook.herokuapp.com/api/send?token="+wmail+"&"+"text="+ read_s;; request.begin(get_); Serial.println("send mail"); request.end(); } } 

I solved the problem by taking another arduino, but deciding to try the old one it worked

  • one
  • Questions asking for help with debugging (“why does this code not work?”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question. Questions without an explicit description of the problem are useless for other visitors. See How to create a minimal, self-contained and reproducible example . - cpp questions
  • Sorry, my esp8266 receives tex and sends it to the host, but when I send text from sirial, the ESP does not see it. while (Serial.available ()> 0) {read_s = Serial.readString (); } read_s is always empty - Yegor Avdeezh
  • @ EgorAvdeezh add the minimum reproducible example to the question using the " edit " button - cpp questions
  • If you connect ESP to your computer (for example, via a usb-uart converter), does it receive messages from it? How do you determine that the received string is empty - for the request sent? - insolor pm

1 answer 1

It looks like your serial reading cycle is incorrect:

  1. If there are no characters to read, the loop is immediately skipped, and an HTTP request is sent with an uninitialized value from the read_s variable. A variable can be anything, just not what you expect. At best, an empty string.
  2. If there are characters available for reading, you read them into a variable, while at each iteration overwriting what was read earlier (I assume that the cycle will spin faster than the data on the serial will come).

Try reading this:

 void loop() { if(Serial.available() == 0) return; // Если данных нет, сразу выходим из функции loop // Если есть данные - читаем их read_s = Serial.readString(); // Дальше уже делаем с ними что хотим ... } 

Updated

It is better to debug in stages:

  1. We are flashing the ESP8266 with a simple sketch that simply sends back what is being sent to it (I assume that you figured out how to flash this module):

     void setup() { Serial.begin(115200); } String read_s; void loop() { if(Serial.available() == 0) return; // Если данных нет, сразу выходим из функции loop // Если есть данные - читаем их read_s = Serial.readString(); // Дальше уже делаем с ними что хотим Serial.println(read_s); // Например, отправляем обратно } 
  2. After the firmware, we leave the module as it is connected to the computer, send messages through the serial monitor, if everything works, then we see how they come back:

    Screenshot 1

  3. Now you need to test the interaction between Arduino and ESP8266. We will send a serial message to the Arduino, and it will send messages to ESP8266, receive a response, send it to the computer. With such a bundle, you need to use the software serial (or Serial1, if you have an Arduino Uno, and Leonardo, for example, see the Hardware serial in the troyka wifi article ) to interact with ESP8266, over one serial interface it is impossible to interact simultaneously with two devices (a computer and a WiFi module).

    Sketch example (modified SoftwareSerialAT115200.ino example from here , the 8th pin of the Arduino should be connected to the TX pin of the wifi module, the 9th pin to the RX):

     #include <SoftwareSerial.h> // создаём объект для работы с программным Serial // и передаём ему пины TX и RX SoftwareSerial mySerial(8, 9); void setup() { Serial.begin(9600); while (!Serial) { // ждём, пока не откроется монитор последовательного порта // для того, чтобы отследить все события в программе } Serial.print("Serial init OK\r\n"); mySerial.begin(115200); } void loop() { // если приходят данные из Wi-Fi модуля - отправим их в порт компьютера if (mySerial.available()) { Serial.write(mySerial.read()); } // если приходят данные из компьютера - отправим их в Wi-Fi модуль if (Serial.available()) { mySerial.write(Serial.read()); } } 

    Screenshot 2

    If messages are not returned, check the connections between the Arduino and ESP8266.

  4. If everything is successful, we add WiFi initialization and message sending code to the WiFi firmware of the module. We flash, immediately test, without disconnecting from the computer.

     #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> const char* ssid = ""; const char* password = ""; void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); // Полчаса убил на отладку из-за отсутствия этой строки WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { Serial.println("Waiting for WiFi..."); delay(100); } Serial.println("WiFi connected."); } String token = "" ; String read_s; void loop() { if(Serial.available() == 0) return; // Если данных нет, сразу выходим из функции loop // Если есть данные - читаем их read_s = Serial.readString(); Serial.println("Got text '" + read_s + "'"); // Отчитываемся, что получили строку // Проверяем наличие соединения if(WiFi.status() != WL_CONNECTED) { Serial.println("Cannot send: no WiFi connection"); return; // Если нет соединения - выходим из функции } // Дальше код отправки запроса String url = "https://dj-hook.herokuapp.com/api/send?token=" + token + "&text=" + read_s; HTTPClient request; request.begin(url); Serial.println("send mail"); request.end(); } 
    1. Again we connect the module to Arduino as in point 3, we test. If everything works, we make changes to the Arduino firmware so that the message is sent to the WiFi module at the touch of a button, we are testing, etc. until we get the desired result.
  • prnt.sc/maos1x does not see - Yegor Avdeozh 5:56 pm
  • Do you have three wifi module or WiFi slot? - insolor
  • I have a module: amperka.ru/product/troyka-wi-fi - Egor Avdeozh
  • Clear. In the evening I will test. - insolor
  • @ YegorAvdeozh, painted in detail - insolor