Scilab串口通信:如何在数据接收及换行/回车时生成时间戳
在Scilab中为串口接收的每行数据添加时间戳
核心思路是在成功读取到带换行/回车的完整一行数据时,立即记录当前时间,以此作为该条数据的实际接收时间戳。以下是具体实现方案:
修改串口行读取函数,添加时间戳获取
基于你提供的readserialline函数,修改为同时返回数据和对应时间戳的版本:
function [data, timestamp] = readserialline_with_timestamp(h) tmpbuf = emptystr(); while tmpbuf == emptystr() TCL_EvalStr("binary scan [gets "+h+"] cu* ttybuf"); tmpbuf = ascii(evstr(TCL_GetVar("ttybuf"))); end data = tmpbuf; // 获取毫秒级精度的时间数组:[年,月,日,时,分,秒(含小数)] time_details = clock(); // 格式化为可读的时间戳字符串,如"2024-05-20 14:30:45.678" timestamp = msprintf("%04d-%02d-%02d %02d:%02d:%06.3f", ... time_details(1), time_details(2), time_details(3), ... time_details(4), time_details(5), time_details(6)); endfunction
主程序调用示例
在串口通信的主逻辑中,调用修改后的函数即可获取每条数据的接收时间:
// 假设已完成串口初始化,句柄为h while %t [line_data, ts] = readserialline_with_timestamp(h); // 输出带时间戳的数据,或写入文件存储 disp(msprintf("[%s] %s", ts, line_data)); // 可自定义退出条件,比如收到"exit"指令时停止 if strcmp(line_data, "exit") == 0 then break; end end
关键说明
gets命令会在检测到换行/回车符时返回完整一行数据,此时调用clock()获取的时间就是该行数据接收完成的精准时间clock()返回的秒数包含小数部分,可提供毫秒级精度,满足多数串口数据记录需求- 确保已正确安装Scilab的serial工具箱
内容的提问来源于stack exchange,提问作者Kwas Poser
相关产品推荐
相关产品推荐

