verilog 通过DPI-C调用C简单示例, verillator模拟
ledloop.v
module ledloop(input wire clk,output wire[3:0] LED
);reg[31:0] cnt = 32'h00000000;always @(posedge clk)cnt <= cnt + 1;assign LED = 4'b0001 << cnt[21:20];
endmodule
电脑模拟较慢,2M计数位移一次,可以自行通过计数位调整。
转接
led_adaptor.v
module led_adaptor(input wire clk,input wire[3:0] LED
);
import "DPI-C" function void print(int a);
reg[3:0] state ;always @(posedge clk)if (state != LED) beginprint(int'(LED));state <= LED;endendmodule
tb
top.v
module top;
wire[3:0] led;
reg clk = 1'b0;initial beginforever #1 clk = ~clk;
endledloop loop1(.clk(clk),.LED(led));led_adaptor adaptor1(.clk(clk),.LED(led));endmodule
print.c
#define BITWIDTH 4
#include <stdio.h>
#include <unistd.h>
#include "svdpi.h"
extern "C"
void print(int a) {unsigned b = (unsigned)a;printf("\r"); //移至行首printf("\033[K"); //清除光标后字符for (int i = 0; i < BITWIDTH; i++){if (b&1)printf("* ");elseprintf(" ");b = b >> 1;} fflush(stdout);
}
Makefile
.PHONY:cleanVERILATOR = verilatorOUTDIR=out
VERILATOR_FLAGS = -Wall -top top -Mdir $(OUTDIR) -cc -binary -build -j 2default: runrun: print.c top.v ledloop.v led_adaptor.v$(VERILATOR) $(VERILATOR_FLAGS) $^./$(OUTDIR)/Vtopclean:-rm -rf $(OUTDIR)
先安装verilator
直接
make
github上传了下直接
git clone https://github.com/yses/fpgasim