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

5 visualizaciones (últimos 30 días)
ziad alalaily
ziad alalaily el 29 de En. de 2015
Respondida: William Gaillard el 28 de Mzo. de 2019
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

Respuestas (1)

William Gaillard
William Gaillard el 28 de Mzo. de 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

Categorías

Más información sobre MATLAB Support Package for Arduino Hardware en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by