Communication esp01 et Arduino Mega

Bonjour,
je voudrais faire communiquer mon mega avec un esp01 via serial.
Jusque la, rien de bien spécial, à part que les SSID et pass changent régulièrement et que c'est impossible pour moi de faire un changement de sketch à chaque fois.

La solution (selon moi) serait d'utiliser un wifimanager.

brancheent entre esp et mega:
VCC-3,3v
MC-Pd - 3,3v
Gnd - Gnd
Tx - Rx
RX - Tx

l'esp fonctionne seul sans problèmes et le mega aussi (en insérant en manuel des ssid et pass.

Quelle est l'erreur, la solution, le coup de pouce,.... que sais-je?????

sketch esp:

#include <FS.h>          // this needs to be first, or it all crashes and burns...
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager

/**************************************************************************************
 * this example shows how to set a static IP configuration for the ESP
 * although the IP shows in the config portal, the changes will revert 
 * to the IP set in the source file.
 * if you want the ability to configure and persist the new IP configuration
 * look at the FS examples, which save the config to file
 *************************************************************************************/
 
//default custom static IP
//char static_ip[16] = "10.0.1.59";
//char static_gw[16] = "10.0.1.1";
//char static_sn[16] = "255.255.255.0";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println();

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;

  //reset settings - for testing
  //wifiManager.resetSettings();

  //set static ip
  //block1 should be used for ESP8266 core 2.1.0 or newer, otherwise use block2

  //start-block1
  //IPAddress _ip,_gw,_sn;
  //_ip.fromString(static_ip);
  //_gw.fromString(static_gw);
  //_sn.fromString(static_sn);
  //end-block1

  //start-block2
  IPAddress _ip = IPAddress(192, 168, 0, 150);
  IPAddress _gw = IPAddress(192, 168, 0, 1);
  IPAddress _sn = IPAddress(255, 255, 255, 0);
  //end-block2
  
  wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);


  //tries to connect to last known settings
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP" with password "password"
  //and goes into a blocking loop awaiting configuration
  if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
    Serial.println("failed to connect, we should reset as see if it connects");
    delay(3000);
    ESP.restart();
    delay(5000);
  }

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");


  Serial.println("local ip");
  Serial.println(WiFi.localIP());
}

void loop() {
  // put your main code here, to run repeatedly:


}

Sketch mega:



//--- SETTINGS ------------------------------------------------
const char* ssid = "";        // WIFI network SSID
const char* password = "";       // WIFI network PASSWORD
int port=8000;                             // Virtuino default Server port
const char* serverIP = "";    // The three first numbers have to be the same with the router IP
//-------------------------------------------------------------

//-------------VirtuinoCM  Library and settings --------------
#include "VirtuinoCM.h"
VirtuinoCM virtuino;               
#define V_memory_count 32          // the size of V memory. You can change it to a number <=255)
float V[V_memory_count];           // This array is synchronized with Virtuino V memory. You can change the type to int, long etc.

boolean debug = true;              // set this variable to false on the finale code to decrease the request time.


//============================================================== setup
//==============================================================
void setup() {
  if (debug) {
    Serial.begin(9600);
    while (!Serial) continue;
  }
  
  Serial1.begin(9600);     // or 115200
  Serial1.setTimeout(50);

  virtuino.begin(onReceived,onRequested,256);  //Start Virtuino. Set the buffer to 256. With this buffer Virtuino can control about 28 pins (1 command = 9bytes) The T(text) commands with 20 characters need 20+6 bytes
  //virtuino.key="1234";                       //This is the Virtuino password. Only requests the start with this key are accepted from the library

  connectToWiFiNetwork();
   
  pinMode(4, OUTPUT);            // On Virtuino panel add a button to control this pin
  pinMode(13, OUTPUT);            // On Virtuino panel add a button to control this pin
  pinMode(6, OUTPUT);             
  pinMode(7, INPUT);             // On Virtuino panel add a led to get the state of this pin
  }

