Chat
Danh mục
Module Wifi ESP8266 - Hiển thị thông tin thời tiết lên LCD

Module Wifi ESP8266 - Hiển thị thông tin thời tiết lên LCD

Số lượng:
Thêm vào giỏ
Module Wifi ESP8266 - Hiển thị thông tin thời tiết lên LCD đã được thêm vào giỏ hàng



Nội dung của hướng dẫn này nhắm giúp các bạn kiểm tra hoạt động, giao tiếp module wifi esp8266 cũng như thử làm ứng dụng nhỏ đọc dữ liệu từ openweathermap.org hiển thị lên LCD 16×2 sử dụng vi điều khiển Pic18f4550 và CCS C 5.025

Các dòng vi điều khiển 8051(89s52), AVR, STM,…sẽ được cập nhật trong thời gian sớm nhất. Đây là module sử dụng khá hay mà giá cả lại vừa phải nên mình sẽ dành nhiều thời gian hướng dẫn các bạn làm các dự án liên quan đến điều khiển qua smartphone, máy tính mà có sử dụng đến wifi hoặc internet.

Video:



I: Module wifi ESP8266

Module ESP8266 là module wifi giá rẻ và được đánh giá rất cao cho các ứng dụng liên quan đến Internet và Wifi cũng như các ứng dụng truyền nhận sử dụng thay thế cho các module RF khác.

ESP8266 là một chip tích hợp cao, được thiết kế cho nhu cầu của một thế giới kết nối mới, thế giới Internet of thing (IOT). Nó cung cấp một giải pháp kết nối mạng Wi-Fi đầy đủ và khép kín, cho phép nó có thể lưu trữ các ứng dụng hoặc để giảm tải tất cả các chức năng kết nối mạng Wi-Fi từ một bộ xử lý ứng dụng.

ESP8266 có xử lý và khả năng lưu trữ mạnh mẽ cho phép nó được tích hợp với các bộ cảm biến, vi điều khiển và các thiết bị ứng dụng cụ thể khác thông qua GPIOs với một chi phí tối thiểu và một  PCB tối thiểu.

Tính năng của chip ESP 8266:

SDIO 2.0, SPI, UART
32-pin QFN ( Chip esp8266)
Tích hợp RF switch, balun, 24dBm PA, DCXO, and PMU
Tích hợp bộ xử lý RISC, trên chip bộ nhớ và giao diện bộ nhớ bên ngoài
Tích hợp bộ vi xử lý MAC / baseband
Chất lượng quản lý dịch vụ
Giao diện I2S cho độ trung thực cao ứng dụng âm thanh
On-chip thấp học sinh bỏ học điều chỉnh tuyến tính cho tất cả các nguồn cung cấp nội bộ
Kiến trúc giả miễn phí thế hệ đồng hồ độc quyền
Tích hợp WEP, TKIP, AES, và các công cụ WAPI

Thông số kỹ thuật esp8266:

Wifi 802.11 b/g/n
Wi-Fi Direct (P2P), soft-AP
Tích hợp giao thức TCP / IP stack
Tích hợp TR chuyển đổi, balun, LNA, bộ khuếch đại quyền lực và phù hợp với mạng
PLLs tích hợp, quản lý, DCXO và các đơn vị quản lý điện năng
+ Công suất đầu ra 19.5dBm ở chế độ 802.11b
Tích hợp công suất thấp 32-bit CPU có thể được sử dụng như là bộ vi xử lý ứng dụng
SDIO 1.1 / 2.0, SPI, UART
STBC, MIMO 1 × 1, 2 × 1 MIMO
A-MPDU & A-MSDU tập hợp & 0.4ms khoảng bảo vệ
Thức dậy và truyền tải các gói dữ liệu trong <2ms
Chế độ chờ tiêu thụ điện năng <1.0mW (DTIM3)


II: Module wifi ESP8266 kết nối với vi điều khiển.
Trong ứng dụng lấy dữ liệu thời tiết từ internet này mình sử dụng vi điều khiển Pic18f4550 của Microchip, module esp8266 được sử dụng là module esp-01


Module wifi esp8266
Sơ đồ chân của module ESP8266:


ESP8266 wifi module-ESP01
esp8266 pinout


ESP8266-Rboard-1
UTXD (TX) – chân truyền tín hiệu của module  nối với chân RX của vi điều khiển

URXD(RX) – chân truyền tín hiệu của module  nối với chân RX của vi điều khiển

