# Problems with function Evaluation

I have a simple model of a RL circuit driven by a PWM voltage

Ts = 0.001; duty = 0.2; nPer = 10;
Ubat = 14; Ud = 0.6; tEnd = 0.005;
pars = {R1 -> 11, L1 -> 0.01};
u[t_, d_, T_, Ub_, Ud_] := If[Mod[t, T] < d T, Ub, -Ud]
eqn = {i1'[t] == (u[t] - R1 i1[t])/L1}; ic = {i1 == 0.14};


This works:

solI1[t_] = First[i1[t]/.NDSolve[{eqn/.u[t] -> u[t,duty,Ts, Ubat,Ud]/.pars,ic},i1,{t,tEnd}]];
Plot[{solI1[t],u[t,duty,Ts,Ubat,Ud]1/Ubat},{t,0,tEnd},PlotRange -> All,ExclusionsStyle -> Gray] I wanted to use this for a parameter estimation like in the FindFit Example

model[R1_?NumberQ,L1_?NumberQ]:=NDSolve[Flatten[{eqn/.u[t]->u[t,duty,Ts,Ubat,Ud],ic}] ,i1,{t,tEnd}];
model[11,0.01]


but this doesn't work! The parameters don't get inserted into the model before the NDSolve evaluation. If I replace the equation by hand it works

model[R1_?NumberQ,L1_?NumberQ]:=First[i1[t]/.NDSolve[Flatten[{i1'[t]==(u[t]-R1 i1[t])/L1,ic}/.u[t]->u[t,duty,Ts,Ubat,Ud]] ,i1,{t,tEnd}]];
solI2[t_]=model[11,0.01];
Plot[{solI2[t],u[t,duty,Ts,Ubat,Ud] 1/Ubat},{t,0,tEnd},PlotRange->All,ExclusionsStyle->Gray] You can either :

Pass the parameters R1 and L1 in eqn :

eqnModified[R1_,L1_] = {i1'[t] == (u[t] - R1 i1[t])/L1}; ic = {i1 == 0.14};
model[R1_?NumberQ,L1_?NumberQ]:=NDSolve[
Flatten[{eqnModified[R1,L1]/.u[t]->u[t,duty,Ts,Ubat,Ud],ic}] ,i1,{t,tEnd}];
model[11,0.01]


Or use Block :

model[R1a_?NumberQ,L1a_?NumberQ]:=Block[{R1=R1a,L1=L1a},NDSolve[
Flatten[{eqn/.u[t]->u[t,duty,Ts,Ubat,Ud],ic}] ,i1,{t,tEnd}]]
model[11,0.01] 