EE402/EE415 Digital System & HDLs Tutorial
__________________________________________________________________________________________________
Lesson 7 (solution)
Flip-flops, Registers, Counters
1(a)
module tflipflop (T, Clock, Reset, Q);
input T, Clock, Reset;
output reg Q;
always @(negedge Reset, posedge Clock) // asynchronous reset
begin
if (!Reset)
Q <= 0;
else
if (T)
Q <= ~Q; // if input T=1, toggle the previous Q value
else
Q <= Q; // if input T=0, keep the same previous Q value
end
endmodule
2(a)
module JKflipflop (J, K, Clock, Q, Qbar);
input J, K, Clock;
output reg Q, Qbar;
always @(posedge Clock)
begin
if ((J==0) && (K==1))
begin
Q <= 0;
Qbar <= 1;
end
else if ((J==1) && (K==0))
begin
Q <= 1;
Qbar <= 0;
end
else if ((J==0) && (K==0))
begin
Q <= Q;
Qbar <= Qbar;
end
else
begin
Q <= Qbar;
Qbar <= Q;
end
end
endmodule
EE402/EE415 Digital System & HDLs Tutorial
__________________________________________________________________________________________________
3 (a)
module UpDownCounter (R, Reset, Clock, L, E, up_down, Q);
input [3:0]R;
input Reset, Clock, L, E, up_down;
output reg [3:0]Q;
always @(negedge Reset, posedge Clock)
if(!Reset)
Q <= 0;
else if (L)
Q <= R;
else if (E)
Q <= Q + (up_down? 1: -1);
endmodule
4
module RingCounter (Reset, Clock, Q);
input Reset, Clock;
output reg [3:0]Q;
integer k;
always @(posedge Clock)
begin
if (!Reset)
Q <= 4'b001;
else
begin
Q[0] <= Q[3];
for (k = 0; k < 3; k = k+1)
Q[k+1] <= Q[k];
end
end
endmodule
EE402/EE415 Digital System & HDLs Tutorial
__________________________________________________________________________________________________
5(a)
module SRflipflop(S, R, Clock, Q, Qbar);
input S, R, Clock;
output reg Q, Qbar;
always @(posedge Clock)
begin
if ((S == 0) && (R == 1))
begin
Q <= 0;
Qbar <= 1;
end
else if ((S == 1) && (R == 0))
begin
Q <= 1;
Qbar <= 0;
end
else if ((S == 0) && (R == 0))
begin
Q <= Q;
Qbar <= Qbar;
end
else
begin
Q <= 1'bx;
Qbar <= 1'bx;
end
end
endmodule
EE402/EE415 Digital System & HDLs Tutorial
__________________________________________________________________________________________________
6(a) The counting sequence is:
Q2 Q1 Q0
0 0 0
0 0 1
0 1 0
1 1 1
then it repeats.
6(b)
module Tcounting(Reset, Clock, Q);
input Reset, Clock;
output reg [2:0]Q;
always @(negedge Reset, posedge Clock)
begin
if (!Reset)
Q <= 3'b000;
else
begin
Q[0] <= ~Q[0];
if (Q[0])
Q[1] <= ~Q[1];
else
Q[1] <= Q[1];
if (Q[1])
Q[2] <= ~Q[2];
else
Q[2] <= Q[2];
end
end
endmodule
EE402/EE415 Digital System & HDLs Tutorial
__________________________________________________________________________________________________
ModelSim - sample simulation:
1(b)
2(b)
3(b)
5(b)
6(b)