Arduino和Matlab之间的串行通信正在丢失数据 [英] Serial communication between Arduino and Matlab is losing data

查看:192
本文介绍了Arduino和Matlab之间的串行通信正在丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am now trying to establish the serial communication between Arduino and Matlab. The script is very simple:

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

Arduino收到此i,然后将其发送回Matlab;

Arduino receive this i, then send it back to Matlab;

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

Repeat step 1&2 for 10 times, i.e., Matlab sends 1,2,...,10 to Arduino, then receive the 1,2,...,10 from Arduino. However, Matlab only get back 3,4,...,10, while the first i=1 and i=2 are lost (I have already made the inputbuffersize=200 now, still not right).

这里是Matlab的代码:

Hereby is the code from 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代码:

And the Arduino Code:

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会重置自身,并且引导程序会等待潜在的草图上传.这会在草图实际运行之前增加一些延迟.

When you open the serial connection, the Arduino resets itself and the bootloader waits for potential sketch upload. This adds some delay before the sketch actually runs.

在打开串行连接后添加一个暂停.

Add a pause after you open the serial connection.

fopen(s);
pause(3);

还有其他选择:

  1. 通过将东西发送到PC,使Arduino在启动时宣布.例如,您要等到Arduino发送S.

我不确定MATLAB是否可以实现此功能,但是如果禁用串行的DTR引脚,则Arduino不会自动重置.

I am not sure if this is possible with MATLAB, but if you disable the serial's DTR pin, the Arduino won't auto reset.

直接与程序员一起刻录代码,因此没有等待引导的引导程序.但这也使您无法通过USB上传草图.

Burn the code directly with the programmer, so the there is no bootloader which waits at boot. But this also prevents you from uploading the sketch via the USB.

防止自动重置的硬件解决方案. 但这可以防止在草图上传期间进行必要的重新引导,因此您必须手动设置重置时间.

A hardware solution to prevent auto reset. But this prevents the necessary reboot during the sketch uploading, so you have to time the reset manually.

这篇关于Arduino和Matlab之间的串行通信正在丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