---
# System prepended metadata

title: Homework4

---

# Homework4
> 資工二1 黃柏芸
> 指導老師：林宏益
 
### 實驗目的:
設計一個BCD to 7段顯示器，並具有載入與同步清除功能
![](https://i.imgur.com/YF1sDTq.png)



### 程式碼:

>design部分
```verilog=
module bcd(clk, rst_syn, Q_out);
input clk;
input rst_syn;
output [3:0] Q_out;
reg [3:0] Q_out;

always@ (posedge clk)
begin
  if (!rst_syn)
    Q_out=4'd0;
 else if (Q_out == 9)
    Q_out=4'd0;
 else
    Q_out=Q_out+1;
end
endmodule

// 1-bit Synchronous Load
module dff(Clk, D, Din, Load, Q4);
  input Clk, D, Din, Load;
  output  [3:0] Q4;
  reg [3:0] Q4;
    always@ (posedge Clk)
if (Load) Q4 = Din;
else Q4 = D;

endmodule

module bcd_to_7(bcd, clk, seg);
input [3:0] bcd;
input clk;
output reg [6:0] seg;

always @(posedge clk)
begin
case (bcd)
  4'b0000 : seg = 7'b1111110; 
  4'b0001 : seg = 7'b0110000;
  4'b0010 : seg = 7'b1101101; 
  4'b0011 : seg = 7'b1111001; 
  4'b0100 : seg = 7'b0110011; 
  4'b0101 : seg = 7'b1011011; 
  4'b0110 : seg = 7'b1011111; 
  4'b0111 : seg = 7'b1110000; 
  4'b1000 : seg = 7'b1111111; 
  4'b1001 : seg = 7'b1110011; 
  default : seg = 7'b0000000; 
endcase
end
endmodule
```

>test bench部分
```verilog=
module testbench();
  wire [3:0] DW, QW;
  wire [6:0] seg;
reg clk, reset, load;
  bcd u0(.clk(clk), .rst_syn(reset), .Q_out(DW));
  dff u1(.Clk(clk), .D(DW), .Din(DW), .Load(load), .Q4(QW));
  bcd_to_7 u2(.bcd(QW), .clk(clk), .seg(seg));
 
initial begin
  clk=0;
  reset = 1;
  load = 0;
  #10 reset = 0;
  #5 reset = 1;
  #100 $finish;
end

always begin
  #2 clk = ~clk;
end

always begin
  #5 load = ~load;
end

initial begin
  $dumpfile("bcd_to_7.vcd");
  $dumpfile("bcd.vcd");
  $dumpfile("dff.vcd");
  $dumpvars(0, u2);
end
endmodule
```

### 實驗結果:
![](https://i.imgur.com/yo5nEVN.png)


### 分析:
case (bcd)
  4'b0000 : seg = 7'b1111110; 
  //這一段的意思是:當bcd的值等於4bit且為二進制,數值為0000的值時,將seg設定為7bit且為二進制,數值為1111110的值
... 
  default : seg = 7'b0000000; 
  //這一段的意思是:當上面的判斷式皆不成立時，就將seg設定為7bit且為二進制,數值為0000000的值(類似else)
endcase

### 心得:
這次的作業比之前都難，因此要不斷的請教同學，但是這樣不太好，所以我決定一定要把Verilog學好!

### github連結:
https://gist.github.com/BoyunHuang/a4a3d9d1267bcb37aac3fd8244044c5b
