Last active
February 16, 2022 05:27
-
-
Save DrJosh9000/00554446324d1a00ec4720a213d2eb01 to your computer and use it in GitHub Desktop.
Advent of Code 2018, Day 1, part 1, in Verilog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Advent of Code 2018, Day 1, part 1 | |
// Provide the input file contents over UART, then ^D. | |
// Output will be printed in hexadecimal. | |
// Requires simpleuart.v (see PicoSoC). | |
module top | |
( | |
input clk, | |
output tx, | |
input rx | |
); | |
localparam UART_DIVIDER = 104; // 921600 baudrate? | |
wire clk_bufg; | |
BUFG bufg ( | |
.I(clk), | |
.O(clk_bufg) | |
); | |
reg [5:0] reset_cnt = 0; | |
wire resetn = &reset_cnt; | |
always @(posedge clk_bufg) | |
reset_cnt <= reset_cnt + !resetn; | |
wire [31:0] uart_divider; | |
reg [3:0] uart_div_we = 4'b1111; | |
reg uart_we = 0; | |
reg uart_re = 1; | |
reg [31:0] uart_di = 0; | |
wire [31:0] uart_do; | |
wire uart_busy; | |
simpleuart simpleuart ( | |
.clk(clk_bufg), | |
.resetn(resetn), | |
.ser_tx(tx), | |
.ser_rx(rx), | |
.reg_div_we(uart_div_we), | |
.reg_div_di(UART_DIVIDER), | |
.reg_div_do(uart_divider), | |
.reg_dat_we(uart_we), | |
.reg_dat_re(uart_re), | |
.reg_dat_di(uart_di), | |
.reg_dat_do(uart_do), | |
.reg_dat_wait(uart_busy) | |
); | |
reg state = 0; | |
reg [31:0] outnibble; | |
reg [31:0] sum = 0; | |
reg [31:0] tmp = 0; | |
reg neg; | |
always @(posedge clk_bufg) begin | |
if (uart_divider == UART_DIVIDER) begin | |
uart_div_we <= 0; | |
end | |
if (! uart_busy) begin | |
if (uart_we && uart_di == "\r") | |
uart_di <= "\n"; | |
else begin | |
uart_we <= 0; | |
case (state) | |
0: begin // reading numbers | |
if (! &uart_do) begin | |
//uart_we <= 1; | |
//uart_di <= uart_do; | |
if (uart_do == "+") | |
neg <= 0; | |
if (uart_do == "-") | |
neg <= 1; | |
if ("0" <= uart_do && uart_do <= "9") | |
tmp <= (10 * tmp) + (uart_do - "0"); | |
if (uart_do == "\r" || uart_do == "\n") begin | |
sum <= sum + (neg ? -tmp : tmp); | |
tmp <= 0; | |
end | |
if (uart_do == 4) begin | |
outnibble <= 0; | |
state <= 1; | |
end | |
end | |
end | |
1: begin // printing answer | |
uart_we <= 1; | |
if (outnibble == 8) begin | |
uart_di <= "\r"; | |
state <= 0; | |
end else begin | |
uart_di <= ((sum[31:28] < 10) ? "0" : "W") + sum[31:28]; | |
outnibble <= outnibble + 1; | |
sum <= {sum[27:0], 4'b0000}; | |
end | |
end | |
endcase | |
end | |
end | |
end | |
endmodule |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment