MATLAB Answers

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

2 views (last 30 days)
Mercader Roig Albert
Mercader Roig Albert on 8 May 2019
Answered: Mark Sherstan on 17 May 2019
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;
end

  0 Comments

Sign in to comment.

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.
MATLAB
% Connect to serial port and set properties
s = serial('/dev/cu.usbmodem14101', 'BaudRate', 9600);
s.InputBufferSize = 20;
s.Timeout = 4;
fopen(s);
% Pause to begin a flow of data
pause(3);
fprintf("Connection established\n")
% Start a counter and timer
count = 0;
tic
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');
end
end
% Display data to the user
fprintf("%d\n", analogOut)
end
% Remove serial port connection
fclose(s);
delete(s)
clear s
Arduino
int analogValue;
void setup() {
// Setup serial port
Serial.begin(9600);
}
void loop() {
// Read the analog pin
analogValue = analogRead(A0);
// Write bytes via serial
writeBytes(&analogValue);
}
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);
}

  0 Comments

Sign in to comment.

Sign in to answer this question.

Products


Release

R2018b