How to sending data from matlab to arduino?

182 ビュー (過去 30 日間)
Rayhan mo
Rayhan mo 2015 年 2 月 15 日
コメント済み: Walter Roberson 2021 年 7 月 16 日
I tried to learned some basic a sending data from matlab to arduino with a LED. i tried to turn on and off the LED if i changed some value in matlab. but the result that the LED is gived was always same. please help me to correct. my MATLAB code is
arduino=serial('COM3','BaudRate',9600); % create serial communication object on port COM3
fopen(arduino); % initiate arduino communication
answer = 0.2
fprintf(arduino,%f%,answer); % send answer to arduino
fclose(arduino); % end communication with arduino
and my arduino code is
int ledPin=13;
int matlabdata;
void setup()
{
pinMode(ledPin,OUTPUT);
Serial.begin(9600);
}
void loop()
{
if(Serial.available()>0) // if there is data to read
{
matlabdata=Serial.read(); // read data
if(matlabdata<0.2)
digitalWrite(ledPin,HIGH); // turn light on
else if(matlabdata>0.2)
digitalWrite(ledPin,LOW); // turn light off
}
}
  1 件のコメント
Yusof Zainol Abidin
Yusof Zainol Abidin 2021 年 1 月 3 日
did you manage to get the answer?? im having the same problem.. please help me..

サインインしてコメントする。

回答 (1 件)

Thang Pham
Thang Pham 2021 年 7 月 16 日
編集済み: Thang Pham 2021 年 7 月 16 日
I think the answer for your problem is: Serial.read() reads a 1-byte char-type data from the serial communication, while your sent data from MATLAB is a float-type data.
To solve this problem:
either change your sent data to char type (use fprintf(arduino, '%s', char(2)))
or change your sent data to string type and change your receive method in Arduino so that your program can read a string "0.2" and then convert it to respective float number. See: https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/tofloat/ for converting string to float and https://www.arduino.cc/reference/en/language/functions/communication/serial/readstring/ for string reading.
Hope it could help you.
  1 件のコメント
Walter Roberson
Walter Roberson 2021 年 7 月 16 日
fprintf(arduino,'%f\n',answer); % send answer to arduino
would send convert the numeric value in answer to character representation and send it, followed by newneline. Serial.ParseFloat() can then read the number; https://www.arduino.cc/reference/en/language/functions/communication/serial/parsefloat/

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMATLAB Support Package for Arduino Hardware についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by