PLC_OPEN MC_MoveAbsolute with same position - codesys

sometimes it may happen that MC_MoveAbsolute is called with the same current position of the axis, in this case the "done" or "busy" states cannot be used to manage the end of the function because the function must not perform any movement.
I'm a newbie to these types of controls, the examples I've studied always use a state machine like this:
1: MC_MoveAbsolute .exec: = true;
if MC_MoveAbsolute .busy then // never goes high if AxisActPos = MC_MoveAbsolute.position;
MC_MoveAbsolute .exec: = false;
nextStep: = 2;
end_if
2:
if MC_MoveAbsolute.done then
// do something
what is the best way to handle these situations?

I normally don't use the busy bit.
1: MC_MoveAbsolute .exec: = true;
nextStep: = 2;
2: if MC_MoveAbsolute.done then
MC_MoveAbsolute .exec: = false;
// do something
end_if
The nature of the case structure is that when the step is incremented, the new code won't be executed until the next program scan. So, presuming that you are executing your MC_MoveAbsolute function block on every scan outside of the case, the done bit will be set appropriately (depending on whether motion was needed or not) before it is checked in step 2 of the case.

Related

Is it possible to use callbacks to access a single trajectory in Julia's DifferentialEquations Ensemble Problems?

I am new to Julia and trying to use the Julia package DifferentialEquations to simultaneously solve for several conditions of the same set of coupled ODEs. My system is a model of an experiment and in one of the conditions, I increase the amount of one of the dependent variables at mid-way through the process.
I would like to be able to adjust the condition of this single trajectory, however so far I am only able to adjust all the trajectories at once. Is it possible to access a single one using callbacks? If not, is there a better way to do this?
Here is a simplified example using the lorentz equations for what I want to be doing:
#Differential Equations setup
function lorentz!(du,u,p,t)
a,r,b=p
du[1]= a*(u[2]-u[1])
du[2]=u[1]*(r-u[3])-u[2]
du[3]=u[1]*u[2]-b*u[3];
end
#function to cycle through inital conditions
function prob_func(prob,i,repeat)
remake(prob; u0 = u0_arr[i]);
end
#inputs
t_span=[(0.0,100.0),(0.0,100.0)];
u01=[0.0;1.0;0.0];
u02=[0.0;1.0;0.0];
u0_arr = [u01,u02];
p=[10.,28.,8/3];
#initialising the Ensemble Problem
prob = ODEProblem(lorentz!,u0_arr[1],t_span[1],p);
CombinedProblem = EnsembleProblem(prob,
prob_func = prob_func, #-> (prob),#repeat is a count for how many times the trajectories had been repeated
safetycopy = true # determines whether a safetly deepcopy is called on the prob before the prob_func (sounds best to leave as true for user-given prob_func)
);
#introducing callback
function condition(u,t,repeat)
return 50 .-t
end
function affect!(repeat)
repeat.u[1]=repeat.u[1] +50
end
callback = DifferentialEquations.ContinuousCallback(condition, affect!)
#solving
sim=solve(CombinedProblem,Rosenbrock23(),EnsembleSerial(),trajectories=2,callback=callback);
# Plotting for ease of understanding example
plot(sim[1].t,sim[1][1,:])
plot!(sim[2].t,sim[2][1,:])
I want to produce something like this:
Example_desired_outcome
But this code produces:
Example_current_outcome
Thank you for your help!
You can make that callback dependent on a parameter and make the parameter different between problems. For example:
function f(du,u,p,t)
if p == 0
du[1] = 2u[1]
else
du[1] = -2u[1]
end
du[2] = -u[2]
end
condition(t,u,integrator) = u[2] - 0.5
affect!(integrator) = integrator.prob.p = 1
For more information, check out the FAQ on this topic: https://diffeq.sciml.ai/stable/basics/faq/#Switching-ODE-functions-in-the-middle-of-integration

Unity - Everything freezes on " yield return new WaitForSeconds(); "?

