matlab - Arduino 和 Matlab 之间的串行通信丢失数据

标签 matlab arduino serial-port

我现在正在尝试建立Arduino和Matlab之间的串行通信。脚本非常简单:

  1. Matlab 向 Arduino 发送一个名为 i 的数字;

  2. Arduino收到这个i,然后将其发送回Matlab;

重复步骤1&2 10次,即Matlab发送1,2,...,10到Arduino,然后从Arduino接收1,2,...,10。然而,Matlab只返回3,4,...,10,而第一个i=1和i=2丢失了(我现在已经使inputbuffersize=200,仍然不对)。

这是来自 Matlab 的代码:

clc,clear;
s=serial('COM16','BaudRate',9600); 
s.InputBufferSize = 200;    
fopen(s);
a=10;
rx = zeros(1, a); % rx is used to store the data send back by Arduino
ry = zeros(1, a); % ry is just helping me to see what happens in Serial
for i = 1:1:a
  fwrite(s, i); % Start to write the value "i" through serial to Arduino
  pause(0.5) % if no pause, the result is worse than now
  ry(i) = s.BytesAvailable; % check how many data are there in the Buffer
  if s.BytesAvailable>0
      rx(i) = fread(s, s.BytesAvailable); % Record the data send by Arduino
  end
end
fclose(s);

以及 Arduino 代码:

char ibyte;
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  if(Serial.available()>0)
  {
    ibyte=Serial.read();
    Serial.write(ibyte);
  }
}

我的引用链接是:http://robocv.blogspot.com/2012/01/serial-communication-between-arduino.html

最佳答案

当您打开串行连接时,Arduino 会自行重置,引导加载程序会等待潜在的草图上传。这会在草图实际运行之前增加一些延迟。

打开串行连接后添加暂停。

fopen(s);
pause(3);

还有其他选项:

  1. 通过向 PC 发送一些内容,让 Arduino 宣布其启动时间。例如,您等待 Arduino 发送 S

  2. 我不确定 MATLAB 是否可以实现这一点,但如果您禁用串口的 DTR 引脚,Arduino 将不会自动重置。

  3. 直接用编程器烧写代码,这样就没有 Bootstrap 在启动时等待。但这也会阻止您通过 USB 上传草图。

  4. A hardware solution to prevent auto reset.但这会阻止在草图上传期间进行必要的重新启动,因此您必须手动安排重置时间。

关于matlab - Arduino 和 Matlab 之间的串行通信丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51728813/

相关文章:

matlab - 从特征值分解中恢复原始矩阵

C# SerialPort不支持高波特率

C# Raspberry pi Linux 串行端口权限即使作为 root 也被拒绝

android - 使用 HC-06 蓝牙模块从 Android 向 Arduino 发送数据

c++ - ReadFile Timeout 字节间延迟时间

matlab - 计算以零分隔的回合数

matlab - 如何将起始目录(在 Matlab 中使用 uigetfile)设置为 'Computer'?

bash - 从命令行/bash 测试 Matlab 许可证是否正在使用

python - 蓝牙错误(11、资源暂时不可用)

c - 如何通过串行读取在 Arduino LCD 上存储两条单独的线