필터 지우기
필터 지우기

Send multiple character string to arduino

조회 수: 16 (최근 30일)
Dennis Weber
Dennis Weber 2017년 12월 20일
답변: Tristan Yang 2018년 1월 2일
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!

답변 (1개)

Tristan Yang
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

카테고리

Help CenterFile Exchange에서 Arduino Hardware에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by