【FPGA】关于两个数相加的"坑"
调试生成校验位的时候,发现在FPGA中计算出的校验byte和使用matlab 计算出的校验byte。对不上,最终检查,发现是FPGA中计算正确,而MATLAB的计算有问题。
1、校验byte的计算方法
一系列数据相加,然后取最终相加结果的低8bit.
c
A=[XX XX XX ... XX];
check_byte=bitand(sum(A(:)),hex2dec('FF'));
2、FPGA计算两个数相加
RTL design
c
//RTL design
module top (
input clk,
input [7:0] a,
input [7:0] b,
output reg [7:0] c='d0
);
always@(posedge clk)
c<=a+b;
endmodule
testbench:
c
//testbench
module tb_top();
reg clk;
reg [7:0] a;
reg [7:0] b;
wire [7:0] c;
top u_top(
.clk(clk),
.a (a),
.b (b),
.c (c)
);
initial begin
clk = 0;
forever #5 clk = ~clk; // 产生周期为10单位时间的时钟信号
end
integer i;
initial begin
a='d252;
b='d0;
for(i=0;i<100;i=i+1)begin
#10
b=b+'d1;
$display("at time %t, data_in = %d", $time, b);
end
end
endmodule
仿真波形

3、MATLAB计算两个数相加
c
a=uint8(240);
b=uint8(0);
for b=0:20
c=a+b;
fprintf("c=%d\n",c);
end
whos c

溢出之后,直接是clip到255;
3、C计算两个数相加
c
#include <stdio.h>
#include <stdint.h>
int main() {
uint8_t a = 240;
uint8_t b = 0;
uint8_t c = 0;
for (b = 0; b < 30; b++)
{
c = a + b;
printf("a[%d]+b[%d]=c=%d\n",a,b, c);
}
return 0;
}

溢出之后为0,然后再在0~255中循环。
4、总结
对比C语言和RTL的处理结果是一致的,但是MATLAB不一致。
这点一定要注意。
MATLAB的溢出机制是不一样的。
所以,如上所述,要计算校验byte,所有数据加起来之后取低8bit.
加起来就不要让数据溢出。
所以先不要用uint8型,强制转成double型,不会溢出的。
c
A=double(A);
check_byte=bitand(sum(A(:)),hex2dec('FF'));
THE END~