Main Content

使用串行端口通信从 Arduino 读取流数据

此示例说明如何使用 serialport 接口启用回调以从 Arduino® Due 读取以 ASCII 字符结尾的流数据。

在 Arduino 上加载程序

将 Arduino Due 插入您的计算机。

使用 Arduino IDE 在 Arduino Due 上加载以下程序。此程序输出连续正弦波点,然后是“回车”和“换行”终止符。

/*
 SineWavePoints
 
 Write sine wave points to the serial port, followed by the Carriage Return and LineFeed terminator.
 */

int i = 0;

// The setup routine runs once when you press reset:
void setup() {
  // Initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// The loop routine runs over and over again forever:
void loop() {
  // Write the sinewave points, followed by the terminator "Carriage Return" and "Linefeed".
  Serial.print(sin(i*50.0/360.0));
  Serial.write(13);
  Serial.write(10);
  i += 1;
}

与 Arduino 建立连接

创建一个 serialport 实例来连接到您的 Arduino Due。

找到 Arduino 连接到的串行端口。您可以从 Arduino IDE 中识别该端口。

serialportlist("available")'
ans = 3×1 string
    "COM1"
    "COM3"
    "COM13"

通过使用 Arduino 代码中指定的端口和波特率创建 serialport 对象,连接到 Arduino Due。

arduinoObj = serialport("COM13",9600)
arduinoObj = 
Serialport with properties

                 Port: "COM13"
             BaudRate: 9600
    NumBytesAvailable: 0
      NumBytesWritten: 0

Show all properties

准备 serialport 对象以开始流式传输数据

通过清除旧数据并配置其属性来配置 serialport 对象。

Terminator 属性设置为与您在 Arduino 代码中指定的终止符匹配。

configureTerminator(arduinoObj,"CR/LF");

清空 serialport 对象以删除所有旧数据。

flush(arduinoObj);

准备 UserData 属性来存储 Arduino 数据。结构体的 Data 字段保存正弦波值,Count 字段保存正弦波的 x 轴值。

arduinoObj.UserData = struct("Data",[],"Count",1)
arduinoObj = 
Serialport with properties

                 Port: "COM13"
             BaudRate: 9600
    NumBytesAvailable: 10626
      NumBytesWritten: 0

Show all properties

创建一个回调函数 readSineWaveData,它读取前 1000 个以 ASCII 字符结尾的正弦波数据点并绘制结果。

function readSineWaveData(src, ~)

% Read the ASCII data from the serialport object.
data = readline(src);

% Convert the string data to numeric type and save it in the UserData
% property of the serialport object.
src.UserData.Data(end+1) = str2double(data);

% Update the Count value of the serialport object.
src.UserData.Count = src.UserData.Count + 1;

% If 1001 data points have been collected from the Arduino, switch off the
% callbacks and plot the data.
if src.UserData.Count > 1001
    configureCallback(src, "off");
    plot(src.UserData.Data(2:end));
end
end

BytesAvailableFcnMode 属性设置为 "terminator",将 BytesAvailableFcn 属性设置为 @readSineWaveData。当可以从 Arduino 读取新正弦波数据(带终止符)时,会触发回调函数 readSineWaveData

configureCallback(arduinoObj,"terminator",@readSineWaveData);

该回调函数会打开 MATLAB® 图窗窗口,图窗窗口中会显示前 1000 个正弦波数据点的绘图。