2014年6月11日 星期三

Binary to BCD Converter ( Shift and Add-3 Algorithm) 二進制轉BCD ---適用於DE2-70 的程式








SW[7:0] ===> Binary Data
HEX2,HEX1,HEX0 ==> BCD HUNDREDS,TENS,ONES;

//Binary to BCD Converter
module BIN_2_BCD(  //適用於DE2-70 的程式
 input [17:0]SW,
 input [3:0] KEY,
 input  CLOCK_50,

 output [17:0] LEDR,
 output [7:0] LEDG,
 output [6:0] HEX0,
 output [6:0] HEX1,
 output [6:0] HEX2,
 output [6:0] HEX3,
 output [6:0] HEX4,
 output [6:0] HEX5,
 output [6:0] HEX6,
 output [6:0] HEX7
 );

//assign HEX0=7'b111_1111;  //off 7-segment Display
//assign HEX1=7'b111_1111;
//assign HEX2=7'b111_1111;
assign HEX3=7'b111_1111;
assign HEX4=7'b111_1111;
assign HEX5=7'b111_1111;
assign HEX6=7'b111_1111;
assign HEX7=7'b111_1111;
wire [3:0] ONES,TENS,HUNDREDS;


//binary_to_BCD(A,ONES,TENS,HUNDREDS);
binary_to_BCD u0(SW[7:0],ONES,TENS,HUNDREDS);
hex_7seg u1(ONES,HEX0);
hex_7seg u2(TENS,HEX1);
hex_7seg u3(HUNDREDS,HEX2);

endmodule


module binary_to_BCD(A,ONES,TENS,HUNDREDS);
input [7:0] A;
output [3:0] ONES, TENS;
output [1:0] HUNDREDS;
wire [3:0] c1,c2,c3,c4,c5,c6,c7;
wire [3:0] d1,d2,d3,d4,d5,d6,d7;

assign d1 = {1'b0,A[7:5]};
assign d2 = {c1[2:0],A[4]};
assign d3 = {c2[2:0],A[3]};
assign d4 = {c3[2:0],A[2]};
assign d5 = {c4[2:0],A[1]};
assign d6 = {1'b0,c1[3],c2[3],c3[3]};
assign d7 = {c6[2:0],c4[3]};
add3 m1(d1,c1);
add3 m2(d2,c2);
add3 m3(d3,c3);
add3 m4(d4,c4);
add3 m5(d5,c5);
add3 m6(d6,c6);
add3 m7(d7,c7);
assign ONES = {c5[2:0],A[0]};
assign TENS = {c7[2:0],c5[3]};
assign HUNDREDS = {c6[3],c7[3]};
endmodule


module add3(in,out);
input [3:0] in;
output [3:0] out;
reg [3:0] out;
always @ (in)
 case (in)
 4'b0000: out <= 4'b0000;
 4'b0001: out <= 4'b0001;
 4'b0010: out <= 4'b0010;
 4'b0011: out <= 4'b0011;
 4'b0100: out <= 4'b0100;  
 4'b0101: out <= 4'b1000;  //>4 +3 ,5+3=8
 4'b0110: out <= 4'b1001;  //6+3 =9
 4'b0111: out <= 4'b1010;
 4'b1000: out <= 4'b1011;  //9+3=12
 4'b1001: out <= 4'b1100;
 default: out <= 4'b0000;
 endcase
endmodule


module hex_7seg(hex_digit,seg);
input [3:0] hex_digit;
output [6:0] seg;
reg [6:0] seg;
// seg = {g,f,e,d,c,b,a};
// 0 is on and 1 is off

always @ (hex_digit)
case (hex_digit)
  4'h0: seg = 7'b1000000;
  4'h1: seg = 7'b1111001;  // ---a----
  4'h2: seg = 7'b0100100;  // |   |
  4'h3: seg = 7'b0110000;  // f   b
  4'h4: seg = 7'b0011001;  // |   |
  4'h5: seg = 7'b0010010;  // ---g----
  4'h6: seg = 7'b0000010;  // |   |
  4'h7: seg = 7'b1111000;  // e   c
  4'h8: seg = 7'b0000000;  // |   |
  4'h9: seg = 7'b0011000;  // ---d----
  4'ha: seg = 7'b0001000;
  4'hb: seg = 7'b0000011;
  4'hc: seg = 7'b1000110;
  4'hd: seg = 7'b0100001;
  4'he: seg = 7'b0000110;
  4'hf: seg = 7'b0001110;
endcase
endmodule


沒有留言:

張貼留言