2

I am new to programming in general and I find myself depending too much on conditional statements. I find them similar to my train of thought when coding which makes them easy to implement.

Below I have a small code snippet in Verilog which controls a digital clock display. The entire code is pretty much laid out in this way. The code works and is pretty readable. However, I find it to be inelegant. Is it possible to simplify the code while at the same time improving readability?

    if (cnt >= clkspeed) begin
        cnt = 0;
        out0 <= out0 + 4'h1;

        // LED0 > 9 -> LED1 += 1
        if (out0 == 4'h9) begin
            out0 <= 4'h0;
            out1 <= out1 + 4'h1;

            // LED1 > 5 -> LED2 += 1
            if (out1 == 4'h5) begin
                out1 <= 4'h0;
                out2 <= out2 + 4'h1;

                // LED2 > 9 -> LED3 += 1
                if (out2 == 4'h9) begin
                    out2 <= 4'h0;
                    out3 <= out3 + 4'h1;

                    // LED3 > 5 -> LED3 = 0
                    if (out3 == 4'h5) begin
                        out3 <= 4'h0;
                    end                     
                end
            end
        end
    end
4

1 回答 1

1

您的问题是您执行相同的操作四次,因为您将数据存储在标量变量中。这种情况的解决方案是将数字存储在一个数组中,然后循环遍历它们。这个的伪代码是这样的:

array<int> digits;
int position = digits.length();
while (position >= 0) {
    digits[position] = (digits[position] + 1) % 10;
    if (digits[position]>0) break; // if there is no carry, just break
    position--;
}

此代码假定每个数字最多为 9。因此您仍然必须添加处理 LED1 和 LED3 的逻辑......(通过使用另一个数组,或者如果您有 OOP 创建一个可以存储实际数字的 LED 对象和LED的限制...)

于 2012-11-10T15:12:26.823 回答