Hi,
I try to implement a real-time data transfer between Matlab and my Arduino Uno via a Bluetooth antenna (HC-05). The Arduino Uno receives its data from an SPI interface with an analog digital converter (SCLK = 1MHz).
The first 16 bits are only status bits and not relevant, the second 16 bits always indicate the current value as 2's complement. Then I give them to my serial interface and thus to the Bluetooth antenna via the Serial.println() function. As you can see in the code:
int x = 1;
while (x == 1)
{
digitalWriteFast(CS, LOW);
byte stat1 = SPI.transfer(0x00); // get first status bits
byte stat2 = SPI.transfer(0x00); // get second status bits
byte firstval1 = SPI.transfer(0x00); // get first data bits
byte firstval2 = SPI.transfer(0x00); // get second data bits
int val1 = int(firstval1 << 8) + int(firstval2); //transform to one value
Serial.println(val1); //print to serial interface
if (bluetooth.available() > 0) // you can ignore this part, it's just for stopping the conversion
{
data = bluetooth.read();
if (data == 'B')
{
x = 0;
}
}
}
}
Then I read the data with the fscanf() function in Matlab and want to plot it in real time. Before I do this I do a small back calculation, which you can ignore.
The code for it:
Vref = 2.42;
n = 16;
gain = 6;
LSB = (2*Vref)/gain/((2^(16))-1);
%%
figure
h = animatedline('Color','r','LineWidth',1);
ax = gca;
ax.YGrid = 'on';
stop = false;
startTime = datetime('now');
while ~stop
% Read current voltage value
Val1 = fscanf(bt, '%f');
Vout = Val1*LSB;
% Get current time
t = datetime('now') - startTime;
% Add points to animation
addpoints(h,datenum(t), Vout)
% Update axes
ylim([-2 2])
ax.XLim = datenum([t-seconds(15) t]);
datetick('x','keeplimits')
drawnow
end
My problem is that I have the feeling that Matlab reads the data from the beginning and not the current data that is being delivered by Serial.println(). When I change the signal, it takes a very long time for the change to become noticeable in the plot, but very quickly in the plot of the Arduino. So I have an asynchronous data transfer, which is probably much too slow. I can see that plotting the data on the Arduino is much, much faster than on Matlab...
Does anyone have any idea how I can do this faster and synchronize?
I have attached a picture of the SPI for better understanding.