Setting the baud rate in MATLAB without calling the serial function

Hi all,

I’m trying to set the baud rate in MATLAB using the a=arduino() route instead of the s=serial(‘COMX’) route.

Essentially, I’m dealing small signal processing and I don’t want to lose arduino’s 10 bit precision so in arduino I read the pin, break the value into a high and low byte, and write it to the serial.

void setup() {
  Serial.begin(115200);

}

void loop() {
int sensorValue = analogRead(A0);
byte myVar_HighByte = highByte(sensorValue); // get the high byte
byte myVar_LowByte = lowByte(sensorValue); // get the low byte
  // x86 compatible machines are little-endian so we send the low byte first
Serial.write(myVar_LowByte);
Serial.write(myVar_HighByte);
  }

Now in MATLAB, I call the serial and set the baud rate, and then reconstruct the value and plot it.

clear;clc
s = serial('/dev/tty.usbmodem1411');
set(s,'DataBits',8);
set(s,'StopBits',1);
set(s,'BaudRate',115200);
set(s,'Parity','none');
% s.InputBufferSize = 1;
fopen(s);

Tmax = 10; % Total time for data collection (s)
figure,
grid on,
xlabel ('Time (s)'), ylabel('Data'),
axis([0 Tmax+1 0 5]),
%%Read and plot the data from Arduino
Ts = 0.01; % Sampling time (s)
i = 0;
data = 0;
t = 0;
tic % Start timer

while toc<=Tmax
    i=i+1;
    inuint10 = fread(s);
    
    data(i)= (inuint10(2)*256+inuint10(1))*5/1023;
    t(i) = toc;
    %Plot live data
        if i > 1
            line([t(i-1) t(i)],[data(i-1) data(i)])
    %         line([data(i-1) data(i)])
            drawnow
        end
end
toc
fclose(s);

However, when I time it with the tic/toc functions for ~10s, my data size is 210 values which means the sampling rate is 21Hz, which is absurdly low, even when I set the baudrate to 115200.

However, if I just run everything natively in MATLAB, like below, I get a similar sampling rate but I have no clue what the baudrate is because it’s not defined anywhere and I’m assuming MATLAB is using the default 9600. Is there a way to set the baudrate in the code below?

clear;clc
a=arduino()

t=1;
x=0;
%%Create a figure window to monitor the live data
Tmax = 10; % Total time for data collection (s)

%%Read and plot the data from Arduino
figure('units','normalized','outerposition',[0 0 1 1])
xlabel ('Time (s)'), ylabel('Data (8-bit)'),
grid on,
tic % Start timer
while(toc<=Tmax)
    voltage=readVoltage(a,'A0');
    x=[x,voltage];
    plot(x);
    grid
    axis auto;
    x(t)=voltage;
    t=t+1;
    drawnow;
end
toc

arduino() is obviously a constructor call. Where the class is defined, and what optional constructors are available is a mystery to us.