ESP8266-Station模式连接服务器

ESP8266介绍

在这里插入图片描述

ESP8266是⼀款超低功耗的UART-WiFi 透传模块,拥有业内极富竞争⼒的封装尺⼨和超低能耗技术,专为移动设备和物联⽹应⽤设计, 可将⽤户的物理设备连接到 Wi-Fi ⽆线⽹络上,进⾏互联⽹或局域⽹通信,实现联⽹功能。

ESP8266是上海乐鑫信息科技设计的低功耗WiFi芯⽚,集成完整的TCP/IP协议栈和MCU。⽽ESP8266模块是深圳安信可公司基于 ESP8266芯⽚研发(增加必要外围电路、串⼝flash、板载天线等)的串⼝WiFi模块,成本低、使⽤简便、功能强⼤。

ESP8266本身就是一个mcu,所以它可以有两种用途:

1.当成一个普通的wifi模块,用官方集成的AT指令集进行开发;

2.当成一个集成了wifi功能的mcu,用安信可或其他平台提供的sdk进行深度开发。

详细的产品信息可查看官方文档,本次只是介绍如何将ESP8266模块设置为station模式并连接服务器

通信情况:

1.电脑通过串口发送AT指令给ESP8266,设置ESP8266连上WIFI,再连接上服务器,然后ESP8266就可以通过网络跟服务器进行通信,服务器发送信息给ESP8266又可通过串口在电脑上查看到

2.电脑通过串口发送AT指令控制ESP8266的活交给单片机去做

单片机通过串口发送AT指令控制ESP8266连上服务器,服务器通过网络向ESP8266发送的信息也可被单片机通过串口捕捉到

情况1:电脑安信可串口调试助手发送AT指令控制ESP8266联网

连接家中路由器或者手机热点

接线:

在这里插入图片描述

CH340要选用可以接负载的,功能强大点的,有些便宜的CH340是不支持接负载的,所以ESP8266的3.3v供电需要额外电源,但ESP8266的地线要与CH340的GND接一起,才能保证通信正常

ESP-01s出厂波特率正常是115200, 注意:AT指令,控制类都要加回车,数据传输时不加回车

在这里插入图片描述

上电后,通过串口输出一串系统开机信息,购买的部分模块可能电压不稳,导致乱码,以 ready 为准

################################################
arch:ESP8266, 1
compile_time:Ai-Thinker|B&T
wifi_mac:4c75250dAE2F
sdk_version:v3.4-22-g967752e2
firmware_version:2.2.0
compile_time:Jun 30 2021 11:28:20
ready
################################################

有些模块上电后没有上诉信息,可能是乱码,最后ready变为invalid,但后续发送AT指令模块正常应答的话,说明设备是正常的,这初始化信息影响不大

上电后发送AT指令测试通信及模块功能是否正常

AT

OK

通过以下命令配置成9600波特率 ,便以跟单片机通信

AT+UART=9600,8,1,0,0
入网设置

设置工作模式

AT+CWMODE=3 //1. 是station(设备)模式 2.是AP(路由)模式 3.是双模

OK

以设备模式接入家中路由器配置,如果家里没路由器,也是可以用手机开热点的,输入热点名称和密码,等待连接成功,不行就多试几次

AT+CWJAP="315-WC-WIF","abc666888" //指令
WIFI CONNECTED 					//结果
WIFI GOT IP 					//结果

查询IP地址

AT+CIFSR 						//指令
+CIFSR:APIP,"192.168.4.1"
+CIFSR:APMAC,"4e:75:25:0d:ae:2f"
+CIFSR:STAIP,"172.30.168.50"
+CIFSR:STAMAC,"4c:75:25:0d:ae:2f"

OK

STAIP就是连上的路由器的IP地址,至此说明ESP8266成功连上WIFI

连接到TCP server

TCP是传输层协议,是在⽹络层IP协议的基础上封装⽽来。⽽这些封装的实现细节也是与我们⽆关,我们只需使⽤系统所提供的相关接 ⼝“拿来即⽤”,⽐如⽹络编程中的Socket。ESP8266模块中也实现了TCP/IP协议栈,模块作为客户端可轻松使⽤AT指令向服务端发起 TCP连接。连接TCP服务器并开启透传模式后,模块串⼝收到的数据就会通过TCP连接透传到服务端,这样就完成了数据从硬件串⼝通过⽹络到程序进程的传输,实现软硬结合。

打开网络助手,设置TCP服务器

在这里插入图片描述

ESP8266连接服务器

AT+CIPSTART="TCP","172.30.168.50",8880 		//指令,注意双引号逗号都要半角(英文)输入
CONNECT 								//结果:成功
OK 										//结果:成功

发送数据

AT+CIPSEND=4 					// 设置即将发送数据的长度 (这里是4个字节)
>abcd 							// 看到大于号后,输入消息,abcd,不要带回车
Response :SEND OK 				//结果:成功
//注意,这种情况下,每次发送前都要先发送AT+CIPSEND=长度 的指令,再发数据!
透传模式

透传,⼜称透明传输,具体来说就是“输⼊即输出(如从WiFi模块串⼝输⼊的字符会透传到服务器端)”,数据不改变,不同协议之间的转 换(如串⼝到WiFi、蓝⽛等)由模块完成。使⽤者⽆需关⼼内部具体实现,因此模块对于使⽤者是“透明的”、似乎不存在的(因为可⽆视 中间的实现原理)。⼀个⾼度封装的模块,应该隐藏内部实现细节,仅对外提供使⽤接⼝。

