There is a subtle problem with this. Keep in mind that Verilog should synthesize down to hardware. The lines in an
always block execute one after the other. It is really difficult for the synthesizer to arrange for the
q=d to occur and then the
q_not=~q to occur next (although for simulation it works well). The synthesizer will have to infer (compile) a latch into your design, and this is bad for speed and other reasons.
Here's another attempt that uses the <= operator:
module d_ff(input clk, input d, output reg q, output reg q_not); always @(posedge clk) begin q<=d; q_not<=~q; // uh oh end endmodule
If you simulate this, you will see it doesn't quite work:
The red part to the left isn't the problem. That simply means the simulator doesn't know the state of the output yet because things haven't settled down. The problem is that
out2 should be inverses of each other and they aren't.
The reason is simple. The <= operator effectively says: "Wait until the end of this
always block (in this case) and then do this assignment at the exact same time as all the other <= assignments in this block."
That means that when
q_not is assigned, it gets the inverse of the current value of
q, not the value that the code just calculated on the previous line.
Try changing to this:
Now the simulation looks right:
Notice the second time the
out1 line goes high. The
D line went high, but the flip flop didn't react until the next rising edge of the clock. Try adjusting the timing so that the
D output goes low early and observe that the flip flop holds the state until the next rising edge.
There are other kinds of flip flops you will commonly see.
T flip flops toggle (from 0 to 1 or 1 to 0) when their
T input is active. A
JK flip flop has a
K input. The
J input causes the output to go to 1, while the
K input makes the output low. If both inputs are active, the output toggles like a
T flip flop.
All of these can be modeled in Verilog, and the synthesis tools will use flip flops on the FPGA (or other device) to efficiently build your circuit. In addition, many flip flops on the device have special features, like a way to asynchronously reset (or set) the flip flop, for example.
Armed with flip flops you can create registers, counters, delay circuits, and state machines among other things.
Next time, I'll wrap up my jag on Verilog with some miscellaneous notes, talk about how people practically use FPGAs in embedded systems, and point you where to go if you want to keep going on your own. Until then, leave a comment. Do you use FPGAs now? If you don't, do you plan to? Do you prefer VHDL over Verilog or vice versa? And why?