使用matlab确定从UART读取多少数据



我目前正在从我的生命线中提取数据;我有一个PSoC 4连接到uart,它发送得很好(所有时间,每个数据之间有20ms延迟),然后我有matlab来接收数据。

我使用的是fscanf(s, '%d')函数,它返回大约3个数字,由uart发送,下面的例子:

s = serial('COM3'); %assigns the object s to serial port
set(s, 'InputBufferSize', 1024); %number of bytes in inout buffer
set(s, 'FlowControl', 'hardware');
set(s, 'BaudRate', 115200);
set(s, 'Parity', 'none');
set(s, 'DataBits', 8);
set(s, 'StopBit', 1);
set(s, 'Timeout',0.5);
%clc;
disp(get(s,'Name'));
prop(1)=(get(s,'BaudRate'));
prop(2)=(get(s,'DataBits'));
prop(3)=(get(s, 'StopBit'));
prop(4)=(get(s, 'InputBufferSize'));
disp(['Port Setup Done!!',num2str(prop)]);
         %opens the serial port
disp('Running');
fopen(s);
b = fscanf(s, '%d') 
-------------------------------------------------------------------------------------------
Matlab terminal:
b  = 
-213
-205
-215

程序获取3个数字,我想只获取第一个(-213)顺便说一句,这个数字可以是16000到- 16000之间的任何数字

不使用fscanf,您可以使用read来读取特定数量的字节。

https://uk.mathworks.com/help/matlab/ref/serial.fread.html

在s = serial('COM3')的情况下,要读取一个字节,您将写入:

b = fread(s, 1, 'uchar');

其中参数为:obj, size, 'precision'

注。当你完成时,不要忘记fclose(s)串口,这样你就可以再次运行程序,而不会得到"Obj已经打开"的错误:)

祝你一切顺利。

最新更新