Ok! all of my code in this scene is in one script and one manager object.
all of it is about 700 lines. so I can't put it here.
I tested different things:
1) switch platform from android to
pc/mac
2) test on a previous version
of unity( previous 2017, and current
on is 2018.1 )
none of them solve the problem.
then I change some part of the code that I suspected to cause the problem. ( none of them solve the solution ).
then I started to put Debug.Log()s everywhere. so I found where it freezes.
Here Is the code:
IEnumerator ShowSigns(int Button1State, int EqualState, int Button2State)
{
Debug.Log("ShowSigns");
if (Button1State == 1)
{
OperationOneCorrectSign.GetComponent<CanvasGroup>().alpha = 1;
}
else if (Button1State == 2)
{
OperationOneIncorrectSign.GetComponent<CanvasGroup>().alpha = 1;
}
if (EqualState == 1)
{
EqualCorrectSign.GetComponent<CanvasGroup>().alpha = 1;
}
else if (EqualState == 2)
{
EqualIncorrectSign.GetComponent<CanvasGroup>().alpha = 1;
}
if (Button2State == 1)
{
OperationTwoCorrectSign.GetComponent<CanvasGroup>().alpha = 1;
}
else if (Button2State == 2)
{
OperationTwoIncorrectSign.GetComponent<CanvasGroup>().alpha = 1;
}
Debug.Log("BeforeWaiting");
yield return new WaitForSeconds(0.3f);
Debug.Log("AfterWaiting");
OperationOneCorrectSign.GetComponent<CanvasGroup>().alpha = 0;
OperationOneIncorrectSign.GetComponent<CanvasGroup>().alpha = 0;
EqualCorrectSign.GetComponent<CanvasGroup>().alpha = 0;
EqualIncorrectSign.GetComponent<CanvasGroup>().alpha = 0;
OperationTwoCorrectSign.GetComponent<CanvasGroup>().alpha = 0;
OperationTwoIncorrectSign.GetComponent<CanvasGroup>().alpha = 0;
state = GameState.CreateNewProblem;
Debug.Log("EndSigns");
}
I found that it freezes on this:
yield return new WaitForSeconds(0.3f);
Very strange!!!
This is a picture of the game.
The game is a simple game that shows 2 math phrase and player should choose the bigger or equal.
The logic is this way:
1) make new phrases and change the game state to "ChooseAnswer"
2) player press one of 3 buttons and the answer checked and score and other things changes and the ShowSigns coroutine will start and ends after 0.3 seconds. and as you see at the end of the coroutine state changes to "CreateNewProblem".
3) in the Update when CreateNewProblem detects, the code call for the NewProblem() function to make new phrases and at the end of that game state changes to "ChooseAnswer".
this logic repeats over and over until time reaches zero.
a "step" variable increase and decrease by 1 by any correct and incorrect answer. and a variable level = steps/10 determines the difficulty of phrases.
the game works correctly on %98 click On buttons. but usually, it freezes somewhere after step 20. In 21, 23, 27, 34 ... very randomly. but always after 20 and some time no freeze until time ends. and always right before yield return. exactly at the same line.
I read many questions and answers but none of them was helpful. I have no while loop, no while(true), as long as I know and check my code no infinite loop, on StopAllCoroutines ... nothing. and I stuck for 2 days.
thanks all of you for helping.
OH,and Here Is the code file
The cause of the freezing is using Random.Range to control a while loop which is in the code linked in your question. One way to get random number without using the while loop is to generate them into List then remove each one you use. This should prevent Random.Range from freezing Unity.

Is there a way to change directory in Modelica/Dymola automatically?