RST – chân reset cứng của module. Reset xảy ra khi tín hiệu xuống mức thấp

GPIO0, GPIO2, CH_PD nối với mức cao.

VCC: Nối với 3.3V

GND: Nối với 0V

Để giao tiếp module ta sử dụng truyền các lệnh AT qua RS232 ở  tốc độ baud 115200.

//COMMAND
#define AT_ECHO_ON                  "ATE1"
#define AT_ECHO_OFF                 "ATE0"
#define AT_RESET                    "AT+RST"
#define AT_CFW                      "AT+GMR"
#define AT_WIFI_MODE                "AT+CWMODE"
#define AT_JOIN_AP                  "AT+CWJAP"
#define AT_GET_IP                   "AT+CIFSR"
#define AT_LIST_AP                  "AT+CWLAP"
#define AT_QUIT_AP                  "AT+CWQAP"
#define AT_SET_AP_PARAMS            "AT+CWSAP"
#define AT_CHECK_JOIN_AP            "AT+CWQAP"
#define AT_GET_CON_STATUS           "AT+CIPSTATUS"
#define AT_START_CON                "AT+CIPSTART"
#define AT_CIP_MODE                 "AT+CIPMODE"
#define AT_SEND                     "AT+CIPSEND"
#define AT_CLOSE_CON                "AT+CIPCLOSE"        
#define AT_SET_MUL_CON              "AT+CIPMUX=1"
#define AT_SET_SERVER               "AT+CIPSERVER"
#define AT_SET_SERVER_TIMEOUT       "AT+CIPSTO"
#define AT_RECEIVED_DATA            "+IPD"
Xem thêm tập lệnh AT của ESP8266: ESP8266 AT command

Các lệnh hay được sử dụng:

Steps and note
AT+RST restart the module, received some strange data, and “ready”
AT+CWMODe=3 change the working mode to 3, AP+STA, only use the most versatile mode 3 (AT+RST may be necessary when this is done.)
Join Router

AT+CWLAP search available wifi spot
AT+CWJAP=“you ssid”, “password” join my mercury router spot (ops, the wifi password is here :) )
AT+CWJAP=? check if connected successfully, or use AT+CWJAP?
TCP Client

AT+CIPMUX=1 turn on multiple connection
AT+CIPSTART=4,”TCP”,”192,168.1.104″,9999 connect to remote TCP server 192.168.1.104 (the PC)
AT+CIPMODE=1 optionally enter into data transmission mode
AT+CIPSEND=4,5 send data via channel 4, 5 bytes length (see socket test result below, only “elect” received), link will be “unlink” when no data go through
TCP Server

AT+CIPSERVER=1,9999 setup TCP server, on port 9999, 1 means enable
AT+CIFSR check module IP address
Trong ví dụ này mình cài đặt cho module esp8266 hoạt động ở chế độ client kết nối tới openweathermap.org thực hiện HTTP GET để lấy chuỗi json trả về, sau đó sẽ thực hiện việc phân tích chuổi json này để  lấy các thông tin về nhiệt độ, độ ẩm, áp suất khí quyển.

Link get data: http://api.openweathermap.org/data/2.5/weather?id=1581130

1581130 là id của Hà Nội-Việt Nam

Chuỗi json:


{
  "coord": {
    "lon": 105.84,
    "lat": 21.02
  },
  "sys": {
    "message": 0.0293,
    "country": "VN",
    "sunrise": 1414623502,
    "sunset": 1414664532
  },
  "weather": [
    {
      "id": 803,
      "main": "Clouds",
      "description": "broken clouds",
      "icon": "04d"
    }
  ],
  "base": "cmc stations",
  "main": {
    "temp": 300.516,
    "temp_min": 300.516,
    "temp_max": 300.516,
    "pressure": 1013.51,
    "sea_level": 1023.88,
    "grnd_level": 1013.51,
    "humidity": 88
  },
  "wind": {
    "speed": 1.87,
    "deg": 137.5
  },
  "clouds": {
    "all": 64
  },
  "dt": 1414656101,
  "id": 1581130,
  "name": "Ha Noi",
  "cod": 200
}
Ở đây ta sẽ lấy các thông tin trong phần tử “main”:

