總網頁瀏覽量

2016年2月19日 星期五

AT Commands sending to ESP8266 from Arduino IDE Serial

This is a Arduino sketch for AT Commands sending from Arduino Serial(TxRx) to ESP8266.
When AT commands is received by arduino, they will bypass arduino to ESP8266!



Connection examples: Motoduino WiFi Module(ESP8266) with S4A IO Board

Connections example: ESP-12


Copy and paste the following sketch to Arduino IDE! Enjoy!

///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <SoftwareSerial.h>
SoftwareSerial esp8266(3,2);  // use pins (3,2) for software serial  S4A IO board
                                                // Rx : D3,  Tx: D2
#define DEBUG true
#define BUFFER_SIZE 512
char serBuffer[BUFFER_SIZE];
char command[128];

void setup() {

    Serial.begin(9600); // start serial communication at 9600bps
    esp8266.begin(9600); // Modify it for your esp8266 module

    Serial.println("Ready...");
}

void loop() {
  char ser_char;

    if(Serial.available()>0){
       Serial.readBytesUntil('\n', serBuffer, BUFFER_SIZE);
       int len = strlen(serBuffer);

       if(3 == len)
       {
           serBuffer[len]='\n';
           if(!strncmp(serBuffer, "AT\r\n",4))
             sendData(serBuffer, 1000, DEBUG);
       }
       else if(( len > 3)&&(serBuffer[2]=='+'))
       {
            Serial.readBytesUntil('\n', serBuffer, BUFFER_SIZE);
            len = strlen(serBuffer);
            serBuffer[len]='\n';
            //Serial.println(serBuffer);          
            sendData(serBuffer, 2000, DEBUG);
       }
          clearBuffer();
    }
}

String sendData(String command, const int timeout, boolean debug)
{
    String response = "";
   
    esp8266.print(command); // send the read character to the esp8266
    long int time = millis();
    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {      
        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }
    if(DEBUG){
      Serial.print(response);
    }
    return response;
}

void clearBuffer(void) {
       for (int i =0;i<BUFFER_SIZE;i++ ) {
         serBuffer[i]=0;
       }
}

沒有留言:

張貼留言