Chapter04 - Home
Exercises: 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18 - 19 - 20 - 21

Exercise. This is the solution to exercise 4.1 in the book.

Solution. The Verilog code for the thermostat module and its testbench is listed below:

‘timescale 1ns/1ps

module tb_thermostat;

localparam CLK_HALF = 5; // 100 MHz clk

reg clk;
reg reset;

always begin
clk = 0;
#CLK_HALF;
clk = 1;
#CLK_HALF;
end

initial begin
reset = 1;
repeat (20) @(posedge clk);
reset = 0;
end

reg [6:0] desired_temperature;
reg [6:0] temperature;
wire heat_on;
wire cool_on;

thermostat i_thermostat(
.clk(clk),
.reset(reset),

.temperature(temperature),
.desired_temperature(desired_temperature),

.heat_on(heat_on),
.cool_on(cool_on)
);

initial begin
temperature = 17;
desired_temperature = 27;
wait (reset==0);
repeat (20) @(posedge clk);
desired_temperature = 23;
repeat (20) @(posedge clk);
desired_temperature = 30;
repeat (20) @(posedge clk);
\$stop;
end

always @(posedge clk) begin
if (heat_on)
temperature <= temperature + 1;
if (cool_on)
temperature <= temperature - 1;
end

endmodule

module thermostat(
input clk,
input reset,

input [6:0] temperature, // 0..127 C
input [6:0] desired_temperature,

output reg heat_on,
output reg cool_on
);

always @(posedge clk or posedge reset) begin
if (reset) begin
heat_on <= b0;
cool_on <= b0;
end else begin
heat_on <= b0;
cool_on <= b0;

if (temperature >= desired_temperature + 1)
cool_on <= 1’b1;

if (temperature <= desired_temperature - 1)
heat_on <= 1’b1;
end
end

endmodule

Notice the oscillatory behavior due to the simple feedback function.