how to properly use fprintf(obj,value) with serial ports

15 vues (au cours des 30 derniers jours)
ziad alalaily
ziad alalaily le 29 Jan 2015
I use fprinf in my code to send string to the arduino UNO that i am using, problem is i have to add a while loop for it to work for example:
Required = 'Hey' arduino = (.....) %set
while( Required)
fprintf(arduino,Required)
end
fclose(arduino)
this gives an infinite loop to the COM port of the receiving arduino
so basically i removed the while loop
and the code became
Required = 'Hey'
arduino = (.....) %set
fprintf(arduino,Required)
fclose(arduino)
however it doesnt send anything at all if anyone can help in solving this, please give it all your best i searched all the mathworks forum and nothing worked Thanks in advance

Réponses (1)

William Gaillard
William Gaillard le 28 Mar 2019
Arduino will reset when you open the COM port. You probably send the 'Hey' while Arduino is resetting. Give Arduino time to reset. You can add a pause to Matlab or do the following:
Try adding the following in Arduino:
above void setup()
char a = 'b';
in void setup()
Serial.println('a'); // send the char 'a' to the serial port followed by carriage return character (ASCII 13 or \r) and newline character (ASCII 10 or \n)
while (a != 'a') // while a does not equal 'a'
{
a = Serial.read(); // read the first available byte from the serial port and store as a
}
And in Matlab after you open the COM port add the following:
a='b';
while (a ~='a') % wait until you receive an 'a' from Arduino
a=fread(s,1,'uchar');
end
fprintf(s,'%c','a'); % send an 'a' back to Arduino

Catégories

En savoir plus sur MATLAB Support Package for Arduino Hardware dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by