打印
[应用相关]

STM32串口提取所需数据

[复制链接]
366|8
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
tpgf|  楼主 | 2024-7-18 16:49 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
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 = '\0'; // 添加字符串结束符
                        // 将提取到的数字字符串转换为整数并赋值给Z_target_distance
                        Z_target_distance = (int)atoi(distance);

            printf("Z轴已移动: %d\n", Z_target_distance);
        }
                       
                        Serial_RxFlag = 0;                       
                }       

3、演示





————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/m0_64386340/article/details/140388502

使用特权

评论回复
沙发
狗啃模拟| | 2024-7-31 23:32 | 只看该作者
你提供的代码已经很接近正确解决方案了,但还有一些改进的空间。特别是代码中 distance 数组的处理,以及对 atoi 和字符串结束符的处理,可以进行优化。

使用特权

评论回复
板凳
狗啃模拟| | 2024-7-31 23:32 | 只看该作者
修改后的代码
c

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

// 变量定义
unsigned char uartData[100] = "Z轴移动10mm";
char distance[20]; // 确保足够的长度来存储数字

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

            // 从当前位置开始提取数字,直到遇到非数字字符
            int i = 0;
            while (*currentPos >= '0' && *currentPos <= '9' && i < sizeof(distance) - 1) {
                distance[i++] = *currentPos++;
            }
            distance[i] = '\0'; // 添加字符串结束符

            // 将提取到的数字字符串转换为整数
            int Z_target_distance = (int)atoi(distance);

            // 打印结果
            printf("Z轴已移动: %d\n", Z_target_distance);
        }

        // 重置接收标志
        Serial_RxFlag = 0;
    }
}


使用特权

评论回复
地板
为你转身| | 2024-8-31 13:29 | 只看该作者
这个代码的目的是从接收到的串口数据中提取出距离值,并将其用于进一步处理。

使用特权

评论回复
5
为你转身| | 2024-8-31 13:45 | 只看该作者
在提取距离的 distance 数组中,声明的长度应足够存放提取的内容及字符串结束符。你已经在后面重新声明了 distance 为长度为20的数组,建议使用这个长度。

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

1754

主题

15166

帖子

10

粉丝