Skip to content

Instantly share code, notes, and snippets.

@munro
Created October 21, 2014 02:16
Show Gist options
  • Select an option

  • Save munro/769cb03b6f4e5faaeb5c to your computer and use it in GitHub Desktop.

Select an option

Save munro/769cb03b6f4e5faaeb5c to your computer and use it in GitHub Desktop.
`timescale 1ns / 1ps
module BinToDec(
input mclk,
input [7:0] sw,
output reg [3:0] an,
output reg [6:0] seg,
output reg [7:0] Led
);
wire [3:0] thousands;
wire [3:0] hundreds;
wire [3:0] tens;
wire [3:0] ones;
wire [6:0] seg_a;
wire [6:0] seg_b;
wire [6:0] seg_c;
wire [6:0] seg_d;
reg [9:0] cnt;
binary_to_decimal binary_to_decimal_inst (
sw,
thousands,
hundreds,
tens,
ones);
DecToSeg7 DecToSeg7_insta (ones, seg_a);
DecToSeg7 DecToSeg7_instb (tens, seg_b);
DecToSeg7 DecToSeg7_instc (hundreds, seg_c);
DecToSeg7 DecToSeg7_instd (thousands, seg_d);
integer i;
always @(sw)
begin
Led <= sw;
end
always @(posedge mclk) begin
case (cnt[9:8])
2'b00 : begin an <= 4'b0111; seg <= seg_d; end
2'b01 : begin an <= 4'b1011; seg <= seg_c; end
2'b10 : begin an <= 4'b1101; seg <= seg_b; end
2'b11 : begin an <= 4'b1110; seg <= seg_a; end
default: begin an <= 4'b0111; seg <= seg_a; end
endcase
end
always @(posedge mclk) begin
cnt <= cnt + 1;
end
endmodule
/**
* 0
* ---
* 5 | | 1
* -6-
* 4 | | 2
* ---
* 3
*/
module DecToSeg7(
input wire [3:0] in,
output reg [6:0] out
);
always @(*) case(in)
0: out <= 7'b1000000;
1: out <= 7'b1111001;
2: out <= 7'b0100100;
3: out <= 7'b0110000;
4: out <= 7'b0011001;
5: out <= 7'b0010010;
6: out <= 7'b0000010;
7: out <= 7'b1111000;
8: out <= 7'b0000000;
9: out <= 7'b0011000;
default: out <= 7'b1110111; // error
endcase
endmodule
module binary_to_decimal(
input [7:0] binary,
output reg [3:0] thousands,
output reg [3:0] hundreds,
output reg [3:0] tens,
output reg [3:0] ones
);
integer i;
always @(binary)
begin
// init to 0
thousands = 4'd0;
hundreds = 4'd0;
tens = 4'd0;
ones = 4'd0;
for (i = 7; i >= 0; i = i - 1)
begin
// add 3 to columns >= 5
if (thousands >= 5)
thousands = thousands + 3;
if (hundreds >= 5)
hundreds = hundreds + 3;
if (tens >= 5)
tens = tens + 3;
if (ones >= 5)
ones = ones + 3;
// shift left one
thousands = thousands << 1;
thousands[0] = hundreds[3];
hundreds = hundreds << 1;
hundreds[0] = tens[3];
tens = tens << 1;
tens[0] = ones[3];
ones = ones << 1;
ones[0] = binary[i];
end
end
endmodule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment