我试图测试matlab和arduino之间的通信,并发生一些奇怪的事情。 我尝试使用数字1到10来接收它们。它适用于2,3,4 .... 10但是1我得到:
警告:读取失败:超时期限内未返回指定数量的数据。
如果我再次运行它,我会得到相同的结果。为1我得到错误,我得到2到10.我没有重置运行之间的arduino。那是奇怪的部分。
我的arudino代码:
uint32_t next_number;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
next_number = 0;
}
void loop() {
if (Serial.available() >= sizeof(next_number)) {
uint8_t data_read = Serial.readBytes((uint8_t*)&next_number, sizeof(next_number));
Serial.write((uint8_t*)&next_number, 4);
digitalWrite(13, HIGH);
}
}
我的Matlab代码:
function send_song_to_arduino()
delete(instrfind);
s = serial('COM3');
disp(['s input buffer size ', num2str(s.InputBufferSize)]);
set(s,'Terminator','LF'); % define the terminator for println
set(s,'Databits',8);
set(s,'Stopbits',1);
set(s,'Parity','none');
set(s, 'BaudRate', 9600);
fopen(s);
disp(['available at start ', num2str(s.bytesavailable)]);
disp(['left to send at start ', num2str(s.BytesToOutput)]);
if (s.bytesavailable > 0)
fread(s, s.bytesavailable, 'uint8')
end
disp('starting');
for i=1:10
fwrite(s, i, 'uint32');
pause(1);
disp(['available ', num2str(s.bytesavailable)]);
received = fread(s, 1, 'uint32');
disp(['recv ', mat2str(received)]);
end
disp(['done available ', num2str(s.bytesavailable)]);
disp(['total sent ', num2str(s.ValuesSent)]);
disp(['left to send at end ', num2str(s.BytesToOutput)]);
fclose(s);
delete(s);
end
结果:
>> send_song_to_arduino
available at start 0
left to send at start 0
starting
available 0
Warning: Unsuccessful read: The specified amount of data was not returned within the Timeout period.
recv zeros(1,0)
available 4
recv 2
available 4
recv 3
available 4
recv 4
available 4
recv 5
available 4
recv 6
available 4
recv 7
available 4
recv 8
available 4
recv 9
available 4
recv 10
done available 0
total sent 10
left to send at end 0
答案 0 :(得分:0)
我的解决方案: 显然,matlab串口打开重置arduino。 arudino端的序列需要一些时间才能启动,因此第一个请求在arduino准备好之前发送。我刚刚在fopen之后添加了一个暂停。