这一篇的主人公是一块esp8266芯片。这款芯片使用了3.3V的直流电源,体积小,功耗低,支持透传,丢包现象不严重,而且价格超低,ESP8266-01系列,相应的还有ESP8266-02,03等等,它们使用的核心芯片都是相同的,不同之处就是引出的引脚不同,而且有的系列对核心芯片还加了金属屏蔽壳,有的可外接陶瓷天线等。
ESP8266官方提供的rom主要有两个,一个是支持at命令修改参数的at系列rom,使用此rom时,可以使用at命令来设置芯片的大部分参数,同时也可将芯片设置为透传模式,这样ESP8266就相当于在互联网和UART之间架起了一座桥梁。
要想使用esp8266芯片首先我们需要对串口进行配置。必须让串口的波特率为11520。接下来对esp8266发送一系列的AT指令,让其可以连接上网络以及我们设置好的服务器上。注意:如果还没有get到wifi的ip就去连接服务器,就会导致该命令会产生busy的回复,所以在这里我们需要对它进行足够的延迟,让这个模块可以get ip。
接下来我们来看一下如何使用esp8266芯片:
esp8266.c
#include <reg52.h>
#include<string.h>
#include<stdio.h>
char send_busy = 0;
extern char *c;
void delay(int time)
{
int i;
int j;
for(i=0;i<100;i++)
{
for(j=0;j<time;j++)
{
}
}
}
//void initUnrt_9600()
// {
// SCON =0x50;
// TMOD=0x20;
// TR1 =1;
// TH1=TL1=0xFD;
// EA =1;
// ES =1;
// }
void initUnrt_115200()
{
SCON =0x50;
T2CON|=0x34;
TR2 =1;
RCAP2H=0xFF;
RCAP2L=0xFD;
TH2=0xFF;
TL2=0xFD;
EA =1;
ES =1;
}
void sendmsg(char *a)
{
int len;
int i;
len=strlen(a);
for(i=0;i<len;i++)
{
send_busy = 1;
SBUF=*a;
while(send_busy);
a++;
}
}
void zhong(void) interrupt 4
{
if(RI==1){
RI=0;
*c=SBUF;
}
if(TI==1)
{
TI=0;
send_busy = 0;
}
}
main.c
#include<reg52.h>
#include<string.h>
#include<stdio.h>
#include "esp8266.h"
char *c;
sbit jdq=P1^0;
sbit Trig=p1^4;
sbit Echo=p1^5;
unsigned int time;
void Timer0Init()
{
TMOD = 0X01;
TH0 = 0;
TL0 = 0;
TF0 = 0;
EA = 1;
}
void initESp8266()
{
sendmsg("AT+CWMODE_DEF=1\r\n");
delay(100);
sendmsg("AT+CWJAP_DEF=\"Do\",\"12345678\"\r\n");
delay(3000);
sendmsg("AT+CIPCLOSE\r\n");
delay(500);
sendmsg("AT+CIPSTART=\"TCP\",\"172.20.10.2\",8880\r\n");
delay(3000);
sendmsg("AT+CIPMODE=1\r\n");
delay(200);
sendmsg("AT+CIPSEND\r\n");
}
int main()
{
int a;
initUnrt_115200();
initESp8266();
// if(*c=='1')
// {
// sendmsg("hello");
// jdq =1;
// }
// else if(*c=='0')
// {
// sendmsg("OK");
// jdq = 0;
// }
}
return 0;
}