how to pass data from a code on Arduino IDE to matlab

Hello,
i'm using arduino Nano 33 IoT to get data from a sensor. So i had to write a code on Arduino IDE because there are no libraries in Matlab, wich help for the calculating. That means i can only get the data using the interface I2C on Arduino Nano 33 IoT. When i use I2C directly on Matlab it doesn't work (problem of sensor libraries ). Now after i have the data on Arduino IDE i want to pass it directly to Matlab. In this Case there is two codes, one in C++ (for Arduino to run the sensor and getting the data) and the other code on matlab for image processing. The problem i'm facing is that i can't combine the two codes.
Can someone help me to figure out how i can run the C++ on Arduino and after that send the Data to Matlab ? The data is a Matrix with 768 pixels. Every 2 seconds i get new Matrix from Arduino in a loop.
Thanks in advance

 Réponse acceptée

Walter Roberson
Walter Roberson le 31 Jan 2023

0 votes

Use https://arduinogetstarted.com/reference/serial-println to convert to text to send. Or https://arduinogetstarted.com/reference/serial-write to send as binary (more efficient)
On the MATLAB side, serialport rather than using arduino . To read as text readline and sscanf or str2double . To read as binary read

8 commentaires

Hey Walter,
thanks for your answer. i used the methode you said, but i'm not geeting any data. I see no error at the comand window. Can you please tell what i'm messing.
serialportlist("available")
arduinoObj = serialport("COM5",115200)
configureTerminator(arduinoObj,"CR/LF")
flush(arduinoObj);
arduinoObj.UserData = struct("Data",[],"Count",1)
% Callback Function
function readIRsensor(src, ~)
% Read the ASCII data from the serialport object.
data = readline(src);
% Convert the string data to numeric type and save it in the UserData
% property of the serialport object.
src.UserData.Data(end+1) = str2double(data);
% Update the Count value of the serialport object.
src.UserData.Count = src.UserData.Count + 1;
% % If 1001 data points have been collected from the Arduino, switch off the
% % callbacks and plot the data.
if src.UserData.Count > 1001
configureCallback(src, "off");
plot(src.UserData.Data(2:end));
end
end
I do not see where you are enabling the callback
I did what you suggested and it did work. Thanks. I'm getting now data from Arduino through the Serial communication in port COM5.
I'm asking how can i do the same thing, but this time without USB (only with WIFI). I using for my project Arduino Nano 33 IoT, that means i can connect it to Matlab with WIFI. But unfortunately I have two problems, the first one is when the Arduino ist connected with Matlab, to get the IP-Adress the Arduino must be with the matlab through USB connected.
a = arduino('192.168.2.50','Nano33IoT',9500)
But this command is no more longer useful, when i power the Arduino with external power supply. I don't get the connection and Matlab doesn't recognize Arduino.
The second problem, i can't get any Data from serialport when i use WIFI. It seems there is no communication between Matlab and Arduino (Serial Communication), because i would be no longer comminicat with matlab throuph USB-PORT
This is the code i'm using to get data trouph Serial Communication using USB. (While-loop is only to get Data live)
serialportlist("available");
arduinoObj = serialport("COM5",115200);
configureTerminator(arduinoObj,"CR/LF");
flush(arduinoObj);
arduinoObj.UserData = struct("Data",[],"Count",1);
while true
data = readline(arduinoObj);
data_str = split(data,',');
sizetest = size(data_str);
if sizetest(1)==768
for i=1:768
data_array(i) = str2double(data_str(i));
end
end
I hope that you kann suggest something useful to solve this two problems.
Thanks
You have a few possibilities:
  • the arduino can be configured as a TCP server, and you can use tcpclient from basic MATLAB to connect to it. TCP is a "reliable" protocol: if errors are detected in transmission, the lower layers will automatically cause the data to be re-sent until it gets through (or you time out.) If packets are somehow received out of order, the interface will automatically reorder them. If a packet goes missing, it could potentially be a while before it is properly recovered. Because of this, TCP over unreliable networks such as WiFi is often considered unsuitable for real-time systems.
  • Or, very much the same as above, but use tcpclient from the Instrument Control Toolbox
  • You could flip the direction and have the arduino be the TCP client and MATLAB act as the TCP server. This needs tcpserver from the Instrument Control Toolbox
  • instead of using TCP you could use udpport from the Instrument Control toolbox. UDP is classified as "unreliable". Any step in the path is permitted to drop a UDP packet if needed, and there is nothing in the UDP protocol itself that will try to recover the missing information. If you were constantly transmitting a stream of position updates (for example) and the most important point was that the MATLAB side had access to the latest available position information, rather than that it needed all the position information, then UDP can be good. The arduino would send the latest information, it would either get there are not, and either way the arduino would send newer information as soon as it had it.
  • there is a File Exchange Contribution that can handle TCP and UDP using external software (without requiring the Instrument Control Toolbox)
