send a value from matlab to arduino

2 Ansichten (letzte 30 Tage)
Zainoor Ahmad
Zainoor Ahmad am 30 Dez. 2019
Beantwortet: Amish am 13 Feb. 2025
How can you send a value from matlab to arduino that i can also see on serial monitor? I have tried all available codes but nothing seems to work for me.
for arduino
int R = 5; //This is the output pin on the Arduino
int O;
void setup()
{
Serial.begin(9600);
pinMode(R, OUTPUT); //Sets that pin as an output
}
void loop()
{
if(Serial.available()>0)
{
O = Serial.read();
Serial.println(O, DEC);
}
}
for matlab
O=1;
s = serial('COM3','BaudRate',9600);
sendData = O;
fopen(s);
s.Terminator = 'CR';
fprintf(s,'%s',sendData);
fscanf(s) ;
fclose(s);

Antworten (1)

Amish
Amish am 13 Feb. 2025
Hi Zainoor,
To send a value from MATLAB to an Arduino and view it on the Serial Monitor, you need to make sure that both the MATLAB code and the Arduino code are correctly configured to communicate with each other. I see that the code for the Arduino seems mostly correct, however, there are a few issues in your MATLAB code that need addressing:
  1. Data Type: Ensure you are sending the data in the correct format that the Arduino can interpret. Since fprintf is used to send strings, you need to convert your numerical data into a string.
  2. Make sure the terminator matches what your Arduino expects.
  3. Ensure you close the serial port after communication to avoid locking issues.
You may try the following modifications for your MATLAB code:
O = 1; % The value you want to send
s = serial('COM3', 'BaudRate', 9600);
fopen(s);
% Send the data as a string
fprintf(s, '%d', O);
response = fscanf(s);
% Display the response
disp(['Arduino Response: ', response]);
% Close the serial port
fclose(s);
delete(s); % Clean up the serial object
For more information on working with Arduino, you can visit the following docmentation:
Hope this helps!

Kategorien

Mehr zu MATLAB Support Package for Arduino Hardware finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by