//============================================================== loop
//==============================================================
void loop() {
  virtuinoRun();        // Necessary function to communicate with Virtuino. Client handler

  
  
  vDelay(1000);     // This is an example of the recommended delay function. Remove this if you don't need
}




//================================================ connectToWiFiNetwork
void connectToWiFiNetwork(){
    Serial.println("Connecting to "+String(ssid));
    while (Serial1.available()) Serial1.read();
    Serial1.println("AT+GMR");       // print firmware info
    waitForResponse("OK",1000);
    Serial1.println("AT+CWMODE=1");  // configure as client
    waitForResponse("OK",1000);
    Serial1.print("AT+CWJAP=\"");    // connect to your WiFi network
    Serial1.print(ssid);
    Serial1.print("\",\"");
    Serial1.print(password);
    Serial1.println("\"");
    waitForResponse("OK",10000);
    Serial1.print("AT+CIPSTA=\"");   // set IP
    Serial1.print(serverIP);
    Serial1.println("\"");   
    waitForResponse("OK",5000);
    Serial1.println("AT+CIPSTA?");
    waitForResponse("OK",3000); 
    Serial1.println("AT+CIFSR");           // get ip address
    waitForResponse("OK",1000);
    Serial1.println("AT+CIPMUX=1");         // configure for multiple connections   
    waitForResponse("OK",1000);
    Serial1.print("AT+CIPSERVER=1,");
    Serial1.println(port);
    waitForResponse("OK",1000);
}


//============================================================== onCommandReceived
//==============================================================
/* This function is called every time Virtuino app sends a request to server to change a Pin value
 * The 'variableType' can be a character like V, T, O  V=Virtual pin  T=Text Pin    O=PWM Pin 
 * The 'variableIndex' is the pin number index of Virtuino app
 * The 'valueAsText' is the value that has sent from the app   */
 void onReceived(char variableType, uint8_t variableIndex, String valueAsText){     
    if (variableType=='V'){
        float value = valueAsText.toFloat();        // convert the value to float. The valueAsText have to be numerical
        if (variableIndex<V_memory_count) V[variableIndex]=value;              // copy the received value to arduino V memory array
    }
}

//==============================================================
/* This function is called every time Virtuino app requests to read a pin value*/
String onRequested(char variableType, uint8_t variableIndex){     
    if (variableType=='V') {
    if (variableIndex<V_memory_count) return  String(V[variableIndex]);   // return the value of the arduino V memory array
  }
  return "";
}

 //==============================================================
  void virtuinoRun(){
  if(Serial1.available()){
        virtuino.readBuffer = Serial1.readStringUntil('\n');
        if (debug) Serial.print('\n'+virtuino.readBuffer);
        int pos=virtuino.readBuffer.indexOf("+IPD,");
        if (pos!=-1){
              int connectionId = virtuino.readBuffer.charAt(pos+5)-48;  // get connection ID
              int startVirtuinoCommandPos = 1+virtuino.readBuffer.indexOf(":");
              virtuino.readBuffer.remove(0,startVirtuinoCommandPos);
              String* response= virtuino.getResponse();    // get the text that has to be sent to Virtuino as reply. The library will check the inptuBuffer and it will create the response text
              if (debug) Serial.println("\nResponse : "+*response);
              if (response->length()>0) {
                String cipSend = "AT+CIPSEND=";
                cipSend += connectionId;
                cipSend += ",";
                cipSend += response->length();
                cipSend += "\r\n";
                while(Serial1.available()) Serial1.read();    // clear Serial1 buffer 
                for (int i=0;i<cipSend.length();i++) Serial1.write(cipSend.charAt(i));
                if (waitForResponse(">",1000)) Serial1.print(*response);
                waitForResponse("OK",1000);
              }
              Serial1.print("AT+CIPCLOSE=");Serial1.println(connectionId);
         }// (pos!=-1)
           
  } // if Serial1.available
        
}

 
//=================================================== waitForResponse
boolean waitForResponse(String target1,  int timeout){
    String data="";
    char a;
    unsigned long startTime = millis();
    boolean rValue=false;
    while (millis() - startTime < timeout) {
        while(Serial1.available() > 0) {
            a = Serial1.read();
            if (debug) Serial.print(a);
            if(a == '\0') continue;
            data += a;
        }
        if (data.indexOf(target1) != -1) {
            rValue=true;
            break;
        } 
    }
    return rValue;
}


 //============================================================== vDelay
  void vDelay(int delayInMillis){long t=millis()+delayInMillis;while (millis()<t) virtuinoRun();}

