Arduino Mega 2560 + ESP8266-01

Cayenne Community

Arduino Mega 2560 + ESP8266-01
Welcome to the myDevices Cayenne Community

Thousands of makers and engineers use our free tool to build projects.
Announcement Highlights

Submit your projects now to the ARDUINO + CAYENNE sponsored contest - Automation Around the Home
Video Feed

IoT Corner - The Lowdown on LoRa

Connecting the ESP8266

Using Arduino with Cayenne
Featured Projects

Check out a few projects from community members. Submit your project to be featured!

Chilibot v1.0
by paul.hellfalk

ESP8266 Light/Fan Control
by dpeters.0905

Cayenne Jukebox
by Kreggly

FishPi Aquarium
by mrmeen

Solar Pool Heater
by lutefisky

Battery Powered ESP8266
by adam

Automated Irrigation System
by jhonnatan razo

MQTT Light Show
by 0lab
Welcome to the myDevices Cayenne Community

NEW! Arduino Beta integration is out the door! Check it out here

This is a community forum for all Cayenne users to discuss their experiences, ask questions, report bugs, and request feature enhancements. We look forward to your feedback!

Frequently Asked Questions (FAQs) | Getting Started Doc | Videos

Arduino Mega 2560 + ESP8266-01

I would like some help to connect an Arduino Mega 2560 with a ESP8266-01 linked in serial 2.

I could connect on the internet using some “AT Comands”, but I could not connect in Cayenne.

Someone could help me with this.


Follow my sketch:

* ESP8266
* Arduino Mega Using Serial2
* AT commands examples for test:
* AT =====> ESP8266 returns OK
* AT+RST =====> ESP8266 restart and returns OK
* AT+GMR =====> ESP8266 returns AT Version; SDK version; id; OK
* AT+CWMODE? => ESP8266 returns mode type
* AT+CWLAP ===> ESP8266 returs close access points
* AT+CIFSR ===> ESP8266 returs designided IP
* AT+CIPMUX=1 ==>Set ESP8266 for multoples conections 
* AT+CIOBAUD=9600 ==>Change Baudrate ==> ESP8266 returs OK
* AT+CIPSERVER=1,80 ==> set modo SERVER port: 4040
* AT+CWMODE=3 ==> Conect ESP8266 ascombined mode (Access Point (2) and Server (1))
* AT+CWSAP="Acc_Point_name","password",wifi_Channel,cript# ==> ej. AT+CWSAP="ESP_8266_AP,"1234",3,0
* AT+CWJAP="SSID","password" ==> Connect to WiFi network
* Marcelo Jose Rovai 18Jan16

#define CAYENNE_PRINT Serial  // Comment this out to disable prints and save space

#include <doxygen.h>
#include <ESP8266.h>
#define esp8266 Serial2
#define CH_PD 4 
#define speed8266 19200 // This is the speed that worked with my ESP8266
//Coloque nos campos indicados o nome e senha da sua rede WiFi
#define SSID        "Vick Cristina Barcelona"
#define PASSWORD    "rafa0402"

// Token de Autenticação do Cayenne Mydevices
char token[] = "27hmhv6grc";
//Cria objeto de conexão wifi com o módulo, usando a Serial1 do Mega.
ESP8266 wifi(Serial2);
void setup(void)
digitalWrite(CH_PD,HIGH); //setado em ALTO - operacao normal

esp8266.begin (speed8266); 
//reset8266(); // Pin CH_PD need a reset before start communication

Serial.println("Iniciando Setup.");