“temp”: 300.516,//Giá trị nhiệt độ (độ K)
“temp_min”: 300.516,
“temp_max”: 300.516,
“pressure”: 1013.51,//Giá trị áp suất
“sea_level”: 1023.88,
“grnd_level”: 1013.51,
“humidity”: 88//Giá trị độ ẩm

Code cho Pic18f4550 sử dụng CCS 5.025


#include <18F4550.h>
#DEVICE ADC=8              
#fuses HSPLL,MCLR,NOWDT,NOPROTECT,NOLVP,NODEBUG,USBDIV,PLL5,CPUDIV1,VREGEN
#use delay(clock=48000000)
#use rs232(UART1,baud=115200,parity=N,bits=8,stream=WIFI_ESP,errors)//Khai bao su dung uart cung
#include <usb_cdc.h>                              
#include <usb_desc_cdc.h>
#define ledv  PIN_C2                              
#define ledr  PIN_C1
#define ledon output_low                                    
#define ledoff output_high                  
#define led_on output_low                                                    
#define led_off output_high                                                    
#define LCD_ENABLE_PIN PIN_D2                
#define LCD_RS_PIN PIN_D0            
#define LCD_RW_PIN PIN_D1            
#define LCD_DATA4 PIN_D4                                        
#define LCD_DATA5 PIN_D5
#define LCD_DATA6 PIN_D6
#define LCD_DATA7 PIN_D7
#include <lcd.c>                                    
#include"esp/wifi.c"
#include"sonbui/mystr.c"

char *SSID_JOIN="TU HU";//"SonBui-AP";
char *PASS_JOIN="12345679";//"a12344321";
char *DATA_SEND="GET /data/2.5/weather?id=1581130 HTTP/1.0\r\nHost: api.openweathermap.org\r\n\r\n" ;     //1581130: Hanoi-Viet nam
char *WEATHER_IP= "188.226.224.148"; //api.openweathermap.org  
void get_internet()
{  
char *write = ">";
int1 OK = False;
printf(LCD_PUTC, "\fGData Hanoi,VN\nopenweathermap.org");
delay_ms(1000);
if( client_Start(0,TYPE_TCP,WEATHER_IP,80))   //kET NOI TOI SERVER DE LAY DU LIEU
{
printf(LCD_PUTC, "\fGet data");
int16 length=strlen(DATA_SEND);                                                        
DO
{
clear_mem();
fprintf(WIFI_ESP, AT_SEND);                  
fprintf(WIFI_ESP, "=%u", 0);    
fprintf(WIFI_ESP, ",%lu",length);
fprintf(WIFI_ESP, CRLF);
for (int mem_loop = 0; mem_loop < 150; mem_loop++) {

wifi_buff[n] = timed_getc();
n++;
if (n > 150) n = 0;
if (timeout_error) break;
}

char *pch = strstr(wifi_buff, write);

IF(pch) {
OK = TRUE;
break;                              
}
delay_ms(100);
}
WHILE(!OK);
//Send http get
clear_mem();    
printf(LCD_PUTC, "\fSend Get");
fprintf(WIFI_ESP, "%s",DATA_SEND);
Long LONG timeout;
timeout = 0;
WHILE(!kbhit(WIFI_ESP) && (++timeout < 2000000))  //20 second
{
delay_us(10);

}                                                      
WHILE(!(fgetc(WIFI_ESP)=='{')) ;      
printf(LCD_PUTC, "\f{");

wifi_buff[0]='{';n=1;                            
do {      
wifi_buff[n] = mili_getc();        
n++;                                        
if (n > 512) n = 0;

}while(!timeout_error) ;
printf(LCD_PUTC, "\fPrint Data");
//printf(usb_cdc_putc, "\r\nWF:%s"wifi_buff);
char *jstart="\"main\":{";
char *jstop=",\"wind\"";
char *p1 = strstr(wifi_buff,jstart);

if(p1)                            
{  
// printf(usb_cdc_putc, "\r\n\fp1:%s"p1);
char *p2 = strstr(p1,jstop);
if(p2)
{
// printf(usb_cdc_putc, "\r\n\fp2:%s"p2);
size_t len = p2-p1;
char *jmain = (char*)malloc(sizeof(char)*(len+1));
strncpy(jmain, p1, len);                                
jmain[len] = '\0';
// printf(usb_cdc_putc, "\r\nRes:%s"jmain);
char *temp="\"temp\":";
char *temp_min=",\"temp_min\":";  
char *ap_suat=",\"pressure\":";
char *ap_suat_end=",\"sea_level";
char *do_am="\"humidity\":";  
char *do_am_end="}";                            
double d_nhiet_do;
free(res) ;
char *nhiet_do=extract_string(temp,temp_min,jmain);
if(nhiet_do)                                                
{
// printf(usb_cdc_putc, "\r\nNhiet do:%s"nhiet_do);
d_nhiet_do = atof (nhiet_do);//treo neu gia tri nhiet do sai dinh dang
d_nhiet_do -= 273.15; //kelvin-celsius
printf (LCD_PUTC, "\fT=%f"d_nhiet_do);
}
free(res) ;
char *ap_suat_khi=extract_string(ap_suat,ap_suat_end,jmain);
if(ap_suat)
{
//  printf(usb_cdc_putc, "\r\nAp suat:%s"ap_suat_khi);
printf (LCD_PUTC, "\nP=%s hpa"ap_suat_khi);
}                                                        
free(res) ;                                                            
char *do_am_khi=extract_string(do_am,do_am_end,jmain);
if(do_am_khi)
{
// printf(usb_cdc_putc, "\r\nDo am khi:%s"do_am_khi);

lcd_gotoxy(10,1) ;                                  
printf (LCD_PUTC, "H=%s %%"do_am_khi);                
}
free(jmain) ;
}
}
}
else
{                                    
printf (LCD_PUTC, "\f Can't connect to\nopenweathermap.org");
delay_ms(1000);
}                        
}
void main()                          
{
lcd_init ();                                                                  
printf (LCD_PUTC, "\f MuaLinhKien.Vn\nPIC 16/18 Basic Kit");
delay_ms(1000);
printf (LCD_PUTC, "\fESP8266 Test\nmualinhkien.vn");
esp_init();
setup_AP(SSID_SET,PASS_SET,5,ECN_WAP2_PSK);                                                                                            
delay_ms(1000);
join_AP(SSID_JOIN,PASS_JOIN);          
delay_ms(1000);
client_Start(0,TYPE_TCP,WEATHER_IP,80);   //kET NOI TOI SERVER DE LAY DU LIEU
delay_ms(1000);
get_ip();
clear_mem();
//!   usb_cdc_init();
//!   usb_init();                                    
//!   usb_task();                                    
//!   usb_wait_for_enumeration();
//!     while(!usb_cdc_connected());                            
while (TRUE)                                                    
{                                                      
get_internet();
for(int loop=0;loop<120;loop++)    
{
output_toggle(ledr);
delay_ms(500);    
}

}
}
Wifi.c

