Reputation: 556
Im trying to test communication between matlab and arduino and something weird happen. I try the numbers 1 to 10 to receive them back. It works for 2,3,4....10 but for 1 i get:
Warning: Unsuccessful read: The specified amount of data was not returned within the Timeout period.
If i run it again i get the same results. for 1 i get error and i get 2 to 10. I dont reset the arduino between runs. Thats the weird part.
My arudino code:
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);
}
}
My Matlab code:
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
Results:
>> 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
Upvotes: 0
Views: 249
Reputation: 556
My solution: Apperently, matlab serial open resetting the arduino. The serial on the arudino side take some time to start so the first request is sent before the arduino is ready. I just added a pause after the fopen.
Upvotes: 0