jueves, 9 de junio de 2016

Configuracion Basica de la conexion para Arduino y ESP8266 a la RED



En este tutorial vamos a aclarar una cuestion muy basica que nos permitirá aplicar los ejemplos o cualquier codigo que queramos tanto en Arduino como en ESP8266, puesto que la configuracion de la interfaz de comunicaciones (ethernet o Wi-Fi) se define por separado de lo que serian los diferentes Slots o Elementos que vaya a contener el nodo, empezamos con los ejemplos que es como mas claramente se puede entender.


Para una comprension mas profunda de la estructura es recomendable leer esta Entrada:
Estructura del código Souliss

 Todos estos ejemplos tratan de un Nodo Gateway, es decir, el que sera el nodo principal de nuestra Red Souliss y del que dependerán los demas.

Este es un ejemplo basico para Arduino:
/**************************************************************************
    Souliss - Hello World
    
    This is the basic example, control one LED via a push-button or Android
    using SoulissApp (get it from Play Store).  
    
    Run this code on one of the following boards:
      - Arduino Ethernet (W5100) 
      - Arduino with Ethernet Shield (W5100)
      
    As option you can run the same code on the following, just changing the
    relevant configuration file at begin of the sketch
      - Arduino with W5200 Ethernet Shield
      - Arduino with W5500 Ethernet Shield
        
***************************************************************************/

// Let the IDE point to the Souliss framework
#include "SoulissFramework.h"

// Configure the framework
#include "bconf/StandardArduino.h"          // Use a standard Arduino
#include "conf/ethW5100.h"                  // Ethernet through Wiznet W5100
#include "conf/Gateway.h"                   // The main node is the Gateway, we have just one node
#include "conf/Webhook.h"                   // Enable DHCP and DNS

// Include framework code and libraries
#include <SPI.h>

/*** All configuration includes should be above this line ***/ 
#include "Souliss.h"

// This identify the number of the LED logic
#define MYLEDLOGIC          0               

void setup()
{   
    Initialize();

    // Get the IP address from DHCP
    GetIPAddress();                          
    SetAsGateway(myvNet_dhcp);       // Set this node as gateway for SoulissApp  
    
    Set_SimpleLight(MYLEDLOGIC);        // Define a simple LED light logic
    

    pinMode(9, OUTPUT);                 // Power the LED
}

void loop()
{ 
    // Here we start to play
    EXECUTEFAST() {                     
        UPDATEFAST();   
        
        FAST_50ms() {   // We process the logic and relevant input and output every 50 milliseconds
            Logic_SimpleLight(MYLEDLOGIC);                          // Drive the LED as per command
            DigOut(9, Souliss_T1n_Coil, MYLEDLOGIC);                // Use the pin9 to give power to the LED according to the logic
        } 
              
        // Here we handle here the communication with Android, commands and notification
        // are automatically assigned to MYLEDLOGIC
        FAST_GatewayComms();                                        
        
    }
} 
Y este seria el mismo Ejemplo para el ESP8266:
/**************************************************************************
    Souliss - Hello World for Expressif ESP8266
    
    This is the basic example, create a software push-button on Android
    using SoulissApp (get it from Play Store).  
    
    Load this code on ESP8266 board using the porting of the Arduino core
    for this platform.
        
***************************************************************************/

// Let the IDE point to the Souliss framework
#include "SoulissFramework.h"

// Configure the framework
#include "bconf/MCU_ESP8266.h"              // Load the code directly on the ESP8266
#include "conf/Gateway.h"                   // The main node is the Gateway, we have just one node
#include "conf/IPBroadcast.h"

// **** Define the WiFi name and password ****
#define WIFICONF_INSKETCH
#define WiFi_SSID               "mywifi"
#define WiFi_Password           "mypassword"    

// Include framework code and libraries
#include <ESP8266WiFi.h>
#include <EEPROM.h>

/*** All configuration includes should be above this line ***/ 
#include "Souliss.h"

// This identify the number of the LED logic
#define MYLEDLOGIC          0               

// **** Define here the right pin for your ESP module **** 
#define OUTPUTPIN   5

void setup()
{   
    Initialize();

    // Connect to the WiFi network and get an address from DHCP
    GetIPAddress();                           
    SetAsGateway(myvNet_dhcp);       // Set this node as gateway for SoulissApp  
 
    Set_SimpleLight(MYLEDLOGIC);        // Define a simple LED light logic
 
    pinMode(OUTPUTPIN, OUTPUT);         // Use pin as output 
}

