Hi all! Could you please help me understand this piece of code here?

%% setup
hold all
a = arduino('COM3', 'Uno');
mpu = i2cdev(a,'0x68'); %mpu adress is normally 0x68
writeRegister(mpu, hex2dec('B6'), hex2dec('00'), 'int16'); %reset
data = zeros(10000,14,'int8'); %prelocating for the speed
j = 1;
a1 = animatedline('Color',[1 0 0]);
a2 = animatedline('Color',[0 1 0]);
a3 = animatedline('Color',[0 0 1]);
legend('Accel_x','Accel_y','Accel_z')
%% loop
while(true)
x=1;
for i=59:72 % 14 Data Registers for Accel,Temp,Gyro
data(j,x) = readRegister(mpu, i, 'int8');
x = x + 1;
end
y = swapbytes(typecast(data(j,:), 'int16')) %if your system is big-endian remove the swapbytes function
addpoints(a1,j,double(y(1)));
addpoints(a2,j,double(y(2)));
addpoints(a3,j,double(y(3)));
j = j+1;
drawnow limitrate
end

 Réponse acceptée

It initializes an i2c register on the arduino. It loops indefinitely. Each cycle it reads 14 bytes of data that are in big-Endian order. It rearranges the data to be 16 bit little-Endian signed 16 bit integers. It takes the first three of those and adds them to the plot and ignores the rest.
After 10000 points it will slow down a lot for memory allocation reasons.
The code could be trimmed a bit, such as not reading the values it is not going to use.

7 commentaires

For the last part of your answer, can you explain more? can you give an example? actually, I am having problem with the code where when I first run the code, the outcome that I get is data in values and graph but when I want to re run the code for the second time and so on, the outcome that I get is zero data values and the graph is in straight line. Is there any problem with the code? Could you help me?
Trimming:
data = zeros(10000,6,'int8'); %prelocating for the speed
for i=59:64 % 6 Data Registers for Accel
It still the same. The data of outcome is zero in 3 matrix vector and the graph is in straight line.
How are you terminating the run when you stop it the first time? Do you do anything particular before you run again, or do you just start the program again?
before I start again, I clear the workspace and command window. then I run the program again
You are control-c or clicking the Pause button in the editor? I am concerned that the arduino connection might still be open.
I am clicking the Pause button in the editor. I clear the command window and workspace the run again.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur MATLAB Support Package for Arduino Hardware dans Centre d'aide et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by