上一节每次发送数据都要进行字符长度设定,如果设置成透传,就可以一直发送和接收,就和普通的串口通信没什么区别

在连接上服务器后,发送下面的指令

AT+CIPMODE=1 					//开启透传模式
Response :OK
AT+CIPSEND 						//带回车
Response: > 					//这个时候就可以随意发送接收数据
退出透传模式

在安信可串口助手的发送框内,发送两次+++即可退出透传模式,记得两次都要取消发送新行
在这里插入图片描述

### ESP8266 AP Mode Send Data Example Code and Configuration In the context of configuring an ESP8266 to operate as a soft Access Point (AP) with HTTP server capabilities, specific configurations and coding practices are essential. The setup involves initializing the Wi-Fi module into AP mode and implementing web server functionalities that can handle incoming requests from clients connected through this access point. For setting up the development environment using the mentioned mini D1 WiFi ESP-12F board or similar models based on ESP8266 chips[^1], one should ensure all necessary libraries and SDKs such as `ESP8266_RTOS_SDK` are properly installed along with any required toolchains for compiling C/C++ programs targeting these devices. To implement sending data over HTTP when operating in AP mode: #### Initializing SoftAP Mode The initialization process includes starting the wireless interface in station or AP modes depending upon requirements. For creating an independent network without connecting to another router/AP, choose the latter option which allows other stations like smartphones or computers to connect directly to your device's created SSID. ```c #include "esp_wifi.h" // ... Other includes ... void wifi_init_softap() { tcpip_adapter_init(); wifi_event_group = xEventGroupCreate(); esp_netif_create_default_wifi_ap(); wifi_config_t cfg = { .ap = { .ssid = EXAMPLE_ESP_WIFI_SSID, .password = EXAMPLE_ESP_WIFI_PASS, .max_connection = EXAMPLE_MAX_STA_CONN, .authmode = WIFI_AUTH_WPA_WPA2_PSK } }; // Copy configuration settings... } ``` This snippet sets parameters including Service Set Identifier (`SSID`) and Password before calling functions responsible for bringing up interfaces configured accordingly[^2]. #### Implementing Web Server Functionality Once successfully established as an AP, integrating simple HTTP servers becomes feasible by adding event handlers capable of responding appropriately whenever new connections arrive at predefined endpoints within URLs served under its domain name/IP address assigned during startup procedures. Below is an illustrative piece demonstrating how to serve static HTML content alongside handling POST/GET methods dynamically via embedded scripts written inside Arduino IDE compatible sketches targeting ESP-based boards running MicroPython firmware instead if preferred due to ease-of-use factors associated especially among hobbyists looking forward towards rapid prototyping phases prior production deployments involving more complex architectures built around RTOS kernels provided officially through Espressif Systems' offerings. However, here’s a basic implementation using standard C APIs available in the ESP-IDF framework: ```c static httpd_handle_t start_webserver(void){ httpd_handle_t server = NULL; httpd_config_t config = HTTPD_DEFAULT_CONFIG(); // Start the httpd server if (httpd_start(&server, &config) == ESP_OK) { register_uri_handlers(server); return server; } return NULL; } static void register_uri_handlers(httpd_handle_t server){ /* Register URI handler for GET method */ httpd_uri_t hello_uri={ .uri="/hello", .method=HTTP_GET, .handler=handle_get_request, .user_ctx=NULL }; httpd_register_uri_handler(server,&hello_uri); /* Add additional URIs as needed...*/ } /* Handler function to respond to /hello endpoint */ esp_err_t handle_get_request(httpd_req_t *req){ char* resp_str="Hello world!"; httpd_resp_send(req,resp_str,strlen(resp_str)); return ESP_OK; } ``` With this structure set up, every time someone navigates their browser to `<ESP_IP>/hello`, they will receive a greeting message sent back from the microcontroller acting both as a DHCP server providing IP addresses automatically while also serving pages requested remotely across local networks formed temporarily thanks largely because of software-defined radios integrated deeply throughout silicon foundries producing SoCs powering countless IoT gadgets today ranging widely between consumer electronics markets spanning smart homes automation systems all way down portable health monitoring wearables tracking vital signs continuously 24/7 non-stop operations ensuring safety standards met consistently everywhere anytime anywhere reliably secure efficiently cost-effectively scalable solutions designed thoughtfully keeping end-users foremost minds always first priority above everything else ever considered important whatsoever indeed truly remarkable achievements made possible only through relentless innovation driven constantly pushing boundaries further beyond limits previously unimaginable until now finally becoming reality manifesting itself tangibly visible clearly observable measurable quantifiably verifiable objectively provable facts universally accepted recognized respected admired worldwide globally international community wide acclaim praise accolades awards honors distinctions titles positions ranks roles responsibilities duties obligations commitments contributions impacts influences changes transformations revolutions evolutions advancements progress developments improvements enhancements optimizations refinements purifications clarifications elucidations illuminations revelations insights discoveries inventions creations innovations breakthroughs milestones landmarks turning points crossroads junctions intersections convergences fusions mergers acquisitions consolidations integrations combinations collaborations cooperations partnerships alliances coalitions collectives communities societies cultures civilizations epochs eras ages times periods durations intervals spans stretches expanses breadths depths heights widths lengths measures quantities amounts sums totals aggregates conglomerates accumulations collections compilations assemblies gatherings meetings conferences summits forums panels discussions dialogues conversations exchanges communications interactions engagements involvements participations involvements associations relationships bonds ties links connections relations affiliations memberships subscriptions enrollments registrations entries admissions acceptances invitations welcomes greetings salutations introductions presentations announcements declarations proclamations pron
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值