Effacer les filtres
Effacer les filtres

Send multiple character string to arduino

16 vues (au cours des 30 derniers jours)
Dennis Weber
Dennis Weber le 20 Déc 2017
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!

Réponses (1)

Tristan Yang
Tristan Yang le 2 Jan 2018
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

Catégories

En savoir plus sur Arduino Hardware dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by