# Simulating a comparator circuit

I'm trying to simulate the circuit posted here, which looks like this: I'm running a transient analysis and have the following settings: I expected to get the output as a square wave, but I'm getting this instead: Does anyone know why I might be getting a zigzag wave rather than a square wave?

Here is the definition of LM339 used: EDIT:

If I use a time step of 0.055ms and the stop time to just 5ms, I get the following: which is still not a square wave.

The amplitude of the input signal is 5V.

• If I'm reading things correctly, your signal is 1 KHz - one cycle per millisecond, but you are only sampling every 10 mS. The vertical lines on the graph are 500 mS apart, so you should get 500 cycles per square - pretty hard to see anything useful. – Peter Bennett Dec 31 '16 at 5:10
• @PeterBennett Granted, I've now set the stop time to 1 and a 1ms step. The output is still not a square wave though. Please see edit. – Kar Dec 31 '16 at 5:17
• You need to sample a few times per cycle - perhaps 0.1 mS would work. Then set the graph to show just a few cycles per square - perhaps 5 mS per square would show something useful. – Peter Bennett Dec 31 '16 at 5:21
• @PeterBennett I've now tried 0.1ms steps over 10ms. Please see update. – Kar Dec 31 '16 at 5:23
• Try using an "op amp with voltage rails". I tried an op amp as a comparator in CircuitLab without rails, and it goes to +/- 60V as in your second diagram. – Ken Shirriff Dec 31 '16 at 6:05

You must be doing something wrong.

Here's the circuit I tried: simulate this circuit – Schematic created using CircuitLab

Since the input signal is a 1kHz sine, you need to put much smaller numbers than the signal frequency as time-step. And also, since this is a comparator, amplitude of the input sine wave is quite important.

Here are the simulation parameters: And here's the plot: • Thanks. @KenShirriff is right that op amp with voltage rails should be used instead. – Kar Dec 31 '16 at 6:18

The problem is that a comparator's output swings between the positive voltage rail and negative voltage rail (more or less). If you use an op amp without voltage rails in CircuitLab, it doesn't know what these values should be, so it defaults to something like +/- 50V. This, of course, messes up your circuit, causing the crazy voltage swings you see in your second image. (The large default makes sense for a typical op amp circuit, which won't get near saturation. But for a comparator circuit, it's bad.)

The solution is to use "op amp with voltage rails", and connect it to a +1V source and ground. Then the comparator outputs 0 or 1V and everything works as expected.