void loop()
{ 
    // Here we start to play
    EXECUTEFAST() {                     
        UPDATEFAST();   
        
        FAST_50ms() {   // We process the logic and relevant input and output every 50 milliseconds
            Logic_SimpleLight(MYLEDLOGIC);
            DigOut(OUTPUTPIN, Souliss_T1n_Coil,MYLEDLOGIC);
        } 
              
        // Here we handle here the communication with Android
        FAST_GatewayComms();                                        
    }
} 
Lo que se puede ver resaltado en ambos ejemplos son las diferencias en la configuracion para cargar el Codigo en un Arduino o un ESP8266, son bastante evidentes.

Quedaria por indicar tambien un ejemplo para Arduino + ENC28J60:

/**************************************************************************
    Souliss - Hello World
    
    This is the basic example, control one LED via a push-button or Android
    using SoulissApp (get it from Play Store).  
    
    Run this code on one of the following boards:
      - Arduino with ENC28J60 Ethernet Shield
        
***************************************************************************/

// Let the IDE point to the Souliss framework
#include "SoulissFramework.h"

// Configure the framework
#include "bconf/StandardArduino.h"          // Use a standard Arduino
#include "conf/ethENC28J60.h"               // Ethernet through Wiznet W5100
#include "conf/Gateway.h"                   // The main node is the Gateway, we have just one node

// Include framework code and libraries
#include <SPI.h>

/*** All configuration includes should be above this line ***/ 
#include "Souliss.h"

// This identify the number of the LED logic
#define MYLEDLOGIC          0               

// Define the network configuration according to your router settings
uint8_t ip_address[4]  = {192, 168, 1, 77};
uint8_t subnet_mask[4] = {255, 255, 255, 0};
uint8_t ip_gateway[4]  = {192, 168, 1, 1};
#define myvNet_address  ip_address[3]       // The last byte of the IP address (77) is also the vNet address
#define myvNet_subnet   0xFF00

void setup()
{   
    Initialize();

     // Set network parameters
    Souliss_SetIPAddress(ip_address, subnet_mask, ip_gateway);
    SetAsGateway(myvNet_address);                                   // Set this node as gateway for SoulissApp  
     
    Set_SimpleLight(MYLEDLOGIC);        // Define a simple LED light logic
    

    pinMode(9, OUTPUT);                 // Power the LED
}

void loop()
{ 
    // Here we start to play
    EXECUTEFAST() {                     
        UPDATEFAST();   
        
        FAST_50ms() {   // We process the logic and relevant input and output every 50 milliseconds
            DigIn(2, Souliss_T1n_ToggleCmd, MYLEDLOGIC);            // Use the pin2 as ON/OFF toggle command
            Logic_SimpleLight(MYLEDLOGIC);                          // Drive the LED as per command
            DigOut(9, Souliss_T1n_Coil, MYLEDLOGIC);                // Use the pin9 to give power to the LED according to the logic
        } 
              
        // Here we handle here the communication with Android, commands and notification
        // are automatically assigned to MYLEDLOGIC
        FAST_GatewayComms();                                        
        
    }
} 

En este caso, dado que la ENC28J60 no permite DHCP es necesario configurar la IP manualmente como se muestra resaltado, se puede ver tambien que en caso de ser DHCP se utiliza el comando GetIPAddress();  para obtener la direccion IP y en caso de no ser asi se utiliza el comando:
Souliss_SetIPAddress(ip_address, subnet_mask, ip_gateway); Esto tambien nos sirve en caso de querer configurar un Arduino + W5100 o un ESP8266 con IP estatica.

Como conclusion queda decir que estas no son las unicas posibilidades de configuracion de la Red, existen multiples posiblidades, aqui hemos explicado las mas habituales, para que todo quede mas documentado en una misma entrada adjunto aqui los enlaces al Github, esto es importante para aprender a navegar por el codigo y los archivos de Souliss, en cuyos comentarios podemos encontrar documentados sus usos y comandos:

Ejemplos usados en esta entrada:
https://github.com/souliss/souliss/blob/friariello/examples/ethernet/e01_HelloWorld/e01_HelloWorld.ino
https://github.com/souliss/souliss/blob/friariello/examples/WiFi/e01_Hello_ESP8266/e01_Hello_ESP8266.ino
https://github.com/souliss/souliss/blob/friariello/examples/ethernet/e01_HelloWorld_uIP/e01_HelloWorld_uIP.ino

Esta es la carpeta con las diferentes Placas y Microprocesadores Sopotados:
https://github.com/souliss/souliss/tree/friariello/bconf