/*
Dung while de doc du lieu tra ve
Dung ngat de lay du lieu bat ki
*/
#INCLUDE <stdlibm.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wifi.h>
char wifi_buff[512];          

int16 n = 0;
INT1 timeout_error;
INT8 timeout_error_count = 0;                        
char CRLF[] = "\r\n";                                                                                                          
char *SSID_SET = "VISMART.CO";
char *PASS_SET = "12345678";                                      
char *STR_OK="\r\nOK\r\n" ;                                        
char *STR_START=":" ;                                    
char data_out[50];    
                                               
void clear_mem(void) {                                          
   for (int16 mem_loop = 0; mem_loop < 512; mem_loop++) {
      if (wifi_buff[mem_loop] == '\0')
      break;        
      else
      wifi_buff[mem_loop] = '\0';
   }
   n = 0;          
}
void clear_data(void) {                                          
   for (int16 mem_loop = 0; mem_loop < 50; mem_loop++) {
      if (data_out[mem_loop] == '\0')
      break;        
      else
      data_out[mem_loop] = '\0';
   }
   n = 0;          
}

char timed_getc() {

   WHILE(!kbhit(WIFI_ESP));
   IF(kbhit(WIFI_ESP))  
   RETURN(fgetc(WIFI_ESP));                  
   ELSE
   {
   
      RETURN(0);
   }
}

char *send_AT_result(char *command) {

   clear_mem();
   fprintf(WIFI_ESP, "%s", command);
   fprintf(WIFI_ESP, CRLF);
   for (int mem_loop = 0; mem_loop < 150; mem_loop++) {

      wifi_buff[n] = timed_getc();
      n++;
      if (n > 150) n = 0;
      if (timeout_error) break;
   }
   return wifi_buff;
}                                              

