Sending a variable from MATLAB to Arduino
13 ビュー (過去 30 日間)
古いコメントを表示
Lorenzo Lellini
2022 年 12 月 15 日
コメント済み: Lorenzo Lellini
2022 年 12 月 15 日
I have a probelm in sending variables from MATLAB to Arduino using the serial connection. Here it is just a test that I prepared but it does not work.
When I run the MATLAB code I see that something happens on Arduino and it seems that the Arduino IDE load the code on the board again (I load it before running MATLAB), but the variable does not change and nothing happens.
Here is the MATLAB Code:
clear all; clc;
variable = 100;
arduino=serialport('/dev/tty.usbmodem1401',9600); % create serial communication object
fopen(arduino); % initiate arduino communication
fwrite(arduino, '%d', variable) % send answer variable content to arduino
clear arduino; % end communication with arduino
%fclose(arduino);
And here is the Arduino Code:
int variable = 0;
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
if (Serial.available() > 0){
variable = Serial.read();
}
if(variable != 0 ){
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
}
void loop() {
}
Thank you!
0 件のコメント
採用された回答
Bora Eryilmaz
2022 年 12 月 15 日
編集済み: Bora Eryilmaz
2022 年 12 月 15 日
You have to call Serial.read() in loop() and not in setup(), since setup() is called only once when Arduino starts running. Also, the second if-block should probably be nested inside the first if-block.
void loop() {
if (Serial.available() > 0){
variable = Serial.read();
if(variable != 0 ){
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
}
}
5 件のコメント
Bora Eryilmaz
2022 年 12 月 15 日
If you want it to blink continuously once the variable is received, then you would need to take the second if-block out of ther first if-block as in your original code.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で MATLAB Support Package for Arduino Hardware についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!