How to collect higher number of samples with MATLAB Support Package for Arduino Hardware

3 views (last 30 days)
Currently, I'm working with Matlab 2018b with the latest Support Package for Arduino Hardware. I'm working with arduino Due Board. I would like to read a sinusoidal signal with a frequency of 50 Hz. I developed a script that allowed me to read a sample every 50 ms. Even though, the signal that has to be read has a period of 20 ms. The optimal speed to read this signal will be 1 sample every ms.
I was trying to increase the BaudRate, but the Support Package for Arduino Hardware only allows you to connect through the Board with this code and the software didn't gave any option. I've tried to create a serial connection, but after that I get troubles using the specific functions for Arduino.
clc, clear all, close all;
% set initial index, voltage and time value
k = 0; %index
v = 0; %voltage
t = 0; %time
tmax = 20;
% create arduino object
a = arduino('COM4', 'Due');
pause (1);
display("starting to read")
tic % Start timer
while toc <= tmax
k = k + 1;
v(k) = readVoltage(a,'A1');
t(k) = toc;

Answers (1)

Mark Sherstan
Mark Sherstan on 17 May 2019
This is the most effcient way I have been able to establish a MATLAB / serial communication and it allows you to focus on putting more weight on the Arduino or MATLAB code depending what you feel more comfertable with.
% Connect to serial port and set properties
s = serial('/dev/cu.usbmodem14101', 'BaudRate', 9600);
s.InputBufferSize = 20;
s.Timeout = 4;
% Pause to begin a flow of data
fprintf("Connection established\n")
% Start a counter and timer
count = 0;
startTimer = toc;
% Get data for 15 seconds
while (toc < startTimer+15)
% Perform the header checks and get cast bytes to ints
if (fread(s, 1) == 159)
if (fread(s, 1) == 110)
x = fread(s, 2);
analogOut = typecast(uint8(x), 'uint16');
% Display data to the user
fprintf("%d\n", analogOut)
% Remove serial port connection
clear s
int analogValue;
void setup() {
// Setup serial port
void loop() {
// Read the analog pin
analogValue = analogRead(A0);
// Write bytes via serial
void writeBytes(int* data1){
// Cast to a byte pointer
byte* byteData1 = (byte*)(data1);
// Byte array with header for transmission
byte buf[4] = {0x9F, 0x6E, byteData1[0], byteData1[1]};
// Write the byte
Serial.write(buf, 4);


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!