void send_AT_OK(char *command) {
   int1 OK = False;
   char *oks = "OK";
   DO
   {
      clear_mem();
      fprintf(WIFI_ESP, "%s", command);
      fprintf(WIFI_ESP, CRLF);
      for (int mem_loop = 0; mem_loop < 150; mem_loop++) {

         wifi_buff[n] = timed_getc();
         n++;
         if (n > 150) n = 0;
         if (timeout_error) break;
      }

      char *pch = strstr(wifi_buff, oks);

      IF(pch) {
         OK = TRUE;
         break;
      }
      delay_ms(100);
   }
   WHILE(!OK);

                                                     
}

void esp_init() {
   int1 OK = False;
   char *oks = "OK";
   char *nc = "no change";      
do { //ATE0
      clear_mem();
     fprintf(WIFI_ESP, AT_RESET);
      fprintf(WIFI_ESP, CRLF);
   delay_ms(2000);
      fprintf(WIFI_ESP, AT_ECHO_OFF);
      fprintf(WIFI_ESP, CRLF);
      for (int mem_loop = 0; mem_loop < 150; mem_loop++) {

         wifi_buff[n] = timed_getc();
         n++;
         if (n > 150) n = 0;
         if (timeout_error) break;
      }
      char *pch = strstr(wifi_buff, oks);

      IF(pch) {
         OK = TRUE;
         printf(LCD_PUTC, "\fATE0");
      }
      delay_ms(100);
   }
   WHILE(!OK);

   //
   do { //AT+CWMODE=3
      clear_mem();                            
      fprintf(WIFI_ESP, MODE_AT_STA);
      fprintf(WIFI_ESP, CRLF);
      for (int mem_loop = 0; mem_loop < 150; mem_loop++) {

         wifi_buff[n] = timed_getc();
         n++;
         if (n > 150) n = 0;
         if (timeout_error) break;
      }

      char *pch = strstr(wifi_buff, oks);

      IF(pch) {
         OK = TRUE;
         printf(LCD_PUTC, "\fAT+CWMODE=3");
      } else {
         char *no_change = strstr(wifi_buff, nc);

         IF(no_change) {
            OK = TRUE;
            printf(LCD_PUTC, "\fAT+CWMODE=3\nNo change");
         }

      }
      delay_ms(100);
   }
   WHILE(!OK);

}

void setup_AP(unsigned char *ssid, unsigned char *password, int chl, int enc) {
   //AT+CWSAP="ssid","password",chl,enc
   int1 OK = False;
   char *oks = "OK";
   for (int loop = 0; loop < 5; loop++) {
      clear_mem();
      fprintf(WIFI_ESP, AT_SET_AP_PARAMS);
      fprintf(WIFI_ESP, "=\"%s\"", ssid);
      fprintf(WIFI_ESP, ",\"%s\"", password);
      fprintf(WIFI_ESP, ",%u", chl);
      fprintf(WIFI_ESP, ",%u", enc);
      fprintf(WIFI_ESP, CRLF);

      for (int mem_loop = 0; mem_loop < 150; mem_loop++) {

         wifi_buff[n] = timed_getc();
         n++;
         if (n > 150) n = 0;
         if (timeout_error) break;
      }

      char *pch = strstr(wifi_buff, oks);

      IF(pch) {
         OK = TRUE;
         printf(LCD_PUTC, "\fAT+CWSAP\nloop=%u", loop);
         break;
      }
      delay_ms(100);
   }
}

void join_AP(unsigned char *ssid, unsigned char *password) //Thuc hien mot lan vi khoi dong lai se tu ket noi
{
   //AT+CWJAP="ssid","password"
   int1 OK = False;
   char *oks = "OK";
   for (int loop = 0; loop < 3; loop++) {
      timeout_error_count = 0;
      printf(LCD_PUTC, "\fCn to:%s\nLan %u", ssid, loop);
      clear_mem();
      fprintf(WIFI_ESP, AT_JOIN_AP);
      fprintf(WIFI_ESP, "=\"%s\"", ssid);
      fprintf(WIFI_ESP, ",\"%s\"", password);
      fprintf(WIFI_ESP, CRLF);
      Long LONG timeout;
      timeout = 0;

      WHILE(!kbhit(WIFI_ESP) && (++timeout < 3000000)) //30 second      
      {    
         delay_us(10);
         if (timeout % 3000 == 0) {
            timeout_error_count++;
            lcd_gotoxy(10, 2);
            int pos = timeout_error_count % 4;
            if (pos == 0)
            printf(LCD_PUTC, "    ");
            if (pos == 1)              
            printf(LCD_PUTC, " .  ");
            if (pos == 2)
            printf(LCD_PUTC, "  . ");
            if (pos == 3)
            printf(LCD_PUTC, "   .");
         }            
      }
      for (int mem_loop = 0; mem_loop < 150; mem_loop++) {
         wifi_buff[n] = timed_getc();
         n++;
         if (n > 150) n = 0;
         if (timeout_error)
         break;
      }
      char *pch = strstr(wifi_buff, oks);

      IF(pch) {
         OK = TRUE;
         printf(LCD_PUTC, "\fCnt To:%s\nLoop=%u", ssid, loop);
         break;
      }
      ELSE
      {
         printf(LCD_PUTC, "\fCn To:%s\nError!", ssid);

      }
      delay_ms(100);
   }
}