With respect to address information:
Thank you very much for the useful help. I would like to connect the Arduino as a client and Matlab as a Server. That means i will use TCP/IP Communication. I did start writing a simple code in Matlab to recieve any kind of data.
s=tcpip('192.168.2.50',2390,'NetworkRole','server')
fopen(s);
data=fread(s);
But to the Arduino side, i didn't find any helpful codes to start with. I found a documenation to connect Arduino and Matlab over Ethernet Shield. This is exactly what i need. But I have Nano 33 IoT that means it has already a WiFi Chip. Read Data from Arduino Using TCP/IP Communication - MATLAB & Simulink - MathWorks Deutschland
I think that would be the same to TCP/IP Communication. But the libraries are not for TCP and also the code. I would be very grafetful if you can edite the code on Read Data from Arduino Using TCP/IP Communication - MATLAB & Simulink - MathWorks Deutschland so that i can start working wiht it. I would like to send for the first time only a data line from Arduino to Matlab.
thank you again for your useful help.
There is a second code for UPD Communication i found on Arduino WiFiNINA Library Examples | Arduino Documentation | Arduino Documentation under the title WifiNINA Udp NTP Client. I think with this code i can create a communication between Matlab and Arduino. Th code is for Time use. I think with some modify can the data be send from Arduino to Matlab. But i have realy no experinece in sending data with Wifi
To be more specific i will add the both codes i wrote. I want to test the comminication by sending to matlab a verktor as string.
The think is, i'm getting no data (ReplyBuffer[])
Matlab Code
uByte = udpport("byte");
echoudp("on",2390)
% uByte is a udpport byte object
configureTerminator(uByte,"CR/LF");
writeline(uByte,"hello","192.168.2.50",2390);
data = readline(uByte)
Arduino Code:
#include <WiFi.h>
#include <WiFiUdp.h>
int status = WL_IDLE_STATUS;
char ssid[] = "MagentaWLAN-6XU4"; // your network SSID (name)
char pass[] = "11980331210951165236"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
unsigned int localPort = 55753;
//unsigned int localPort = 2390;
char ReplyBuffer[] = { 2, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
WiFiUDP Udp;
// für Setup sollen alle Prints bleiben für INFOS
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
// einmaliger Gebrauch
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("static IP successful.");
// vielleicht brauchen wir nicht: Zur Sicherheit lassen wir
String fv = WiFi.firmwareVersion();
if (fv != "1.1.0") {
Serial.println("Please upgrade the firmware");
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, keyIndex, pass); // Das habe ich eingefügt
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
Serial.println("\nStarting connection to server...");
// if you get a connection, report back via serial:
Udp.begin(localPort);
}
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
// da werden dann unsere Daten an Matlab geschikt
Udp.write(ReplyBuffer);
Udp.endPacket();
}
The way you build the echo server works for me when I change the IP address to "localhost". That is, that code for echoudp is for testing "loopback" -- testing that when you write data on the MATLAB end that it is properly going out and being received back as input on port 2390.
You would not use echoudp for the case where you expected the arduino to answer.
Note that the 2390 port that you writeline() to must match the local port number on the arduino end. You commented that out; you are assigning 55753 instead.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by