Les deux fonctionnent séparément mais tu ne dis pas ce qui ne va pas lorsqu'ils sont connectés.

Lequel alimente l'autre ?

Quel process avez vous en tête pour changer le mot de passe?

l'alim se fait via le mega. désolé de l'oubli.
lorsqu'ils sont connectés entre eux, le mega n'a pas l'air de se connecter au wifi.
le serial me renvoie un "Connection......." sans plus.

pour changer le mot de passer, j'utilise wifimanager, il lance un autoconnectap wifi, ce qui me permet de choisir le réseau wifi via gsm ou pc via ip 192.168.4.1.

Merci

OK - je ne connais pas "virtuino", si c'est cela qui doit gérer la communication
à quoi sert le MEGA ? pourquoi ne pas faire tout sur un ESP (un peu plus puissant que le 01 éventuellement)

Virtuino en soi, n'est qu'une interface de communication entre appli gsm et mega.
Le mega est utilisé pour 4 relais, horloge, 2 phidgets 1130, 3 sondes. (4 ports analogiques)
le sketch en lui-même fait quasi 50k et les variables 3k.
en plus de cela une bonne dizaine d'eeproms.
Serait-il possible d'utiliser une autre board?

donc 4 pins numériques, 4 pins analogiques + de l'I2C pour l'horloge je suppose. ça rentrerait sans souci sur un ESP32 sans doute

une bonne dizaine d'eeproms

Je ne suis pas sûr de ce que vous voulez dire par cela.

que j'ai 10 valeurs a stocker en eeprom.

OK - donc pas de souci avec le stockage en flash sur ESP
plus on évite la multiplication de cartes qui doivent se parler entre elles, mieux on se porte généralement

l'esp pour le moment ne fonctionne que pour utiliser la Connection wifi et stocker le SSID et password du wifi. (mais peut-être possible autrement)?

A quoi sert la connexion Wi-Fi alors?

Elle sert de communication entre mega/esp et gsm

Pour résumer:

L'ESP fait tourner un sketch "vide" qui permet juste à l'ESP de rejoindre le réseau WiFi en utilisant WiFiManager

Le MEGA essaye de balancer des commandes AT dans la fonction connectToWiFiNetwork() à quelque chose connecté sur Serial1

➜ Qu'est-ce qui est connecté sur Serial1 ? (ESP-01, GSM?)

ici on dirait que la liaison avec la Mega est sur Serial ? (et peut-être pas assez de jus pour alimenter correctement l'ESP-01)

l'esp est connecté sur le serial1 en effet.
je me posais juste la meme question en effet.
je vais voir pour alimenter l'esp via une autre source.

le pourquoi du wifimanager dans l'esp, c'est pour justement arriver à modifier le SSID et pass en cas de changement de wifi.

Mais si l'ESP est configuré avec un sketch "Arduino", il n'a plus l'OS qui permet de gérer des commandes AT donc balancer des trucs sur Serial1 n'a pas d'effet...

ok, il ne me reste plus qu'a chercher pour implémenter les 2 sketchs en 1 :sob:

pour moi le sujet peut être clos.
merci pour votre aide, tout fonctionne comme je le veux.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.