I am using an Arduino UNO in a project at school. We are trying to communicate serially between the Arduino and Matlab. I am having issues getting communication between the two. My Matlab and Arduino code is shown below. If I step through the Matlab code using breakpoints, I get the exact behavior I would expect. Three bytes are transmitted from Matlab, and those three bytes are echoed back to Matlab by the Arduino. However, if I run the code without breakpoints then I don't get any response from the Arduino. I have verified that the Rx signal lights up on the Arduino when I am transmitting to it. Also, I have tried many different delays on both the Arduino end and the Matlab end. I have tried delays ranging anywhere from 0s - 2s.
The Matlab code on my 2.2GHz Core i7 is going to execute far faster than the 16MHz clock frequency of the Arduino. However, the input buffer to the Arduino should be filling up as Matlab is asynchronously transmitting data to it (especially if delays are used). Since I am not exceeding the 64 byte serial input buffer, I wouldn't expect this would be causing the issues. What else am I overlooking? Serial communication should be trivial between Matlab and the UNO.
Matlab
% Connect to Arduino the specified port
Port = '/dev/tty.usbmodem1451';
BaudRate = 9600;
DataBits = 8;
% Create the serial connection and open communication with the Arduino.
ser = serial(Port, 'BaudRate', BaudRate, 'DataBits', DataBits);
pause(0.5);
fopen(ser);
n = 3;
for i=1:n
fprintf(ser, '%u', i);
pause(.002);
end
display(ser.BytesAvailable);
A = fread(ser, n);
fclose(ser);
Arduino Sketch
void setup() {
int baud = 9600;
Serial.begin(baud);
}
void loop() {
long pause = 2; // Delay in milliseconds
if(Serial.available() > 0) {
byte b = Serial.read();
// echo the data back to Matlab
Serial.write(b);
delay(pause);
}
}