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

조회 수: 2 (최근 30일)
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

답변 (1개)

Mark Sherstan
Mark Sherstan 2019년 5월 17일
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);
}

카테고리

Help CenterFile Exchange에서 MATLAB Support Package for Arduino Hardware에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by