在 Verilog 中从 txt 读取和写入数组

Posted

技术标签:

【中文标题】在 Verilog 中从 txt 读取和写入数组【英文标题】:Read and write array from txt in Verilog 【发布时间】:2019-03-07 08:42:12 【问题描述】:

首先我想说的是,我正在通过在 ModelSim 中编译的 Verilog 模型在 ADS(Advanced Design System 2017)中运行仿真。

我的目标是将 .txt 文件中的数据作为输入加载到测试台中,以便运行模拟,然后将此模拟的结果保存在另一个 .txt 文件中。

以下是名为“param.txt”的输入测试 .txt 文件的内容:

1
2
3
4
5
6
7
8
9
10

这是我的 Verilog 测试平台代码:

`include "disciplines.vams"


module resistor(p,n);
electrical p,n;
parameter real R=50.0;
integer file;
integer out;
real pwm_A[0:50];
integer i;
integer j=1;


analog begin

    @(initial_step) // Initial Conditions
    begin


////////////// Read

file=$fopen("param.txt","r");

    if (file)  $display("File was opened successfully : %0d", file);
    else       $display("File was NOT opened successfully : %0d", file);

    for (i=1; i<50; i=i+1) begin  
        pwm_A[i]=$fscanf(file,"%d",j);
        j = j+1;
    end



////////////// Write


out=$fopen("out.txt","w");

    for (i=1; i<=15; i=i+1) begin  

        $fwrite(out,"%d\n",pwm_A[i]);

    end

// Trying to manually display data
$fdisplay(out,123);


$fclose(file);
$fclose(out);


end

// Simulation (doesnt matter)
V(p,n) <+ R * I(p,n);


end
endmodule

模拟日志没有错误或警告:

File was opened successfully : -32

但名为“out.txt”的输出 .txt 文件会生成以下内容:

1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
123 

而不是原始数据。

值得注意的是,'123'手动引入的值没有问题可以写入,但其余数据为'0'或'1'。

谁能发现问题?

提前致谢。

【问题讨论】:

【参考方案1】:

这一行

pwm_A[i]=$fscanf(file,"%d",j);

应该阅读

$fscanf(file,"%d",pwm_A[i]);

$fscanf 系统函数$fdisplay的对立面——函数输出到其参数列表中的变量中。它返回从该行成功读取的项目数。这将(希望)前十行为 1,下一行为 0。所以,你真的应该检查这个数字,如果它不是你所期望的,你应该做点什么,例如:

count = $fscanf(file,"%d",pwm_A[i]);
if (count != 1) 
  // whatever

【讨论】:

非常感谢您的回复。为了测试这段代码,我建立了 15 个值来查看前 10 个为 1,其余为 0,因此我可以看到任何问题。在我的实际设计中,我确实知道 .txt 有多少值,所以这不是问题。假设初始 .txt 有 10 个值 (1-10)。使用您更正的行: for (i=1; i 是的,但这是一个不同的问题。请改为提出一个新问题。 Stack Overflow 的想法不仅是为了帮助最初的提问者,也是为了为未来的 Google 员工提供有用的资源。 当然,这里是:***.com/questions/55042142/… 解决了!再次感谢。

以上是关于在 Verilog 中从 txt 读取和写入数组的主要内容,如果未能解决你的问题,请参考以下文章

在python中从.txt写入.md [重复]

verilog如何给数组赋值

如何在matlab中从nifti图像中逐片写入?

c语言中从文件中按行读取字符串,并进行相应操作。

modelsim和matlab联合使用

如何在 Flutter 中从 firebase 存储读取和写入文本文件?