void quit_AP() {
   //AT+CWQAP
   int1 OK = False;
   char *oks = "OK";
   DO
   {
      clear_mem();
      fprintf(WIFI_ESP, AT_QUIT_AP);
      fprintf(WIFI_ESP, CRLF);

      for (int mem_loop = 0; mem_loop < 150; mem_loop++) {

         wifi_buff[n] = timed_getc();
         n++;
         if (n > 150) n = 0;                    
         if (timeout_error) break;
      }

      char *pch = strstr(wifi_buff, oks);

      IF(pch) {
         OK = TRUE;
         printf(LCD_PUTC, "\fAT+CWQAP");
         break;
      }
      delay_ms(100);
   }                              
   WHILE(!OK);
}


void get_ip()
{
   //AT+CIFSR
   int1 OK = False;
   char *oks = "OK";
   DO
   {
      clear_mem();
      fprintf(WIFI_ESP, AT_GET_IP);
      fprintf(WIFI_ESP, CRLF);

      for (int mem_loop = 0; mem_loop < 150; mem_loop++) {

         wifi_buff[n] = timed_getc();
         n++;    
         if (n > 150) n = 0;                    
         if (timeout_error) break;
      }

      char *pch = strstr(wifi_buff, oks);

      IF(pch) {
         OK = TRUE;
         printf(LCD_PUTC, "\fIP:%s",wifi_buff);
         break;
      }
      delay_ms(100);
   }                              
   WHILE(!OK);

}
int1 client_Start(int id, int type, char *ip, unsigned int16 port)
{

   char *cmd = AT_SET_MUL_CON;
   int1 OK = False;
   char *oks = "OK";
   char *connected="ALREAY CONNECT"; //Ket noi da duoc ket noi tu truoc toi ip nay hoac ip khac voi id nay

 
 
   DO                  
   {
      char *pch = strstr(send_AT_result(cmd), oks);

      IF(pch) {
         OK = TRUE;
         printf(LCD_PUTC, "\f%s", AT_SET_MUL_CON);
         break;
      }
      delay_ms(100);
   }
   WHILE(!OK);
   //
   for (int loop = 0; loop < 5; loop++) {
      timeout_error_count = 0;
      printf(LCD_PUTC, "\f%s\nPort:%5lu    %u", ip, port, loop);
      clear_mem();                                              
      fprintf(WIFI_ESP, AT_START_CON);
      fprintf(WIFI_ESP, "=%u", id);
      if (type == TYPE_TCP)
      fprintf(WIFI_ESP, ",\"TCP\"");                                  
      else                                
      fprintf(WIFI_ESP, ",\"UDP\"");
      fprintf(WIFI_ESP, ",\"%s\"", ip);
      fprintf(WIFI_ESP, ",%lu", port);
      fprintf(WIFI_ESP, CRLF);
      Long LONG timeout;
      timeout = 0;
   
      WHILE(!kbhit(WIFI_ESP) && (++timeout < 3000000)) //30 second      
      {
         delay_us(10);
         if (timeout % 3000 == 0) {
            timeout_error_count++;
            lcd_gotoxy(11, 2);                      
            int pos = timeout_error_count % 4;          
            if (pos == 0)
            printf(LCD_PUTC, "    ");
            if (pos == 1)
            printf(LCD_PUTC, " .  ");
            if (pos == 2)                                
            printf(LCD_PUTC, "  . ");
            if (pos == 3)
            printf(LCD_PUTC, "   .");
         }
      }
      for (int mem_loop = 0; mem_loop < 150; mem_loop++) {
         wifi_buff[n] = timed_getc();
         n++;                        
         if (n > 150) n = 0;
         if (timeout_error)
         break;
      }
      char *pch = strstr(wifi_buff, oks); //chu y con "ALREAY CONNECT"

      IF(pch) {
         OK = TRUE;
         printf(LCD_PUTC, "\fIP:%s\nP:%5lu lan %u OK    ", ip, port, loop);
         break;                                
      }
      ELSE
      {
         char *link = strstr(wifi_buff, connected);  

         IF(link) {
            OK = TRUE;                                          
            printf(LCD_PUTC, "\fID CONNECTED!\nloop=%u", loop);
            break;    
         }      
         else                    
         {
         OK = FALSE;
         printf(LCD_PUTC, "\fIP:%s\nP:%5lu Error", ip, port);  
         }                                          

      }
      delay_ms(100);
 
   }
     return OK;
 
}
void server_Start(unsigned int16 port)   // Truoc khi chay phai restart                                  
{

   char *cmd = AT_SET_MUL_CON;
   int1 OK = False;
   char *oks = "OK";
   char *link_builded = "link is builded";

 
 
   DO
   {
      char *pch = strstr(send_AT_result(cmd), oks); //chu y:link is builded

      IF(pch) {
         OK = TRUE;
         printf(LCD_PUTC, "\f%s", AT_SET_MUL_CON);
         break;
      }
      else
      {
         char *pch = strstr(send_AT_result(cmd), link_builded); //chu y:link is builded

         IF(pch) {
            OK = TRUE;
            printf(LCD_PUTC, "\fLink is Builded");
            break;
         }
       
      }
      delay_ms(100);                                      
   }
   WHILE(!OK);
   //
   for (int loop = 0; loop < 5; loop++) {
      timeout_error_count = 0;
      printf(LCD_PUTC, "\fServ Port:%5lu\nLan %u", port, loop);
      clear_mem();                                              
      //AT+CIPSERVER=1,9999    

      fprintf(WIFI_ESP, AT_SET_SERVER);
      fprintf(WIFI_ESP, "=1");
      fprintf(WIFI_ESP, ",%lu", port);
      fprintf(WIFI_ESP, CRLF);
      Long LONG timeout;
      timeout = 0;
   
      WHILE(!kbhit(WIFI_ESP) && (++timeout < 3000000)) //30 second      
      {
         delay_us(10);      
         if (timeout % 3000 == 0) {
            timeout_error_count++;
            lcd_gotoxy(11, 2);                      
            int pos = timeout_error_count % 4;          
            if (pos == 0)
            printf(LCD_PUTC, "    ");
            if (pos == 1)
            printf(LCD_PUTC, " .  ");
            if (pos == 2)
            printf(LCD_PUTC, "  . ");
            if (pos == 3)
            printf(LCD_PUTC, "   .");
         }
      }
      for (int mem_loop = 0; mem_loop < 150; mem_loop++) {
         wifi_buff[n] = timed_getc();
         n++;
         if (n > 150) n = 0;      
         if (timeout_error)
         break;
      }
      char *pch = strstr(wifi_buff, oks);

      IF(pch) {
         OK = TRUE;                                                      
         printf(LCD_PUTC, "\fServ Port:%5lu\nLan %u OK", port, loop);
         break;
      }
      ELSE
      {
         printf(LCD_PUTC, "\fServ Port:%5lu\nLan %u Error!", port, loop);

      }
      delay_ms(100);            
   }

}
//Cip close khi ket noi toi server phai co id
//close ket noi toi clinet(modlue khac hoac may tinh) thi ko can