Y las diferentes interfaces de comunicacion:
https://github.com/souliss/souliss/blob/friariello/examples/ethernet/e01_HelloWorld_uIP/e01_HelloWorld_uIP.ino

Comentarios, sugerencias o preguntas aqui abajo. :P Salu2

14 comentarios:

  1. Se puede poner ip fija a un ESP?? Gracias

    ResponderEliminar
    Respuestas
    1. Si, tal y como ves en la entrada "Esto tambien nos sirve en caso de querer configurar un Arduino + W5100 o un ESP8266 con IP estatica." :P :)

      Eliminar
  2. Este comentario ha sido eliminado por el autor.

    ResponderEliminar
  3. Puedes poner un ejemplo de una instalación souliss con 3 nodos utilizando solo ESP8266 o darme el link a algún ejemplo con esta configuración.
    Estoy haciendo pruebas y no consigo conectar los nodos.

    Saludos!

    ResponderEliminar
    Respuestas
    1. Hola Mefizto, si tienes dudas tambien puedes pasarte por el foro y lo vemos :P
      https://groups.google.com/forum/#!forum/souliss-es

      En cualquier caso aqui tienes los ejemplos para el ESP, uno de ellos debe ser el Gateway, con lo que tendrias que ponerle este ejemplo:
      https://github.com/souliss/souliss/blob/friariello/examples/WiFi/e01_Hello_ESP8266/e01_Hello_ESP8266.ino

      Para añadir un segundo Peer simplemente añade detras de la linea 49:

      SetAsPeerNode(0xAB03, 2);

      Con respecto a los Peer tienes que utilizar este ejemplo:
      https://github.com/souliss/souliss/blob/friariello/examples/WiFi/e01_Peer_ESP8266/e01_Peer_ESP8266.ino

      Y para el segundo peer (tercer nodo) cambia la linea 46 de:
      SetAddress(0xAB02, 0xFF00, 0xAB01);
      a SetAddress(0xAB03, 0xFF00, 0xAB01);

      En todos los casos recuerda poner el nombre de tu wifi y contraseña al principio porque estos ejemplos no tienen el webconfig habilitado :P

      Salu2

      Eliminar
    2. Gracias Juan, intenté siguiendo los tutoriales, pero no logro conectar los nodos, te dejo un link con los sketches y unas imágenes de la app:

      https://drive.google.com/drive/folders/0B6PAFrGZTW5NU1BMcHFXVmVJX2s?usp=sharing

      Eliminar
    3. Segun veo en las imagenes 001533 y 002720 aparecen los 3 nodos con 3 dispositivos. Ya deberia funcionar :P no?

      Eliminar
    4. El nodo I me aparece vacio y el II me aparece el control de la salida digital pero no responde, ¿Qué crees que pueda estar fallando?

      Eliminar
  4. impecable Juan, todo lo que hago en Souliss es siguiendo tus pasos!! Ahora me estoy metiendo en el tema de ESP as AP para configurar wifi y luego conectarme a una wifi sin harcodear SSID ni PWD. Uso la lib WiFiManager, pero despues me complica joinear con setup de souliss. Alguna idea?

    ResponderEliminar
    Respuestas
    1. Hola "Unknown" :P
      No hace falta que te compliques con la libreria WifiManager, ya tienes un ejemplo en la libreria que habilita un webconfig para configurar SSID, PWD y mas cosas ;)

      https://github.com/souliss/souliss/blob/d9ed9bf7418fe5914ba80ddd94194c9f714c211e/examples/zeroconf/e02_WebConfig_OTA/e02_WebConfig_OTA.ino

      Salu2! y pasate por el foro si aun no lo has hecho :P

      Eliminar
  5. Hola Juan.
    Excelente trabajo el que realizas en este blog.
    Me surge una duda...usb to ttl para programar mi esp8266-12 pero no encuentro como cablearlo para programarlo. Tendrías algún esquema donde se vean las conexiones??
    Gracias de antemano

    ResponderEliminar
    Respuestas
    1. Hola, puede el cableado entre el ESP y el USB es sencillo.
      TTL <> ESP
      3.3V A VCC
      GND A GND
      RX A TX
      TX A RX

      Ademas tienes que asegurarte que el GPIO0 esta a GND para entrar en modo programacion.

      Si tienes mas dudas pasate por el foro :P

      Salu2

      Eliminar
    2. Muchas gracias!! mañana mismo lo pruebo a ver si soy capaz :)
      Un saludo

      Eliminar