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
Your problem here is that you perform the same operation four times, as you store your data in scalar variables. The solution for this case would be to store the numbers in an array, and loop through them. The pseudocode of this is something like:
This code assumes that every digit counts up to 9. So you still have to add the logic for handling LED1 and LED3… (Through using another array, or if you have OOP creating a LED object which can store the actual number and the limit for the led…)