I'm using Matlab as a PI (proportional integral) controller. I'm trying to control a "virtual robot" agent via .txt
files. The simulated agent writes errors in a .txt
file. I run it through Matlab and set speed via a second .txt
file, which the agent reads, all in realtime.
The problem is that sometimes Matlab tries to read the error file while the agent is using it (at least that's what I think is happening) and I get this error message:
??? Error using ==>
rfinputs>LocalTimeRespCheck at 421
Final time must be a positive
number.
Error in ==> PI_REG at 42
[v,t]=lsim(pid_d,E,t);
Is there a way to avoid it and have it synchronized perfect every time? Here is the code I'm using (E.txt
is the error file, V.txt
is the speed file):
clc, clear all, close all
Kp=1.3;
Ki=0.32;
Kd=0;
Ts=0.008;
pid_c = tf([Kd Kp Ki],[1 0]);
pid_d = c2d(pid_c,Ts);
fid=fopen('E.txt');
r=textscan(fid,'%f','\r\r');
fclose(fid);
E=r{1};
while length(E)<2464
s = dir('C:\Robot_1\E.txt');
if s.bytes == 0
pause(0.003)
else
fid=fopen('E.txt');
r=textscan(fid,'%f','\r\r');
fclose(fid);
E=r{1}; %E is error in mm
t=[0:Ts:(length(E)-1)*Ts];
[v,t]=lsim(pid_d,E,t);
v;
V=v(length(E)) %V is speed in mm/s
fid=fopen('V.txt','w');
fprintf(fid,'%V6.4f\n',V);
fclose(fid);
end
end