Serial.Write Data to arduino and then read it in matlab

10 views (last 30 days)
I have an IMU set up on an arduino UNO, it uses Serial Write to make a dataframe with the gyro writing the X, Y and Z variables. I then open Matlab and want matlab to be able to read the varibles and I cannot get it to work
Here is the data frame, Someone told me how to write it, btu didn't really provide much info on why each thing is done a particular way. Any further info here would be helpful. (all variables are uint8_t)
Serial.write(3); %random number
Serial.write(9) ; % Number of serial writes
Serial.write(0); %Write a 0 here, packet sequence which is irrelevant
Serial.write(2) % random number
Serial.write(4) ; % random number
Serial.write(T) ; %First Varible I want to measure
Serial.write(X);%First Varible I want to measure
Serial.write(Y);%First Varible I want to measure
Serial.write(Z);%First Varible I want to measure
I don't really know what I am doing with the matlab code
arduinoObj = serialport("COM6",9600)
flush(arduinoObj)
data = read(arduinoObj,4,uint8)
  • the 4 is also a random number, as far as i can tell thats the number of varibles I want to read which is 4

Answers (1)

Vidip
Vidip on 2 Nov 2023
I understand that you have an Arduino UNO connected to IMU that collects data from a gyroscope (presumably measuring X, Y, and Z axes) and the Arduino is sending this data as a data frame over a serial connection to MATLAB to read and interpret these variables.
The Arduino code you provided is writing a simple packet of data to the serial port. The first two bytes are random numbers, which can be used to synchronize the sender and receiver. The third byte is a packet sequence number, which can be used to detect lost or out-of-order packets. The fourth and fifth bytes are random numbers, which can be used to fill up the packet and make it a consistent length. The sixth to ninth bytes are the data values that you want to measure, in this case the X, Y, and Z gyroscope readings. Also, different functions used for this are:
  1. serialport("COM6", 9600): This line creates a serial port object named arduinoObj to establish communication with the Arduino. It specifies the COM port ("COM6") and the baud rate (9600) to match the settings on your Arduino.
  2. flush(arduinoObj): This line flushes any existing data in the input buffer of the serial port. It ensures that you are reading fresh data.
  3. read(arduinoObj, 4, "uint8"): This line reads 4 bytes from the serial port using the read function. It specifies that the data should be interpreted as unsigned 8-bit integers (uint8). This matches the data format you're sending from Arduino.
For further information, refer to the documentation links below:

Categories

Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!