Serial.print("Versao de Firmware ESP8266: ");
//A funcao wifi.getVersion() retorna a versao de firmware informada pelo modulo no inicio da comunicacao
//Vamos setar o modulo para operar em modo Station (conecta em WiFi) e modo AP (é um ponto de WiFi tambem)
if (wifi.setOprToStationSoftAP()) {
    Serial.println("Station e AP OK.");
} else {
    Serial.println("Erro em setar Station e AP.");
//Agora vamos conectar no ponto de WiFi informado no inicio do codigo, e ver se corre tudo certo
if (wifi.joinAP(SSID, PASSWORD)) {
    Serial.println("Conectado com Sucesso.");
    Serial.println("IP: ");
    //rotina wifi.getLocalIP() retorna o IP usado na conexao com AP conectada.
} else {
    Serial.println("Falha na conexao AP.");

//Agora vamos habiliar a funcionalidade MUX, que permite a realizacao de varias conexoes TCP/UDP
if (wifi.enableMUX()) {
    Serial.println("Multiplas conexoes OK.");
} else {
    Serial.println("Erro ao setar multiplas conexoes.");

//Inicia servidor TCP na porta 8090 (veja depois a funcao "startServer(numero_porta)", que serve para UDP!
if (wifi.startTCPServer(8090)) {
    Serial.println("Servidor iniciado com sucesso.");
} else {
    Serial.println("Erro ao iniciar servidor.");
Serial.println("Setup finalizado!");

  //  Cayenne.begin(token, ssid, password);
  //  Cayenne.config(token); //If this doesn't work, try Blynk.config(token);

//Na conexao TCP, basicamente a funcionalidade a ser mostrada sera a de "echo", ou seja, a aplicacao ira retornar todos os //dados enviados para ela via socket TCP.
void loop(void)
//Variavel para buffer de dados de trasmissao
uint8_t buffer[128] = {0};
//Como usamos multiplas conexoes, cada conexao tem sua ID, e precisa ser armazenada para referencia no programa. Usamos    //essa variavel para isso.
uint8_t mux_id;
//E esta variavel len serve para armazenar o comprimento de dados recebidos por meio da rotina wifi.recv(), que tambem     //associa ao buffer os dados recebidos e ao mux_id a id responsavel pela transmissao
uint32_t len = wifi.recv(&mux_id, buffer, sizeof(buffer), 100);
if (len > 0) {
    Serial.print("Recebido de :");
    for(uint32_t i = 0; i < len; i++) {
    //Agora envia de volta. A referencia para o socket TCP criado é o mux_id, ou id da conexao, usado aqui na rotina
    //wifi.send, veja abaixo:
    if(wifi.send(mux_id, buffer, len)) {
        Serial.print("Enviado de volta...\r\n");
    } else {
        Serial.print("Erro ao enviar de volta\r\n");
    //E, como sempre, liberar a conexao TCP, de modo a permitir que novas conexoes sejam realizadas.
    if (wifi.releaseTCP(mux_id)) {
        Serial.print("Liberando conexao TCP com ID: ");
        Serial.println(" OK");
    } else {
        Serial.print("Erro ao liberar TCP com ID: ");


// Reset funtion to accept communication
void reset8266 ()
 pinMode(CH_PD, OUTPUT);
 digitalWrite(CH_PD, LOW);
 digitalWrite(CH_PD, HIGH);

Give this post a try and see if it gets you connected WifiShield with arduino uno compiling error - #11 by kreggly

Tks Adam.

I performed the code but I could not conect in cayenne:

[519] Connecting to Vick Cristina Barcelona
[5610] IP: +CIFSR:STAIP,“”

[6635] Failed to disable MUX
[6635] Connected to WiFi

but in cayenne dashboard I could not connect.

@kreggly any ideas? I suppose at some point I should get an ESP out and try this out myself.

Don’t know.

I have an ESP-02 board to work with now, but not an ESP-01.

Don’t know if anyone has actually got an ESP-01 connected to Cayenne with the serial commands. Might be an incompatibility. We know the ESP-07 and ESP-12 ones work fine.



I do have a 1 around here somewhere. I’ll give it a try when I get a chance.

Thank you in advance.

I´m using something like this

The only difference is that instead of the resistors I am using a CD4050 module to guarantee the 3.3V to the ESP.

@adam Could you have a chance to try this device. Tks

Yep, worked fine for me. WifiShield with arduino uno compiling error - #53 by adam