El Tutorial consiste en configurar una tarjeta Cactus Micro con microcontrolador ATmega32U4 , que viene con la tarjeta Wifi ESP8266 incluida, el mismo lo conectamos a dos Leds, uno nos informara con el primer parpadeo que se conecto a nuestro Wifi y luego comenzara a parpadear para indicarnos que llego al loop, también conectamos un LCD para que Nos Indique el Nombre del Wifi y la IP que le configuramos de Forma estática, el segundo led lo podemos apagar y encender a través de una conexión telnet al puerto 22, escribiendo (verde on o verde off).
Caracteristicas:
- Built-in ESP8266 WIFI module.
- ATmega32U4 running at 3.3V/8MHz
- Supported under Arduino IDE v1.0.6
- On-Board micro-USB connector for programming
- 4 x 10-bit ADC pins
- 12 x Digital I/Os (5 are PWM capable)
- Rx and Tx Hardware Serial Connections
Materiales necesarios:
- Micro Atmega32U4 + ESP8266 WIFI
- 1 Protoboard
- 1 Led Azul
- 1 Led Verde
- 2 Resistencias
- Varios Jumpers
- Pantalla LCD
Grafico de Conexión:
Código:
//CODIGO:
#include <OneWire.h>
#include <avr/pgmspace.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <string.h>
#include <SPI.h>
#include <WiFiClient.h>
#include <IPAddress.h>
#define TIMEOUT 5000 // mS
#define HOSTIP "192.168.1.111" // iP de Asignado
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Configurando los Pines del LCD I2C y la dirección (0x27)
int wifiConnected;
char serialbuffer[100]; //serial buffer for request command
// Variables will change:
int ledState = HIGH; // ledState used to set the LED
#define BUFFER_SIZE 128
char buffer[BUFFER_SIZE];
//====================================
const bool printReply = true;
const char line[] = "-----\n\r";
int loopCount=0;
char html[50];
char command[20];
char reply[500];
char ipAddress [20];
char name[30];
int lenHtml = 0;
char temp[5];
//=====================================
// Importante Usamos el pin 13 para habilitar la tarjeta Wifi esp8266
#define WIFI_ENABLE_PIN 13
#define LEDREDPIN 9
#define LEDGREENPIN 4
#define DEBUG 1
#define SSID "NOMBRE DEL WIFI"
#define PASS "clave del wifi-aqui"
SoftwareSerial serialEsp8266(11, 12); // rx, tx comunicacion con Cactus Board
void setup()
{
int CommandStep = 1;
lcd.begin(16,2); // initialize the lcd for 16 chars 2 lines, turn on backlight
Serial.begin(9600); //serial Atmega32U4
serialEsp8266.begin(9600); //Inicializando Serial connection to ESP8266
//serialEsp8266.setTimeout(100);
pinMode(LEDREDPIN, OUTPUT);
pinMode(LEDGREENPIN, OUTPUT);
pinMode(WIFI_ENABLE_PIN, OUTPUT);
digitalWrite(WIFI_ENABLE_PIN, HIGH);
delay(2000);//delay
// ------- Quick 3 blinks of backlight -------------
for(int i = 0; i< 3; i++)
{
lcd.backlight();
delay(250);
lcd.noBacklight();
delay(250);
}
lcd.backlight(); // finish with backlight on
//-------- Write characters on the display ------------------
// NOTE: Cursor Position: (CHAR, LINE) start at 0
lcd.setCursor(0,0); //Start at character 4 on line 0
lcd.print("Hi, ELECTRONICAPTY");
delay(1000);
lcd.setCursor(0,1);
lcd.print("Testing Your LCD");
delay(5000);
// Wait and then tell user they can start the Serial Monitor and type in characters to
// Display. (Set Serial Monitor option to "No Line Ending")
lcd.clear();
lcd.setCursor(0,0); //Start at character 0 on line 0
lcd.print("www.electronicapty.com");
lcd.setCursor(0,1);
lcd.print("+(507) 836-6461");
Serial.println(F("ESP8266 on Cactus Board Atmega"));
//while(serialEsp8266.available()>0)
//serialEsp8266.read();
//delay(1000);
Serial.println(F("Resetting module"));
//serialEsp8266.println("AT+RST");
serialEsp8266.print(F("AT+RST\r\n"));
getReply( 3000 );
//delay(3000);
// configure as a station
Serial.println(F("Change to station mode as station"));
serialEsp8266.print(F("AT+CWMODE=1\r\n"));
getReply( 1500 );
//serialEsp8266.println(F("AT+CWMODE=1")); //Configurando el Modo a estación
//delay(300);
//Desabilitar DHCP STATION EN TARJETA
Serial.println(F("Desabilitando DHCP Client on station"));
serialEsp8266.print(F("AT+CWDHCP=1,0\r\n"));
getReply( 1500 );
//Poniendo IP FIJO en la estacion
Serial.println(F("Poniendo IP fijo station"));
serialEsp8266.print("AT+CIPSTA=192.168.1.111");
getReply( 2500 );
// connect to the network. Uses DHCP. ip will be assigned by the router.
Serial.println(F("Connect to a network "));
//Verificando para conectar, sino intentando de nuevo connectar al Wifi
boolean connected=false;
for(int i=0;i<5;i++)
{
if(connectWifi())
{
connected = true;
break;
}
}
if (!connected){while(1);}
delay(5000);
//print the ip addr
//serialEsp8266.println("AT+CIFSR");
Serial.println(F("Get the ip address assigned:"));
serialEsp8266.print(F("AT+CIFSR\r\n"));
// Serial.println( GetResponse("AT+CIFSR", 10) );
//delay(500);
getReply( 1000 );
// parse ip address.
int len = strlen( reply );
bool done=false;
bool error = false;
int pos = 0;
while (!done)
{
if ( reply[pos] == 10) { done = true;}
pos++;
if (pos > len) { done = true; error = true;}
}
if (!error)
{
int buffpos = 0;
done = false;
while (!done)
{
if ( reply[pos] == 13 ) { done = true; }
else { ipAddress[buffpos] = reply[pos]; buffpos++; pos++; }
}
ipAddress[buffpos] = 0;
}
else { strcpy(ipAddress,"ERROR"); }
// Display. (Set Serial Monitor option to "No Line Ending")
lcd.clear();
lcd.setCursor(0,0); //Start at character 0 on line 0
lcd.print("SSID:");
lcd.setCursor(5,0); //Start at character 0 on line 0
lcd.print(SSID);
lcd.setCursor(0,1);
lcd.print("IP: ");
lcd.setCursor(3,1);
lcd.print(HOSTIP);
// Setting for Multiple connections
Serial.println(F("Set for multiple connections"));
serialEsp8266.print(F("AT+CIPMUX=1\r\n"));
getReply( 1500 );
// Start up the server on port
Serial.println(F("Start the server on ip address obtained"));
serialEsp8266.print(F("AT+CIPSERVER=1,22\r\n")); // Start up the server on port 80
getReply( 1500 );
//Serial.println("");
Serial.print(F("Connect to "));
Serial.println(ipAddress);
Serial.println(F(""));
//===========================
}//=============END VOID SETUP==================
//=================================BEGIN VOID LOOP====================
void loop()
{
String IncomingString="";
char SingleChar;
boolean StringReady = false;
digitalWrite(9, HIGH); // turn the LED on (HIGH is the voltage level)
delay(300); // wait for a second
digitalWrite(9, LOW); // turn the LED off by making the voltage LOW
delay(300); // wait for a second
// listen for communication from the ESP8266 and then write it to the serial monitor
if ( serialEsp8266.available() ) { Serial.write( serialEsp8266.read() ); }
// listen for user input and send it to the ESP8266
if ( Serial.available() ) { serialEsp8266.write( Serial.read() ); }
while (serialEsp8266.available())
{
IncomingString=serialEsp8266.readString();
StringReady= true;
}
//********** Only run when string is available ************//
if ((IncomingString.indexOf("rojo") != -1) || (IncomingString.indexOf("all") != -1)) {
Serial.println("Someone trying to control RED LED");
ProcessLEDCommand(LEDREDPIN, IncomingString);
}
if ((IncomingString.indexOf("verde") != -1) || (IncomingString.indexOf("all") != -1)) {
Serial.println("Someone trying to control GREEN LED");
ProcessLEDCommand(LEDGREENPIN, IncomingString);
}
}
//==================================END VOID LOOP======================
void getReply(int wait)
{
int tempPos = 0;
long int time = millis();
while( (time + wait) > millis())
{
while(serialEsp8266.available())
{
char c = serialEsp8266.read();
if (tempPos < 500) { reply[tempPos] = c; tempPos++; }
}
reply[tempPos] = 0;
}
if (printReply) { Serial.println( reply ); Serial.println(line); }
}
//=========================================
void ProcessLEDCommand(int LEDPin, String IncomingString){
if (IncomingString.indexOf("on") != -1) {
Serial.println("Someone trying to turn on LED");
digitalWrite(LEDPin,HIGH);
}
if (IncomingString.indexOf("off") != -1) {
Serial.println("Someone trying to turn off LED");
digitalWrite(LEDPin,LOW);
}
if (IncomingString.indexOf("blink") != -1) {
Serial.println("Someone trying to blink LED");
BlinkLED(LEDPin,5,200);
}
}
//================================
void BlinkLED(int LEDPin, int NumberOfBlinks, int OnDuration)
{
for (int x=1; x <= NumberOfBlinks ; x ++){
digitalWrite(LEDPin,HIGH);
delay(OnDuration);
digitalWrite(LEDPin,LOW);
delay(OnDuration);
}
}
//==================================
boolean SendCommand(String cmd, String ack, boolean halt_on_fail)
{
serialEsp8266.println(cmd); // Send "AT+" command to module
// Otherwise wait for ack.
if (!echoFind(ack)) // timed out waiting for ack string
if (halt_on_fail)
errorHalt(cmd+" failed"); // Critical failure halt.
else
return false; // Let the caller handle it.
return true; // ack blank or ack found
}
//=========================================
// Read characters from WiFi module and echo to serial until keyword occurs or timeout.
boolean echoFind(String keyword)
{
byte current_char = 0;
byte keyword_length = keyword.length();
// Fail if the target string has not been sent by deadline.
long deadline = millis() + TIMEOUT;
while(millis() < deadline)
{
if (serialEsp8266.available())
{
char ch = serialEsp8266.read();
Serial.write(ch);
if (ch == keyword[current_char])
if (++current_char == keyword_length)
{
Serial.println();
return true;
}
}
}
return false; // Timed out
}
//===============================================
// Print error message and loop stop.
void errorHalt(String msg)
{
Serial.println(msg);
Serial.println("HALT");
digitalWrite(LEDREDPIN,LOW);
digitalWrite(LEDGREENPIN,HIGH);
while(true){};
}
//=============================================
// Get the data from the WiFi module and send it to the debug serial port
String GetResponse(String AT_Command, int wait){
String tmpData;
serialEsp8266.println(AT_Command);
delay(10);
while (serialEsp8266.available() >0 ) {
char c = serialEsp8266.read();
tmpData += c;
if ( tmpData.indexOf(AT_Command) > -1 )
tmpData = "";
else
tmpData.trim();
}
return tmpData;
}
//============================================
void homepage(int ch_id) {
String Header;
Header = "HTTP/1.1 200 OK\r\n";
Header += "Content-Type: text/html\r\n";
Header += "Connection: close\r\n";
//Header += "Refresh: 5\r\n";
String Content;
Content = "D";
Content += String(ledState);
Header += "Content-Length: ";
Header += (int)(Content.length());
Header += "\r\n\r\n";
serialEsp8266.print("AT+CIPSEND=");
serialEsp8266.print(ch_id);
serialEsp8266.print(",");
serialEsp8266.println(Header.length()+Content.length());
delay(10);
if (serialEsp8266.find(">")) {
serialEsp8266.print(Header);
serialEsp8266.print(Content);
delay(10);
}
// Serial1.print("AT+CIPCLOSE=");
// Serial1.println(ch_id);
}
//=======================================
void clearSerialBuffer(void) {
while ( serialEsp8266.available() > 0 ) {
serialEsp8266.read();
}
}
//========================================
void clearBuffer(void) {
for (int i =0;i<BUFFER_SIZE;i++ ) {
buffer[i]=0;
}
}
//=========================================
boolean connectWifi()
{
String cmd="AT+CWJAP=\"";
cmd+=SSID;
cmd+="\",\"";
cmd+=PASS;
cmd+="\"";
serialEsp8266.println(cmd);
Serial.println(cmd);
delay(2000);
for(int i = 0; i < 20; i++)
{
Serial.print(".");
if(serialEsp8266.find("OK"))
{
Serial.println(F("OK, Connected to WiFi."));
wifiConnected = 1;
digitalWrite(LEDREDPIN, HIGH);
return true;
}
else
{
Serial.println(F("Can not connect to the WiFi."));
wifiConnected = 0;
return false;
}
}
}