STM32串口提取所需数据

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、演示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值