簡單的學習了WIFI模塊和相關AT指令,配置WiFi模組工作模式為單STA模式,并把配置保存在flash 中,然后自動發送指令連接網絡和連接服務器,最終即可發送數據。因為做的時候還沒有后端對接,相關的GET和POST請求沒有寫完
具體代碼參考附件。
單片機源程序如下:
- #include <reg52.h>
- #include <string.h>
- #include <intrins.h>
- typedef unsigned char u8;
- typedef unsigned int u16;
- unsigned char Usart_Receive[20]={0};
- unsigned char Usart_Cnt=0;
- bit Usart_AT_flage;
- u8 dat;
- void Init(void)
- {
- TMOD = 0x20;
- SCON = 0x50;
- TH1 = 0xFD;
- TL1 = TH1;
- PCON = 0x00;
- EA = 1;
- ES = 1;
- TR1 = 1;
- }
- void delay5ms(void) //誤差 -0.000000000001us
- {
- unsigned char a,b;
- for(b=15;b>0;b--)
- for(a=152;a>0;a--);
- }
- void delay1s(void) //誤差 -0.000000000227us
- {
- unsigned char a,b,c;
- for(c=13;c>0;c--)
- for(b=247;b>0;b--)
- for(a=142;a>0;a--);
- _nop_(); //if Keil,require use intrins.h
- }
- void Sent_ZF(u8 dat) //發送一個字節
- {
- ES = 0;
- TI=0;
- SBUF = dat;
- while(!TI);
- TI = 0;
- ES = 1;
- }
- void AT_Send_String(u8 *string) //發送字符串
- {
- while(*string)
- {
- Sent_ZF(*string++);
- delay5ms();
- }
- }
- void ESP8266_Init()
- {
- while(1)
- {
- AT_Send_String("AT\r\n");
- delay1s();
- delay1s();
- if(Usart_AT_flage ==1)
- {
- if(strstr(Usart_Receive, "OK"))
- {
- Usart_AT_flage = 0;
- AT_Send_String("OK\r\n");
- break;
- }
- }
- }
- while(1)
- {
- AT_Send_String("AT+CWMODE=1\r\n"); //配置WiFi模組工作模式為單STA模式,并把配置保存在flash
- delay1s();
- delay1s();
- if(Usart_AT_flage ==1)
- {
- if(strstr(Usart_Receive, "OK"))
- {
- Usart_AT_flage = 0;
- AT_Send_String("OK\r\n");
- break;
- }
- }
- }
- while(1)
- {
- AT_Send_String("AT+CWJAP=\"guazhou\",\"123456789\"\r\n"); //!連接網絡
- delay1s();
- delay1s();
- if(Usart_AT_flage ==1)
- {
- if(strstr(Usart_Receive, "OK"))
- {
- Usart_AT_flage = 0;
- AT_Send_String("OK\r\n");
- break;
- }
- }
- }
- while(1)
- {
- AT_Send_String("AT+CIPSTART=\"TCP\",\"192.110.43.11\",8080\r\n"); //連接服務器
- delay1s();
- delay1s();
- delay1s();
- if(Usart_AT_flage ==1)
- {
- if(strstr(Usart_Receive, "OK"))
- {
- Usart_AT_flage = 0;
- AT_Send_String("OK\r\n");
- break;
- }
- }
- }
- while(1)
- {
- AT_Send_String("AT+CIPMODE=1\r\n"); //設置透傳
- delay1s();
- delay1s();
- delay1s();
- if(Usart_AT_flage ==1)
- {
- if(strstr(Usart_Receive, "OK"))
- {
- Usart_AT_flage = 0;
- AT_Send_String("OK\r\n");
- break;
- }
- }
- }
- while(1)
- {
- AT_Send_String("AT+CIPSEND\r\n"); //啟動發送
- delay1s();
- delay1s();
- delay1s();
- if(Usart_AT_flage ==1)
- {
- if(strstr(Usart_Receive, "OK"))
- {
- Usart_AT_flage = 0;
- AT_Send_String("OK\r\n");
- break;
- }
- }
- }
-
- //get請求/post請求略,可參看截圖寫出
- }
- void main()
- {
- Init();
- ESP8266_Init();
- while(1);
- }
- void InterruptUART(void) interrupt 4
- {
- if(RI)
- {
- RI=0;
- Usart_Receive[Usart_Cnt]=SBUF;
- Usart_Cnt++;
- if(Usart_Receive[Usart_Cnt-2]=='\r'&&Usart_Receive[Usart_Cnt-1]=='\n') //檢測倒數一二位
- {
- Usart_Cnt=0;
- Usart_AT_flage=1;
-
- }
- else if(Usart_Cnt>20)
- {
- Usart_Cnt=0;
- }
- }
- else
- TI=0;
- }
復制代碼
所有資料51hei提供下載:
WiFi HTTP通信.zip
(26.12 KB, 下載次數: 44)
2019-11-20 20:20 上傳
點擊文件名下載附件
下載積分: 黑幣 -5
|