Send multiple character string to arduino
10 次查看(过去 30 天)
显示 更早的评论
Hi all,
I want to establish a communication between Matlab and my Arduino. Therefore, I want to send one string that contains ~500 characters. To verify my code, I want to send a string that contains 5 characters. If the transmitting was succesful, a LED attached to my arduino will turn on. I use this arduino code.
if true
int LEDPin = 2;
int msg_length = 0;
char userInput[500];
int data = 0;
char tmp;
void setup()
{
Serial.begin(9600);
pinMode(LEDPin, OUTPUT);
}
void loop()
{
delay(500);
if ( data == 0 ) {
Serial.println('a');
if (Serial.available()) {
msg_length = Serial.available();
if ( msg_length == 5 ) {
tmp = Serial.read();
if ( tmp == 'S' ) {
userInput[0] = tmp;
for (int i = 1; i <= msg_length; i++) {
tmp = Serial.read();
userInput[i] = char(tmp);
}
data = 1;
digitalWrite(LEDPin, HIGH);
userInput[499] = {'\r'};
}
}
}
}}
end
And this code in Matlab.
if true
function arduinoCom
instrreset;
clear all;
arduino=serial('COM5','BaudRate',9600); % create serial communication object on port COM4
fopen(arduino); % initiate arduino communication
fprintf(arduino, '%c', 'S1234'); % 'S1234' is what i want to transmit
fclose(arduino); % end communication with arduino
end
end
If I use the serial monitor from Arduino IDE and I type in my string 'S1234', it works and the LED turns on. However, when I use the matlab method, it doesn't.
I am not familiar with the communication via serial ports, so pls feel free to critisize me.
Thanks a lot!
0 个评论
回答(1 个)
Tristan Yang
2018-1-2
Hi Dennis,
In order to write to a string to serial port in MATLAB, please use the '%s' as the format instead of '%c': >> fprintf(arduino, '%s', 'S1234');
Please refer to the documentation below for more information on 'fprintf' function for serial communication: https://www.mathworks.com/help/matlab/ref/serial.fprintf.html
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!