1、介绍

从STM32接收到的数据中提取我们所需的数据,极大的便利了串口控制的流程。如:从“Z轴移动10mm”中,将10提取出来,并赋值给其他变量。

2、实现代码:

添加必要的头文件:

#include "Sensor.h"   //串口头文件
#include "string.h"
#include "stdio.h"
#include "stdlib.h"

添加所需变量:

unsigned char uartData[100] = "Z轴移动10mm";
char distance[5];

主要代码:

if (Serial_RxFlag == 1)		//如果接收到数据包
		{
			strcpy(uartData, Serial_RxPacket);
			char *dacPos = strstr(uartData, "Z轴移动");
       if (dacPos != NULL)  // 如果找到了
       {
         // 移动到"Z轴移动"后面的字符位置
         char *currentPos = dacPos + strlen("Z轴移动");

            // 从当前位置开始提取数字,直到遇到非数字字符
         char distance[20]; // 假设距离字符串不会超过20个字符
         int i = 0;
         while (*currentPos >= '0' && *currentPos <= '9' && i < sizeof(distance) - 1) 
					 {
             distance[i++] = *currentPos++;
           }
            distance[i] = '\0'; // 添加字符串结束符
			// 将提取到的数字字符串转换为整数并赋值给Z_target_distance
			Z_target_distance = (int)atoi(distance);
       
            printf("Z轴已移动: %d\n", Z_target_distance);
        }
			
			Serial_RxFlag = 0;			
		}	

3、演示

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