Proteus仿真单片机STM32F103的TCP通信4

张开发
2026/7/2 11:31:02 15 分钟阅读
Proteus仿真单片机STM32F103的TCP通信4
proteus单片机AP服务端与手机客户端通信proteus单片机-usbwifi模块AP服务端-无线网卡-网络调试助手手机客户端1.单片机端服务端程序#includemain.h#includeusart.h#includegpio.h/* Private includes ----------------------------------------------------------*//* USER CODE BEGIN Includes */#includestring.h#includecJSON.h#includestdio.h#includestdlib.h#ifdef__GNUC__#definePUTCHAR_PROTOTYPEint__io_putchar(intch)#else#definePUTCHAR_PROTOTYPEintfputc(intch,FILE*f)#endifPUTCHAR_PROTOTYPE{HAL_UART_Transmit(huart1,(uint8_t*)ch,1,0xFFFF);returnch;}intfputc(intch,FILE*f){HAL_UART_Transmit(huart1,(uint8_t*)ch,1,0xffff);returnch;}intfgetc(FILE*f){uint8_tch0;HAL_UART_Receive(huart1,ch,1,0xffff);returnch;}uint8_trx_buffer[256];// 接收缓冲区uint8_trx_data;// 单字节接收数据uint16_trx_index0;// 缓冲区索引uint8_tjson_received0;// JSON数据接收标志/* USER CODE END Includes *//* Private typedef -----------------------------------------------------------*//* USER CODE BEGIN PTD *//* USER CODE END PTD *//* Private define ------------------------------------------------------------*//* USER CODE BEGIN PD *//* USER CODE END PD *//* Private macro -------------------------------------------------------------*//* USER CODE BEGIN PM *//* USER CODE END PM *//* Private variables ---------------------------------------------------------*//* USER CODE BEGIN PV *//* USER CODE END PV *//* Private function prototypes -----------------------------------------------*/voidSystemClock_Config(void);/* USER CODE BEGIN PFP */// 读取字符串中两个字符之间的字符串并包含这两个字符voidextractStringBetweenChars(constchar*input,charstartChar,charendChar,char*output){constchar*startstrchr(input,startChar);if(startNULL){output[0]\0;return;}constchar*endstrchr(start1,endChar);if(endNULL){output[0]\0;return;}intlengthend-start1;strncpy(output,start,length);output[length]\0;//末尾添加\0}// 处理JSON数据voidProcessJSON(char*json_str){cJSON*rootcJSON_Parse(json_str);// 解析JSON字符串outputif(rootNULL){printf(JSONPARSEFAIL: %s\n,cJSON_GetErrorPtr());return;}// 提取JSON字段cJSON*ledcJSON_GetObjectItem(root,led);cJSON*beepcJSON_GetObjectItem(root,beep);cJSON*tempcJSON_GetObjectItem(root,temp);if(ledbeeptemp){printf(led:%s,beep:%d,temp:%d\n,led-valuestring,beep-valueint,temp-valueint);}else{printf(JSONFIELDNULL\n);}cJSON_Delete(root);// 释放JSON对象}voidcommand(charCommand_AT[]){intLenthstrlen(Command_AT);HAL_UART_Transmit(huart2,(uint8_t*)Command_AT,Lenth,0xff);printf(%s,Command_AT);HAL_Delay(3500);}voidwifiSend(chardata[]){uint8_tLenthstrlen(data);charsendBuff[30];sprintf(sendBuff,ATCIPSEND0,%d\r\n,Lenth);command(sendBuff);HAL_UART_Transmit(huart2,(uint8_t*)data,Lenth,0xff);}// 初始化ESP8266voidESP8266_Init(void){constchar*init_commands[]{ATRST\r\n,// 重启ESP8266ATCWMODE2\r\n,// 设置为AP模式ATCWSAP\MCU\,\\,3,0\r\n,// 配置AP名称和密码ATCIPMUX1\r\n,// 启用多连接ATCIPSERVER1,8899\r\n,// 启动TCP服务器端口8080};for(inti0;isizeof(init_commands)/sizeof(init_commands[0]);i){HAL_UART_Transmit(huart2,(uint8_t*)init_commands[i],strlen(init_commands[i]),HAL_MAX_DELAY);HAL_Delay(1000);// 等待ESP8266响应}}/* USER CODE END PFP *//* Private user code ---------------------------------------------------------*//* USER CODE BEGIN 0 *//* USER CODE END 0 *//** * brief The application entry point. * retval int */intmain(void){/* USER CODE BEGIN 1 */charoutput[50];/* USER CODE END 1 *//* MCU Configuration--------------------------------------------------------*//* Reset of all peripherals, Initializes the Flash interface and the Systick. */HAL_Init();/* USER CODE BEGIN Init *//* USER CODE END Init *//* Configure the system clock */SystemClock_Config();/* USER CODE BEGIN SysInit *//* USER CODE END SysInit *//* Initialize all configured peripherals */MX_GPIO_Init();MX_USART1_UART_Init();MX_USART2_UART_Init();/* USER CODE BEGIN 2 */ESP8266_Init();// 启用UART接收中断HAL_UART_Receive_IT(huart2,rx_data,1);/* USER CODE END 2 *//* Infinite loop *//* USER CODE BEGIN WHILE */while(1){if(json_received){json_received0;// 清除标志extractStringBetweenChars((char*)rx_buffer,{,},output);printf(\r\nss:%s%d\r\n,output,strlen(output));ProcessJSON((char*)output);// 处理JSON数据rx_index0;// 重置缓冲区索引memset(rx_buffer,0,sizeof(rx_buffer));// 清空缓冲区wifiSend(MCUserver\r\n);}HAL_Delay(1000);/* USER CODE END WHILE *//* USER CODE BEGIN 3 */}/* USER CODE END 3 */}// UART接收中断回调函数voidHAL_UART_RxCpltCallback(UART_HandleTypeDef*huart){if(huart-InstanceUSART2){if(rx_data\n){// 检测到换行符表示JSON数据接收完成rx_buffer[rx_index]\0;// 添加字符串结束符json_received1;// 设置标志}else{rx_buffer[rx_index]rx_data;// 存储数据}HAL_UART_Receive_IT(huart2,rx_data,1);// 重新启用中断}}2.鸿蒙手机端客户端程序import{socket}fromkit.NetworkKit;import{BusinessError}fromkit.BasicServicesKit;// 创建一个TCPSocket连接返回一个TCPSocket对象。let tcp:socket.TCPSocketsocket.constructTCPSocketInstance();// 绑定本地IP地址和端口。let ipAddress:socket.NetAddress{}as socket.NetAddress;ipAddress.address10.0.2.15;//固定ipAddress.port8080;//任意class SocketInfo{message:ArrayBuffernewArrayBuffer(1);remoteInfo:socket.SocketRemoteInfo{}as socket.SocketRemoteInfo;}Entry ComponentstructIndex{State message:stringHello World;State senddata:stringIm a client.State ipAddresst:socket.NetAddress{}as socket.NetAddress;State showDatas:string[][]//用于接收客服端发送的消息build(){Column({space:5}){Text(TCP客户端).fontSize(35).fontColor(#ffffff).margin({top:60,bottom:10})Button(绑定连接)//-设置PC机本地IP、PORT.fontSize(25).width(80%).onClick((){ipAddress.address10.0.2.15;//固定服务端的为10.0.2.2ipAddress.port8899;//任意tcp.bind(ipAddress,(err:BusinessError){if(err){console.log(bind fail);return;}console.log(bind success);});})Row({space:5}){Text(服 务 端ip:).width(40%).fontSize(20).textAlign(TextAlign.End)TextInput({placeholder:192.168.1.1}).fontSize(20).width(60%).onChange((value){this.ipAddresst.addressvalue;//this.ipAddresst.address 192.168.0.104;})}Row({space:5}){Text(服务端port:).width(40%).fontSize(20).textAlign(TextAlign.End)TextInput({placeholder:8899}).fontSize(20).width(60%).type(InputType.Number).onChange((value){this.ipAddresst.portparseInt(value)//this.ipAddresst.port 8899;})}Button(创建连接).fontSize(25).width(80%).onClick((){tcp.on(message,(value:SocketInfo){console.log(on message);let buffervalue.message;let dataViewnewDataView(buffer);let receivedatafor(let i0;idataView.byteLength;i){receivedataString.fromCharCode(dataView.getUint8(i));}this.showDatas.push(服务端receivedata)console.log(on connect received:receivedata);});tcp.on(connect,(){console.log(on connect);});tcp.on(close,(){console.log(on close);});// 连接到指定的IP地址和端口。//this.ipAddresst.address 192.168.0.104;//this.ipAddresst.port 8899;let tcpConnect:socket.TCPConnectOptions{}as socket.TCPConnectOptions;tcpConnect.addressthis.ipAddresst;tcpConnect.timeout6000;tcp.connect(tcpConnect).then((){console.log(connect success);}).catch((err:BusinessError){console.log(connect fail);});})TextInput({text:{led:on,beep:1,temp:45},placeholder:请输入发送的数据}).fontSize(25).width(85%).onChange((value){this.senddatavalue})Button(发送).width(80%).fontSize(20).onClick((){let tcpSendOptions:socket.TCPSendOptions{data:this.senddata}tcp.send(tcpSendOptions).then((){console.log(send success);}).catch((err:BusinessError){console.log(send fail);});})Text(关闭连接).fontSize(20).fontWeight(FontWeight.Bold).onClick((){// 连接使用完毕后主动关闭。取消相关事件的订阅。setTimeout((){tcp.close().then((){console.log(close success);}).catch((err:BusinessError){console.log(close fail);});tcp.off(message);tcp.off(connect);tcp.off(close);},30*1000);})Text(服务端接收数据:).width(85%).fontSize(20)List(){ForEach(this.showDatas,(item:string){ListItem(){Text(item).fontSize(20)}})}.width(95%).backgroundColor(0x3d9140)}.backgroundColor(0x228B22).height(100%).width(100%)}}

更多文章