Cayenne Community
HOME PROJECTS DOCS SUPPORTED HARDWARE
SIGN IN GET STARTED
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
mashuca1h
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.
Tks
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
* AT+CWJAP="ROVAI TIMECAP","mjr747@1"
*
* 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)
{
pinMode(CH_PD,OUTPUT);
digitalWrite(CH_PD,HIGH); //setado em ALTO - operacao normal
esp8266.begin (speed8266);
Serial.begin(9600);
//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
Serial.println(wifi.getVersion().c_str());
//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.
Serial.println(wifi.getLocalIP().c_str());
} 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("Status:[");
Serial.print(wifi.getIPStatus().c_str());
Serial.println("]");
Serial.print("Recebido de :");
Serial.print(mux_id);
Serial.print("[");
for(uint32_t i = 0; i < len; i++) {
Serial.print((char)buffer[i]);
}
Serial.print("]\r\n");
//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.print(mux_id);
Serial.println(" OK");
} else {
Serial.print("Erro ao liberar TCP com ID: ");
Serial.print(mux_id);
}
Serial.print("Status:[");
Serial.print(wifi.getIPStatus().c_str());
Serial.println("]");
}
// Cayenne.run();
delay(100);
Serial.print(".");
}
// Reset funtion to accept communication
void reset8266 ()
{
pinMode(CH_PD, OUTPUT);
digitalWrite(CH_PD, LOW);
delay(300);
digitalWrite(CH_PD, HIGH);
}