ESP8266-01一些内容

系统有些指令必须特性状态下才可以执行,即先执行一些其它AT指令

 

1.设置station模式的IP信息

 AT+CIPSTA="192.168.19.1","192.168.1.1","255.255.0.0"

设置后,使用AT+CWDHCP=2,1 

恢复:DHCP方式

 

2.启动后服务器

AT+CIPMUX=1

AT+CIPSERVER=1,333  --后面是端口

 

3.启动UDP广播地址监听

AT+CIPMUX=1

AT+CIPSTART=0,"UDP","255.255.255.255",1111,2000,2

说明:1111任意端口(表示远程),2000为本地端口,

2(mode参数)表示以最后一次收到数据包IP为目标地址,也就是说如果有多个IP给本设备发送UDP包,那么AT+CIPSEND=0,x回复时数据发给最后一个发消息过来的

 当采用mode=2时使用:AT+CIPSTATUS可以查看最后一发请求过来的的链接情况

4.启动UDP链接

AT+CIPSTART=0,"UDP","192.168.88.88",8080,2000,2

参数2与上面一样,比方192.168.88.11:8111,最后一个给设备发UPD包,那么设备回复时的目标设备就是192.168.88.11:8111了

 

5.退出透传模式

1.发送+++后面不要有回车换行

2.等一会

3.发送回车与换行

4.发送AT&回车换行看命令是否恢复

 

6.Arduino下进行测试

/*
ESP-01    

VCC       -------- 3.3V
GND      -------- GND
CH-PD   -------- 3.3V (加不加10K电阻都可以)

TXD       ------   10  // 软串口的RX
RXD       -------  11  // 软串口的TX
                

UNO的代码:
*/
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()  
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }


  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}
View Code

7.启动后开启UDP透传模式,以及看门狗
服务端需要按$F...$E的格式封送数据

#include <avr/wdt.h>  
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX
unsigned long lastSendTime=0;
unsigned long lastReceiveTime=0;
String RecCache="";

void setup()  
{
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
  
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  

  Serial.println("Ready!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  
  mySerial.print("+++");
  delay(100);
  mySerial.println("AT");
  
  mySerial.println("AT+RST");
  delayAndRead(3000);
  
  //
  while(!isGotIP()){
    digitalWrite(13,HIGH);
    delay(300);
    digitalWrite(13,LOW);
    cls();
  }
  mySerial.println("AT+CIPSTART=\"UDP\",\"122.226.151.4\",12462,2000,0");
  delayAndRead(100);
  mySerial.println("AT+CIPMODE=1");
  delayAndRead(100);
  mySerial.println("AT+CIPSEND");
  delayAndRead(100);
  
   wdt_enable(WDTO_8S); 
}



void loop() // run over and over
{
  //handle user input cmd
  while (Serial.available()){
    mySerial.write(Serial.read()); 
  }
  
  while(mySerial.available()){
    char c= mySerial.read();
    RecCache=RecCache +(String)c;
  }
  
  int bIndex= RecCache.indexOf("$F");
  if(bIndex>=0){
    int eIndex=RecCache.indexOf("$E",bIndex);
    if(eIndex>=0){
       //Extra Data
       String data=RecCache.substring(bIndex+2,eIndex);
       RecCache=RecCache.substring(eIndex);
       lastReceiveTime=millis();
       
       handleData(data);
    }
  }else{
    RecCache=""; 
  }
  
  if(RecCache.length()>=1024)RecCache="";
  
  //check watchdog
  if((millis()-lastReceiveTime)<30000){
    wdt_reset(); 
  }
  
  //heart beat
  if((millis()-lastSendTime)>=10000){
       mySerial.println(millis());
      lastSendTime=millis(); 
    }
}

void handleData(String data){
 
  Serial.println(data);
}

void cls(){
   while(mySerial.available()){
     mySerial.read();
  }
}

void delayAndRead(int waitTime){
   delay(waitTime);
   while(mySerial.available()){
     Serial.write(mySerial.read()); 
   }
}

boolean isGotIP(){
  mySerial.println("AT+CIPSTATUS");
  delay(100);
  
 if( mySerial.find("STATUS:2")){
   return true;
 }
 return false;
 
}
View Code

 UDP服务端代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SmartPivot.WinClient
{
    public partial class Form1 : Form
    {
        private UdpClient udpServer = null;
        private bool isRunning = false;
        private bool Enable = false;
        private SynchronizationContext SyncCtx = null;


        public Form1()
        {
            InitializeComponent();
            SyncCtx = SynchronizationContext.Current;
            btnSend.Enabled = false;
        }

        private void btnSwitch_Click(object sender, EventArgs e)
        {
            try
            {
                if (isRunning)
                {
                    btnSend.Enabled = false;
                    _Stop();
                }
                else
                {

                    ThreadPool.QueueUserWorkItem(o =>
                    {
                        _Start();
                    }, null);
                    btnSend.Enabled = true;
                }
            }
            catch (Exception ex)
            {

            }
        }
        private void _Stop()
        {
            Enable = false;

            if (udpServer != null)
            {
                try
                {
                    udpServer.Close();

                }
                catch { }
            }
            isRunning = false;
            this.Text = "已停止";
        }
        private void _Start()
        {
            if (isRunning) return;
            Enable = true;
            //设置标题
            SyncCtx.Post(o =>
            {
                this.Text = "运行中";
            }, null);

            var ipAddress = IPAddress.Parse(txtIP.Text);
            int port = int.Parse(txtPort.Text);

            // udpServer.Client.Bind(new IPEndPoint(ipAddress, port));
            // udpServer.Connect(new IPEndPoint(ipAddress, port));
            udpServer = new UdpClient(new IPEndPoint(ipAddress, port));
            udpServer.AllowNatTraversal(false);
            var remote = new IPEndPoint(0, 0);
            isRunning = true;

            while (Enable)
            {
                try
                {
                    byte[] receiveData = udpServer.Receive(ref remote);
                    var str = Encoding.ASCII.GetString(receiveData);
                    Console.WriteLine(string.Format("Remote,{0}:{1},[{2}]",
                                                     remote.Address.ToString(),
                                                     remote.Port, DateTime.Now));
                    Console.WriteLine(str);
                    var responseTmp = String.Format("{0},{1},{2}" , remote.ToString(), DateTime.Now.ToString("yyMMddHHmmss"), Guid.NewGuid().ToString());
                    var responseDate = Encoding.ASCII.GetBytes("$F" + responseTmp.Length + ":" + responseTmp +"$E" + Environment.NewLine);
                    udpServer.Send(responseDate, responseDate.Length, remote);

                    SyncCtx.Post(o => {
                        txtRIP.Text = remote.Address.ToString();
                        txtRPort.Text = remote.Port.ToString();
                    }, null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ent => ent.AddressFamily == AddressFamily.InterNetwork);
            txtIP.Text = ip == null ? "" : ip.ToString();
            txtPort.Text = "12462";
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (udpServer == null) return;
                var sendData=Encoding.ASCII.GetBytes(txtSend.Text);
                var ipAddress = IPAddress.Parse(txtRIP.Text);
                int port = int.Parse(txtRPort.Text);
                udpServer.Send(sendData, sendData.Length, new IPEndPoint(ipAddress, port));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Send Err:" + ex.Message);
            }
        }
    }
}
View Code

 8.设置AP名称
AT+CWSAP="DF21_LSC","12345678",5,3  

其中5表示通道,3表示WPA2_PSK

密码需要8位以上

9.设置波特率

默认是115200

mySerial.println("AT+CIOBAUD=9600");

你可能感兴趣的:(ESP8266-01一些内容)