I have the following problem:
I have over 20 different models which I want to simulate one after another but I want to change the simulation directory each time.
Right now I'm manually changing directory after each simulation (from ./ModelOne to ./ModelTwo) and I'd like to know if there's a way to change it automatically when I initialize or translate the new model.
Regards
Nev
the best way is to write a script I think:
pathOfSave = {"E:\\work\\modelica\\SimulationResult\\Model1\\","E:\\work\\modelica\\SimulationResult\\Model2\\"};
nbSim = 2;
pathOfMod = { "MyModel.",
"MyModel.};
modelsToSimulate = { ""Model1" ,
"Model2"};
//If equdistant=true: ensure that the same number of data points is written in all result files
//store variables at events is disabled.
experimentSetupOutput(equdistant=false, events=false);
//Keep in the plot memory the last nbSim results
experimentSetupOutput(equdistant=false, events=false);
for i in 1:nbSim loop
//delete the result file if it already exists
Modelica.Utilities.Files.removeFile(pathOfSave + modelsToSimulate[i]);
//translate models
translateModel(pathOfMod[i]+modelsToSimulate[i]);
// simulate
simulateModel(
pathOfMod[i]+modelsToSimulate[i],
method="dassl",
stopTime=186350,
numberOfIntervals=nbOfPoi,
resultFile=pathOfSave + modelsToSimulate[i]);
end for;
You can also put the command cd("mynewpath") in the initial algorithm section, if you want it tobe attached to the model.
model example
Real variable;
protected
parameter String currDir = Modelica.Utilities.System.getWorkDirectory();
initial algorithm
cd("C:\\Users\\xxx\\Documents\\Dymola\\MyModelFolder");
equation
variable = time;
when terminal() then
cd(currDir);
end when;
end example;
In any case you can find all commands of dymola in the manual one under the section "builtin commands".
I hope this helps,
Marco

MATLAB change repeating timer period

Is it possible to change the Period of a repeating timer (in TimerFcn)?
Intuitively, when programming for Windows, I would handle WM_TIMER messages and use SetTimer to edit the period of a timer, but a similar approach doesn't seem to work in MATLAB, because the timer needs to be restarted in order to change the Period property. This messes up execution, which can be best described as changing the period to near-zero. No errors are produced.
Here's some example code that's used to create a task array: each task item consists of something to do and a delay. The array is basically walked by a timer, which should change its Period based on the current task delay.
function obj = Scheduler(~)
obj.scheduletimer = timer(...
'TimerFcn',#obj.OnTimer,...
'BusyMode','queue',...
'TasksToExecute',length(obj.tasklist),...
'ExecutionMode','fixedRate');
end
function OnTimer(obj,source,event)
obj.Start(); // Executed task, schedule next
end
function Start(obj)
// Stop timer if needed
if(strcmp(obj.scheduletimer.Running,'on'))
stop(obj.scheduletimer);
end;
// Set new period and resume
if(~isempty(obj.tasklist))
obj.scheduletimer.Period = obj.tasklist(1).something;
start(obj.scheduletimer);
end;
end
When I don't mess with the timer in OnTimer, everything obviously works fine, but I'd like to change the Period each iteration.
Edit: I've tried to implement the pingpong solution suggested by Pursuit, but it's still not working. Note that the switching timers idea does work, but periods still don't seem to be applied.
function obj = Scheduler(~)
obj.timer1 = timer(...
'TimerFcn',#obj.OnTimer);
obj.timer2 = timer(...
'TimerFcn',#obj.OnTimer);
end
function OnTimer(obj,source,event)
obj.Start(); // Executed task, schedule next
end
function Start(obj)
if(strcmp(obj.timer1.Running,'on'))
obj.timer2.Period = obj.tasklist{1}{2};
start(obj.timer2);
else
obj.timer1.Period = obj.tasklist{1}{2};
start(obj.timer1);
end;
end
Ugh.
Use two timers, (e.g. timerNamePing and timerNamePong). At the end of the action for each timer setup the next timer to execute once in single shot mode with some delay.
This avoids the need to constantly tear down and create new timers, and avoids the error which occurs when you try and edit a timer which is currently executing.
Here is a working example to demonstrate:
function setupPingPong
timerPing = timer;
timerPong = timer;
timerPing.TimerFcn = #(~,~)pingPongActivity(true, timerPing, timerPong);
timerPing.Name = 'PingTimer';
timerPong.TimerFcn = #(~,~)pingPongActivity(false, timerPing, timerPong);
timerPong.Name = 'PongTimer';
timerPing.StartDelay = 0;
start(timerPing);
function pingPongActivity(isPing, timerPing, timerPong)
if isPing
disp(['PING (' datestr(now,'yyyy-mm-dd HH:MM:SS.FFF') ')'])
else
disp(['PONG (' datestr(now,'yyyy-mm-dd HH:MM:SS.FFF') ')'])
end
delayTime = ceil(rand*10);
display([' delaying ' num2str(delayTime) ' sec.'])
if isPing
nextTimer = timerPong;
else
nextTimer = timerPing;
end
set(nextTimer,'StartDelay', delayTime);
start(nextTimer);
Once this is going, to stop the madness, I use:
t = timerfind; stop(t); delete(t)
I use the 'StopFcn' property in timer object again to restart the counter.
something like this ('TimerScale' changes the next period)
init :
Timer_OBJ = timer( 'ExecutionMode', 'singleShot', ...
'StartDelay', SystemTicksSecs/TimerScale, ...
'TimerFcn', #(src,evt)obj.TimerCallBack,...
'StopFcn', #(src,evt)obj.TimerStopCallBack );
start(Timer_OBJ);
and inside TimerStopCallBack
set(Timer_OBJ, 'StartDelay', SystemTicksSecs/TimerScale);
start(Timer_OBJ);

Which costs more while looping; assignment or an if-statement?

Consider the following 2 scenarios:
boolean b = false;
int i = 0;
while(i++ < 5) {
b = true;
}
OR
boolean b = false;
int i = 0;
while(i++ < 5) {
if(!b) {
b = true;
}
}
Which is more "costly" to do? If the answer depends on used language/compiler, please provide. My main programming language is Java.
Please do not ask questions like why would I want to do either.. They're just barebone examples that point out the relevant: should a variable be set the same value in a loop over and over again or should it be tested on every loop that it holds a value needed to change?
Please do not forget the rules of Optimization Club.
The first rule of Optimization Club is, you do not Optimize.
The second rule of Optimization Club is, you do not Optimize without measuring.
If your app is running faster than the underlying transport protocol, the optimization is over.
One factor at a time.
No marketroids, no marketroid schedules.
Testing will go on as long as it has to.
If this is your first night at Optimization Club, you have to write a test case.
It seems that you have broken rule 2. You have no measurement. If you really want to know, you'll answer the question yourself by setting up a test that runs scenario A against scenario B and finds the answer. There are so many differences between different environments, we can't answer.
Have you tested this? Working on a Linux system, I put your first example in a file called LoopTestNoIf.java and your second in a file called LoopTestWithIf.java, wrapped a main function and class around each of them, compiled, and then ran with this bash script:
#!/bin/bash
function run_test {
iter=0
while [ $iter -lt 100 ]
do
java $1
let iter=iter+1
done
}
time run_test LoopTestNoIf
time run_test LoopTestWithIf
The results were:
real 0m10.358s
user 0m4.349s
sys 0m1.159s
real 0m10.339s
user 0m4.299s
sys 0m1.178s
Showing that having the if makes it slight faster on my system.
Are you trying to find out if doing the assignment each loop is faster in total run time than doing a check each loop and only assigning once on satisfaction of the test condition?
In the above example I would guess that the first is faster. You perform 5 assignments. In the latter you perform 5 test and then an assignment.
But you'll need to up the iteration count and throw in some stopwatch timers to know for sure.
Actually, this is the question I was interested in… (I hoped that I’ll find the answer somewhere to avoid own testing. Well, I didn’t…)
To be sure that your (mine) test is valid, you (I) have to do enough iterations to get enough data. Each iteration must be “long” enough (I mean the time scale) to show the true difference. I’ve found out that even one billion iterations are not enough to fit to time interval that would be long enough… So I wrote this test:
for (int k = 0; k < 1000; ++k)
{
{
long stopwatch = System.nanoTime();
boolean b = false;
int i = 0, j = 0;
while (i++ < 1000000)
while (j++ < 1000000)
{
int a = i * j; // to slow down a bit
b = true;
a /= 2; // to slow down a bit more
}
long time = System.nanoTime() - stopwatch;
System.out.println("\\tasgn\t" + time);
}
{
long stopwatch = System.nanoTime();
boolean b = false;
int i = 0, j = 0;
while (i++ < 1000000)
while (j++ < 1000000)
{
int a = i * j; // the same thing as above
if (!b)
{
b = true;
}
a /= 2;
}
long time = System.nanoTime() - stopwatch;
System.out.println("\\tif\t" + time);
}
}
I ran the test three times storing the data in Excel, then I swapped the first (‘asgn’) and second (‘if’) case and ran it three times again… And the result? Four times “won” the ‘if’ case and two times the ‘asgn’ appeared to be the better case. This shows how sensitive the execution might be. But in general, I hope that this has also proven that the ‘if’ case is better choice.
Thanks, anyway…
Any compiler (except, perhaps, in debug) will optimize both these statements to
bool b = true;
But generally, relative speed of assignment and branch depend on processor architecture, and not on compiler. A modern, super-scalar processor perform horribly on branches. A simple micro-controller uses roughly the same number of cycles per any instruction.
Relative to your barebones example (and perhaps your real application):
boolean b = false;
// .. other stuff, might change b
int i = 0;
// .. other stuff, might change i
b |= i < 5;
while(i++ < 5) {
// .. stuff with i, possibly stuff with b, but no assignment to b
}
problem solved?
But really - it's going to be a question of the cost of your test (generally more than just if (boolean)) and the cost of your assignment (generally more than just primitive = x). If the test/assignment is expensive or your loop is long enough or you have high enough performance demands, you might want to break it into two parts - but all of those criteria require that you test how things perform. Of course, if your requirements are more demanding (say, b can flip back and forth), you might require a more complex solution.