Serial communication with timer

15 views (last 30 days)
Reto Hofmann
Reto Hofmann on 9 Sep 2013
Hi all
I want to control a external device over a serial connection. I have two 1000-element arrays in matlab with the positions to send. When I just use a for loop to send the data, then the whole array is sent in about 3 seconds. This is too fast, I just want to send one position every 10ms so that the whole process takes 10 seconds. When I add a pause(X) after sending one position, then the whole process takes about 16 seconds, and it doesn't matter if I enter 0.01 or 0.0001 as X. Why is that?
Then I tried to use a timer. But I couldn't figure out how to write the TimerFcn that it works.
Can someone help me? The beginning would be as follows.
PositionX = rand(1,1000);
PositionY = rand(1,1000);
T=timer('Period',0.01,'TasksToExecute', 1000)
T.ExecutionMode='fixedRate';
T.TimerFcn = %%insert function here %%
start(T);
What the function should do is the following:
fprintf(serial_object,PositionX(i));
fprintf(serial_object,PositionY(i));
as i goes from 1 to 1000.
Best regards and thanks for the help,
Reto
  3 Comments
Reto Hofmann
Reto Hofmann on 10 Sep 2013
Edited: Reto Hofmann on 10 Sep 2013
Hey thank you for your comment. I couldn't yet test the part with the timer but I tried to implement the part with the specific format.
In each step I have to send 4 numbers in the range from 0-255, which are 4 byte. When I make it like that,
mynumber=[32, 56, 36, 55]; fprintf(s, '%c', mynumber)
then it works. The problem is, if there is a 0 in the mynumber vector, then it only transmits the numbers up to that 0. How do I send a 0?

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 9 Sep 2013
T.TimerFcn = setup_timer();
function timerfcn = setup_timer
i = 0;
timefcn = @send_position;
function send_position(varargin)
i = i + 1;
if i <= length(PositionX)
fprintf(serial_object, '%9.3f %9.3f\n', PositionX(i), PositionY(i))
end
end
end

Products

Community Treasure Hunt

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

Start Hunting!