void  close_connect(int id) //Tra ve ok hoac "link is not"
{                                                                                      
   // AT+CIPCLOSE=<id>
   int1 OK = False;
   char *not_link="link is not";   //chua ket noi
   char *oks="OK";
   for (int loop = 0; loop < 5; loop++) {                                                          
      clear_mem();
      fprintf(WIFI_ESP, AT_CLOSE_CON);
      fprintf(WIFI_ESP, "=%u", id);  
      fprintf(WIFI_ESP, CRLF);                        

      for (int mem_loop = 0; mem_loop < 150; mem_loop++) {

         wifi_buff[n] = timed_getc();
         n++;
         if (n > 150) n = 0;
         if (timeout_error) break;                        
      }                                    

      char *pch = strstr(wifi_buff, oks);  

      IF(pch) {
         OK = TRUE;                                          
         printf(LCD_PUTC, "\fCLOSE CONNECT\nloop=%u", loop);
         break;
      }
      ELSE
      {
         char *link = strstr(wifi_buff, not_link);  

         IF(link) {
            OK = TRUE;                                          
            printf(LCD_PUTC, "\fNOT CONNECT\nloop=%u", loop);
            break;
         }
      }                                            
   }
}
void send_data(int id, char  *data)
{                                        
   // AT+CIPSEND= <id>,<length>
   int1 OK = False;              
   char *write = ">";
   char *send_ok="SEND OK";
   int16 length=strlen(data);
   for (int loop = 0; loop < 5; loop++) {                                                          
      clear_mem();                    
      fprintf(WIFI_ESP, AT_SEND);
      fprintf(WIFI_ESP, "=%u", id);  
      fprintf(WIFI_ESP, ",%lu",length);
      fprintf(WIFI_ESP, CRLF);                        

      for (int mem_loop = 0; mem_loop < 150; mem_loop++) {

         wifi_buff[n] = timed_getc();
         n++;
         if (n > 150) n = 0;
         if (timeout_error) break;
      }                                    

      char *pch = strstr(wifi_buff, write);

      IF(pch) {
         OK = TRUE;                                          
         printf(LCD_PUTC, "\fSEND >\nlenght=%lu", length);
       
       
         //Gui noi dung              
         char *sent = strstr(send_AT_result(data), send_ok);

         IF(sent) {            
            OK = TRUE;
            printf(LCD_PUTC, "\fSEND OK\nlenght=%lu", length);
            break;                  
         }      
      }                                
      else
      {
         OK = FALSE;                                          
         printf(LCD_PUTC, "\fSEND FAIL!\nloop=%u", loop);
      }
      delay_ms(100);                                              
   }                          
 
}


