# Problem with SquareWave in NDSolve

I would like to have a triangulare signal drive a ODE system, using SquareWave[]. Something seems to go wrong though during integration. Uext'[t] and rate SquareWave[rate/(4 umax) t evaluate to different graphs. What is the problem here? Thanks!

    rate = 0.06;
umax = 0.9;
sol2 = Flatten[
Evaluate[{Uext[t], Uext'[t], rate SquareWave[rate/(4 umax) t]} /.
NDSolve[
{
Uext'[t] == rate SquareWave[rate/(4 umax) t],
Uext[0] == -umax
},
{Uext}, {t, 0, 400}]]];
Show[
Plot[Evaluate[{sol2[[2]], sol2[[3]]}], {t, 0, 400}],
AspectRatio -> 1,
PlotRange -> Automatic,
Frame -> True,
ImageSize -> {500, 500}]


Although Mathematica version 9 was supposed to be able to handle discontinuities in differential equations better than earlier versions, it still doesn't do it automatically in this example. So you have to manually insure it doesn't jump over a whole period of the rectangle wave, by doing something like this:

rate = 0.06;
umax = 0.9;
sol2 = Flatten[
Evaluate[{Uext[t], Uext'[t], rate SquareWave[rate/(4 umax) t]} /.
NDSolve[{Uext'[t] == rate SquareWave[rate/(4 umax) t],
Uext[0] == -umax}, Uext, {t, 0, 400},
MaxStepSize -> 2 umax/rate, MaxSteps -> Infinity]]];

Show[Plot[Evaluate[Rest@sol2], {t, 0, 400}], AspectRatio -> 1,
PlotRange -> Automatic, Frame -> True, ImageSize -> {500, 500}]


I only modified the NDSolve command by adding the options MaxStepSize -> 2 umax/rate, MaxSteps -> Infinity. The latter is half a period of the RectangleWave and should be enough to not jump over the discontinuities, independently of what you choose for rate and umax.