The development board sends and receives data to the mobile phone through the wifi module in the UDP connection mode

foreword

This article mainly explains that the STM32F103_MINI [development board] sends and receives data to the mobile phone through the wifi module in the UDP connection mode. We need to understand the UDP connection process and program code.

1. [UDP] connection process

The main operations of the UDP connection process are: reset → mode setting → WIFI connection → view ip → create UDP connection → send data → receive data

2. Use steps

1. Create a [header file]

The code is as follows (example):

#include "main.h"
#include "usart.h"
#include "gpio.h"
#include <stdio.h>
void SystemClock_Config(void);
static void MX_NVIC_Init(void);
#include <stdio.h>
#include <string.h>

2. Data establishment

The code is as follows (example):

int  main ( void )
 {
   /* USER CODE BEGIN 1 */ 
  uint8_t rx_len = 0 ;                 // data receive length 
  uint8_t rx_data[ 200 ] = { 0 };         // save received data 
  uint8_t tx_data[ 200 ] = "AT\r\ n" ;    // save send data

  HAL_Init();
  SystemClock_Config();
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();

  MX_NVIC_Init();

  USART_StartRx();    //Start to receive data

The data requested by the url used here.

3. UDP connection process

The code is as follows (example):

ESP8266_SendCommand("AT+RST", "OK", 500);
  HAL_Delay(800);
  ESP8266_SendCommand("AT+CWMODE=1", "OK", 500);
  ESP8266_SendCommand("AT+CWJAP=\"NETGEAR\",\"100ask.cq\"", "OK", 5000);
  ESP8266_SendCommand("AT+CIPSTART=\"UDP\",\"192.168.50.230\",9999,9999,2", "OK", 500);
  ESP8266_GetIP();

3. Send data

The code is as follows (example):

while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */ 
     //Key pressed 
     if (Key_GetFlag())
     {
        ESP8266_Send_UDP("{\"data\":\"doorbell\",\"status\":\"1\"}");
     }

     //Receive UDP data 
     if (USART2_Receive(rx_data))
     {
         //printf("%s\r\n", rx_data);
         if (strstr((char *)rx_data, "\"dev\":\"led\",\"status\":\"0\"")) 
         {
            printf("led off\r\n");
            HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
            USART2_ClearBuf(); 
            memset(rx_data, 0, 200);
         }
         else if (strstr((char *)rx_data, "\"dev\":\"led\",\"status\":\"1\""))
         {
            printf("led on\r\n");
            HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);
            USART2_ClearBuf(); 
            memset(rx_data, 0, 200);             
         }
     }

  }

Summarize

The above is what I want to talk about today. This article only introduces the UDP connection process and the writing of the program, and the UDP connection process can give us a better understanding of the wifi connection protocol of the Internet of Things.

Leave a Comment

Your email address will not be published. Required fields are marked *