How to add the reset signal to the sensitivity list in the generated Verilog code when writing a Chisel code, for example the code below for D flip flop:
val x = Reg(init = UInt(0, width = 1))
x := io.D
io.Q := x
will generate a Verilog code as this:
always #(posedge clk) begin
if(reset) begin
x <= 1'h0;
end else begin
x <= io_D;
end
end
as seen the reset is synchronous with the clock, how to code Chisel to generate something like this:
always #(posedge clk or posedge reset) begin
if(reset) begin
x <= 1'h0;
end else begin
x <= io_D;
end
end
where the reset signal is in the sensitivity list and hence asynchronous.
Edit:
As pointed by chrisvp there is another question here and a discussion in chisel-users google group here
Since Chisel 3.2.0, asynchronous reset is supported. The example code can be implemented with the following:
import chisel3._
import chisel3.stage.ChiselStage
class Foo extends RawModule {
val clk = IO(Input(Clock()))
val reset = IO(Input(AsyncReset()))
val io = IO(Input(new Bundle{ val D = UInt(1.W) }))
val out = IO(Output(Bool()))
val x = withClockAndReset(clk, reset) { RegNext(io.D, init=0.U) }
out := x
}
This will then produce the following Verilog logic for register x:
always #(posedge clk or posedge reset) begin
if (reset) begin
x <= 1'h0;
end else begin
x <= io_D;
end
end
To use synchronous reset, change the type of reset from AsyncReset to Bool.
This question is a copy of How to generate an asynchronous reset verilog always blocks with chisel
If really required, you could consider forcing this by considering the rst as a second clock domain as described in the Chisel manual , though I wouldn't recommend to do so.
Related
My math may not be serving me well. I've written a simple recursive function in Verilog to calculate value of log base 2. Log2(1000) should return 9.965 rounded to 10. But, my simulation shows that the function returns 9 as the final value of the recursive function. Any idea what I'm doing wrong?
module test;
real numBits;
function real log2 (input int X);
if (X == 1)
log2 = 0.0;
else begin
log2 = log2(X / 2) + 1.0;
$display($stime,,,"log2 = %0d",log2);
end
endfunction
initial begin
numBits = log2(1000);
$display($stime,,,"numBits = %f",numBits);
end
endmodule
Here's the EDA playground link that shows the code:
https://www.edaplayground.com/x/icx7
A couple of problems with your code. The first is the input to your function needs to be real. Then, it's never good to compare real numbers with equality do to rounding errors. Use X<=1 instead. And finally you should declare recursive functions with an automatic lifetime so that the arguments and the return values do not get overwritten.
function automatic real log2 (input real X);
if (X <= 1)
log2 = 0.0;
else begin
log2 = log2(X / 2) + 1.0;
$display($stime,,,"log2 = %0g",log2);
end
endfunction
The following example in Pascal was given in a book dedicated to the basics of programming. The function ReadLongint is supposed to check whether the input is 0-9 encoded in a char type. The function then returns true or false depending on the check results, as well as a variable for calculations, rendered into an integer via the operator ord().
Being a newbie I've had hard times figuring out how exactly this code works. But even the bigger mystery for me was the necessity of line 9.
'repeat
read(c);
position := position + 1;
until (c <> #32) and (c <> #10);'
I can see that it's a cycle which repeats itself if you input Space or Enter. However, I've checked the program without these lines, substituting it with a simple read(c); , and the program seems to work just fine. Can somebody please explain the role of this line in the example?
Here is the full program:
function ReadLongint(var check: longint): boolean;
var
c: char;
number: longint;
position: integer;
begin
number := 0;
position := 0;
repeat
read(c);
position := position + 1;
until (c <> #32) and (c <> #10);
while (c <> #32) and (c <> #10) do
begin
if (c < '0') or (c > '9') then
begin
writeln('Unexpected ''', c, ''' in position: ', position);
readln;
ReadLongint := false;
exit
end;
number := number * 10 + ord(c) - ord('0');
read(c);
position := position + 1
end;
check := number;
ReadLongint := true
end;
var
x, y: longint;
ok: boolean;
begin
repeat
write('Please type the first number: ');
ok := ReadLongint(x)
until ok = true;
repeat
write('Please type the second number: ');
ok := ReadLongint(y)
until ok = true;
writeln(x, ' times ', y, ' is ', x * y)
end.
Your readLongInt function wants to (partially) mimic the behavior of read/readLn. The behavior of read/readLn differs slightly if the destination variable is an integer (or real) or char value. The ISO Standard 7185 puts it like that:
c) If v is a variable-access possessing the integer-type (or subrange thereof), read(f, v) shall satisfy the following requirements. No component of s shall equal end‑of‑line. The components of r, if any, shall each, and (s ~t ~u).first shall not, equal either the char-type value space or end‑of‑line. […]
Translated to plain English: Leading spaces and newlines are ignored when interpreting a number (i. e. an integer [or real] variable as the destination). This is quite different to read/readLn in conjunction with a char‑variable where ' ' is a legal value, thus it is not “skipped”, you know.
The until (c <> #32) and (c <> #10) loop is trying to imitate the behavior of read(check) although the actually used read(c) merely reads a single char value, one after another.
PS: It always makes me cringe seeing ok = true. I hope you, unlike the author(s) of the textbook, knows that the = true is redundant, merely an identity.
is there solution in Delphi 7 for deynamically creating for-loop cycles?
for example, i want to have a function that generates 1..n for-cycles
for example:
function generate_binary(var number_of_loops:integer):string
var x:word
begin
for x:=1 to number_of_loops do begin
for ... cycle 1
...
...
...
for ... cycle[x]
//code
end; //cycle n
end; //cycle[x]
end;
end;
is there some code for doing that? Or i must manually set every for.. cycles?
This is not direct answer to the topic question, but an example of particular problem solving. There are more effective methods of generation (especially for numbers, not for strings).
Look at this recursive code to generate all strings with predefined length and number of 1's. Note that output size will very large for big Len (number of combination C(N,K) is exponential function)
procedure Generate01Combination(Len, OnesLeft: Integer; s: string);
begin
if Len = 0 then
Memo1.Lines.Add(s)
else begin
if Len > OnesLeft then
Generate01Combination(Len - 1, OnesLeft, s + '0');
if OnesLeft > 0 then
Generate01Combination(Len - 1, OnesLeft - 1, s + '1');
end;
end;
begin
Generate01Combination(5, 2, '');
end;
outputs
00011
00101
00110
01001
01010
01100
10001
10010
10100
11000
Yes, you can kind of "generate loops" - if you enclose them into procedures and pass those procedures as procedure pointers.
But you said for ... cycle[1] - WHAT is that "..." ? Is it for I := 1 to 4 do cycle[1]() ? Or is it for I := cycle[1] to 10 do ; ? It all fits in!
So, well, - and yes, you indeed came with XYZ problem,- I will make an answer that formally fits, I think, but is hardly to help you with your own problem.
type TLoopProc = procedure(const LoopCount: integer);
procedure Loop1(const LoopCount: integer); var i: integer;
begin
for I := 1 to LoopCount do ShowMessage('Loop1 loop is burning!');
end;
procedure Loop2(const LoopCount: integer); var i: integer;
begin
for I := 1 to LoopCount do ShowMessage('Loop2 loop is burning!');
end;
procedure Loop3(const LoopCount: integer); var i: integer;
begin
for I := 1 to LoopCount do ShowMessage('Loop3 loop is burning!');
end;
procedure Loop4(const LoopCount: integer); var i: integer;
begin
for I := 1 to LoopCount do ShowMessage('Loop4 loop is burning!');
end;
var Loops: array[1..4] of TLoopProc;
function generate_binary(const number_of_loops:integer):string
var x,y:word;
begin
Result := '1234';
for x := 1 to number_of_loops do begin
for y := 1 to x do begin
Loops[y](x+y);
end;
end;
end;
BEGIN
Loops[1] := Loop1;
Loops[2] := Loop1;
Loops[3] := Loop1;
Loops[4] := Loop1;
generate_binary(4);
END.
See, formally that does call that ever increasing number of loops.
Those loops which bodies are contained inside their own procedures.
Not that I think you really can apply that to your real task.
But coming back to your real task, it is very very different.
You are given two numbers: N <= L with N being number of "1" to position in the string of Length L.
To me it looks a slightly hidden example of mathematical induction.
Can you position one single "1" in the string? I think you can.
But if you have all the strings with a single "1" - can you position the second "1" to the right of it? And then the 3rd "1" ?
So we would not search for the strings, we would search for ones' positions, sequences like 4-6-8-9-15-16-29-....
var results: iJclStringList;
// here it is just like TStringList, but interface-based, thus needs no `.Free`
type OnePositions = array of integer;
procedure Error;
begin
raise Exception.Create ('We badly screwed'); // or whatever you would make it do
end;
procedure StoreResult( const L: integer; const P1: OnePositions );
var R: string; i,Prev1,Next1: integer;
begin
R := StringOfChar( '0', L );
Prev1 := 0;
// if those Low/High functions are not yet implemented in Delphi7,
// you may run the loop from 0 to Prev(Length(P1))
// to go through all the P1 array elements
for i := Low(P1) to High(P1) do begin
Next1 := P1[i]; // position for next "1"
if Next1 > Length(R) then Error; // outside of string
if Prev1 >= Next1 then Error; // Next "1" is left of previous "1"
R[Next1] := '1';
Prev1 := Next1; // tracing what was the right-most "1" inserted
end;
Results.Add(R);
end;
// L - string length, thus maximum position of "1"
// StartAt - the leftmost (minimal) position of the 1st left "1" to place
// positions < StartAt already were taken
// Rest1s - how many "1" left to be placed (we still have to place)
procedure PositionRest(var Pos: OnePositions; const L, StartAt, Rest1s: integer);
var Max, idx, NextRest1s, i: integer;
begin
idx := Length(Pos) - Rest1s; // number of "1" we are setting now
NextRest1s := Rest1s - 1; // how many "1"s to be set by next calls
Max := L - NextRest1s; // rightmost part of string we have to leave free for next "1" to be placed
for i := StartAt to Max do begin
Pos[idx] := i; // placing our dear "1" here or there
if NextRest1s = 0 // did we maybe just positioned the last "1" ?
then StoreResult( L, Pos )
else PositionRest( Pos, L, i+1, NextRest1s);
end;
end;
procedure GenerateAll( const L,N: integer );
var Ones: OnePositions;
begin
results := JclStringList();
SetLength(Ones,N);
PositionRest(Ones, L, 1, N);
Memo1.Lines.Text := results.Text;
results := nil;
end;
var L: integer = 20; N: integer = 7;
GenerateAll( L,N );
Here are results at Phenom X3 710 2.6GHz CPU from CodeTyphon 5.60 and Delphi XE2: http://imgur.com/a/22B9b - 4 variants.
Example:
Only single core was used, would have to think how to make it parallelized;
Sources and Win32 EXE: http://rghost.ru/7lYwX2B4Y and http://rghost.ru/8RHmCKF4D
Project1 built by CT 5.60 and Project2 built by Delphi XE2
PS. Some general advices.
Whenever you can - use const parameters to functions. Only use var parameters when you know what it is and why you do need that. It is very rarely needed !
Do not use word for looping. Today CPU runs in 32 bits or 64 bits ( for Delphi 7 - only 32 bits ) - so use CPU-native type integer or cardinal, it would make it slightly easier for the hardware and 65535 maximum value for word might be too small sometimes.
Delphi 7 is good but old. Did you purchased it? Why to stick with it today? I think you better either purchase modern Delphi version or take free Lazarus/FPC suite (i'd stick with CodeTyphon distro, without controversial Orca);
PPS. I implemented OTL-based multithreading approach.
On a somewhat good note, I had to implement exactly dynamic number of loops approach.
As was expected MT-decoupling required extensive memory copying and multiple FastMM calls, which is uni-threaded by design, so multithreading was nothing but illusion and results were even worse than I expected -
still even that crippled MT-ing would provide to "show first 100 results while others are not being calculated yet.
I could enhance it here and there, getting rid of intermediate dynamics arrays (using lists and pointers instead) and switching to MT-oriented Heap Memory Manager, but that would clearly overflow the topic-started experience. It would be challenging to make most fast implementation, but since no one cares, then be it. Still this task was interesting synthetic example for pushing some OTL features and bounds.
trying to mimic the verilog behavior regarding the bitwise operations (meaning - an operation that works on all bits of a vector and output 1 bit answer.
example:
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
...
signal vect : std_logic_vector (length -1 downto 0);
signal ans : std_logic;
signal addin : std_logic;
when vect = all '0' i will want ans to be '1' (nor)
when vect = all '1' i will want ans to be '1' (and)
when vect = even num of '1' i will want ans to be '1' (xor)
, etc.
i made the following functions (only one is shown here):
function vand (vect :std_logic_vector) return std_logic is
variable temp : std_logic;
begin
temp := '1';
for I in (vect'length -1) downto 0 loop
temp := temp and vect(I);
end loop;
return temp;
end;
this function should give the "AND" on all bits.
so, here comes my questions:
a. is there an easier way to make such operations?
b. i'm using Vand like this if Vand(vect & addin) = '1' do something... but when vect is '0H' and addin is 'H' the condition is filled and I have no idea why. can someone think why this kind of operation is problematic? the function behaves itself on other cases, but here i tested it for rapid change immunity and got this unwanted behavir.
edit
i do not know the length of the vector 'vect' or the vector 'vect & addin'.
edit 2
solved the second problem by creating a sub function Vand(vect : std_logic_vector; b: std_logic) that uses the original Vand (and found a bug in my Vnor along the way). still hoping for a better solution than these two functions.
There are functions called or_reduce and and_reduce which do what you want. They also call to_X01 on the inputs, which means that H and Ls will be converted to 1 and 0.
They can be found in std_logic_misc for std_logic_vectors and are proposed for the next rev of VHDL for ieee.numeric_std for signed and unsigned vectors.
VHDL-2008 also allows this syntax on std_logic_vectors:
anded <= and v;
ored <= or v;
Having some trouble declaring functions within my script:
%Read the raw audio data
refData = wavread('file1.wav');
userData = wavread('file2.wav');
% I want to continue writing my "main" function here, and call the below functions
%%%%%%%%%%%%%
% Functions %
%%%%%%%%%%%%%
%Vector x
function preEmphasis(x)
alpha = 0.95;
len = length(x);
for i=1:len
x_i = x(i);
x_iMinus1 = x(i-1);
x(i) = x_i - alpha*x_iMinus1;
end
end
%Vector x
function normalization(x)
maxVal = max(abs(x));
x = x / maxVal;
end
%Vector x; numFrames, frameSize: integers; stepSize: percentage (float, 0.2 -> 0.5 for example)
function Ymatrix = createYmatrix(x, numFrames, frameSize, stepSize)
Ymatrix = zeros(numFrames, frameSize);
for i=1:numFrames
for j=1:frameSize
Ymatrix(i,j) = x(stepSize*i + j);
end
end
end
The words "function" and "end" are highlighted in red as "parse errors". How can I fix this? Thanks.
You can't declare functions within your main script. You have to create an external m-file and implement your function inside it, like it says in the official documentation:
Any function that is not anonymous must be defined within a file.
(just to be clear, a script does not accept input arguments or return output arguments).
However, you can have local functions declared inside a function m-file.
Read more about function declarations in the official documentation.
EDIT: You can Refer to #natan's answer if you're looking for a way to avoid function m-files altogether. He implemented your functions as anonymous functions, which can be declared inside the script file. Good luck!
In Addition to what Eitan mentioned, here is how to implement an anonymous functions in your case, note that code vectorization is a must. For example, in your case instead of normalization you can write:
normalization = #(x) x./max(abs(x));
and then use it as if it was a function, y=normalization(x)
For preEmphasis:
preEmphasis= #(x) [x(1) x(2:end)-0.95*x(1:end-1)];
Your current code has a bug for the case i=1 so I interpret that as for=2:len instead;
The solution for Ymatrix is a bit ugly (haven't invested to much time vectorizing it nicely), but it should work:
Ymatrix = #(x, numFrames, frameSize, stepSize) ...
ones(1,numFrames)'*x(1+stepSize:stepSize+frameSize)+...
meshgrid(0:stepSize:stepSize*numFrames-1,ones(1,frameSize))';
Just turn your script into a function; then you can use local and nested functions. Use return values or assignin if you need to get values back in to the base or caller's workspace.