//Loi khi module reset ma client ko biet no dong      
Wifi.h


#define    ECN_OPEN          0      //Che do bao mat
#define    ECN_WEP           1
#define    ECN_WAP_PSK       2
#define    ECN_WAP2_PSK      3
#define    ECN_WAP_WAP2_PSK  4

#define    TYPE_TCP     1            //Che do ket noi
#define    TYPE_UDP     0                              

#define    TRAN_OPEN    1         //Che do truyen nhan        
#define    TRAN_CLOSE   0

#define    MODE_STA     "AT+CWMODE=1"         //Che do wifi
#define    MODE_AP      "AT+CWMODE=2"                                        
#define    MODE_AT_STA  "AT+CWMODE=3"

#define WIFI_TX_BUFFER_SIZE 128      //Bo dem
#define WIFI_RX_BUFFER_SIZE 128

//COMMAND
#define AT_ECHO_ON                  "ATE1"
#define AT_ECHO_OFF                 "ATE0"
#define AT_RESET                    "AT+RST"
#define AT_CFW                      "AT+GMR"
#define AT_WIFI_MODE                "AT+CWMODE"
#define AT_JOIN_AP                  "AT+CWJAP"
#define AT_GET_IP                   "AT+CIFSR"
#define AT_LIST_AP                  "AT+CWLAP"
#define AT_QUIT_AP                  "AT+CWQAP"
#define AT_SET_AP_PARAMS            "AT+CWSAP"
#define AT_CHECK_JOIN_AP            "AT+CWQAP"
#define AT_GET_CON_STATUS           "AT+CIPSTATUS"
#define AT_START_CON                "AT+CIPSTART"
#define AT_CIP_MODE                 "AT+CIPMODE"
#define AT_SEND                     "AT+CIPSEND"
#define AT_CLOSE_CON                "AT+CIPCLOSE"        
#define AT_SET_MUL_CON              "AT+CIPMUX=1"
#define AT_SET_SERVER               "AT+CIPSERVER"
#define AT_SET_SERVER_TIMEOUT       "AT+CIPSTO"
#define AT_RECEIVED_DATA            "+IPD"

( Full)
Khi nhấn nút "Tải Về Máy", bạn sẽ vào trang quảng cáo, vui lòng chờ 5 giây. Nút  hiện ra ở góc phải phía trên, nhấn vào để đến trang download

Điện Tử | Tin Học - eChipKool.Com - Chia sẻ kiến thức - Kết nối đam mê điện tử

Nguồn laptrinhpic.info