In this post we will save data coming from a sensor connected to Arduino to a Matlab structure or a txt file.

CSV stands for comma separated values. Something like A,val1,val2,val3,B


  • We’ve seen a basic Matlab-Arduino serial communication here
  • We’ve played around with the gyroscope in this post
  • You can check this article about accelerometers

Arduino Side

Connect your sensor to the microcontroller. We just need to send a CSV friendly serial message to Matlab and the job is done.

Here is the relevant part of the Arduino sketch required for this post. Let’s assume you are getting three values x,y and z from your sensor then just add this function to your sketch.

In your serial routine, add this code to send serial messages on demand. It will send a CSV friendly message every time it receives the ‘M’ character.

Matlab Side

Ok, in this part we will first set up a serial object then fix the sample rate.

Please note that we’ve also initialized three arrays to store the sensors’ data.

Now, ask the Arduino for data and open a try/catch statement to read the port. If the message starts with ‘A’ then extract the values with textscan and add them to the arrays.

Let’s wait one second before recording. Use the following code to save data in a Matlab structure and a CSV txt file.



Connect the Arduino to your computer. Check the serial port name, PORTNAME. Close the serial monitor otherwise the port will be busy. Open a terminal and write what follows.

userk@dopamine:~$  sudo rm /dev/ttyS101
userk@dopamine:~$  sudo ln -s /dev/PORTNAME /dev/ttyS101

Now run the matlab script. You shouldn’t get any errors from the serial object. The program will ask you the desired sample rate. Use values bigger than 50 Hz. When asked press r to record.
The Script will save values received from the serial in CSV format to a txt file called Sample.txt and in a Matlab structure called Samples.mat.

Don’t hesitate to comment this post for help.

Full Code