VHDL读取16位二进制采样文件时出现IO内部错误求助
GHDL读取
signed(15 downto 0)类型二进制文件时的IO错误解决 问题背景
编写VHDL仿真模块读取包含16位采样的二进制文件,使用GHDL编译仿真时触发IO错误,但将采样类型替换为integer、bit等非向量类型时无异常。
原始代码
library ieee; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; use std.textio.all; entity read_binary_file is generic ( clk_per : time := 8 ns ); end read_binary_file; architecture behav of read_binary_file is subtype sample is signed(15 downto 0); type sample_file is file of sample; file input_file : sample_file; signal input : signed(15 downto 0); begin read_file : process variable input_data : sample; begin file_open(input_file, ".\HPGex2_Na22\data_chA_r00020.bin", read_mode); while not endfile(input_file) loop read(input_file, input_data); input <= input_data; wait for clk_per; end loop; if endfile(input_file) then file_close(input_file); wait; end if; end process; end behav;
编译仿真命令
ghdl -a "--std=08" ./read_binary_file/read_binary_file.vhdl ghdl -e "--std=08" read_binary_file ghdl -r "--std=08" read_binary_file --stop-time="1000ms" --vcd=wave.vcd --disp-time
错误信息
.\read_binary_file.exe:internal error: file: IO error .\read_binary_file.exe:error: simulation failed
原因分析
VHDL中file of <复合类型>(比如signed属于复合类型)的二进制IO采用工具内部的序列化格式,并非直接对应原始的二进制字节流。而目标文件是普通的16位采样二进制数据,两者格式不兼容,因此触发IO错误。integer、bit等标量类型的文件IO格式与原始二进制数据匹配,所以可以正常读取。
解决方案
改用textio读取原始字节数据,手动拼接为16位后转换为signed类型。注意根据实际文件的字节序(大端/小端)调整拼接顺序:
library ieee; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; use std.textio.all; entity read_binary_file is generic ( clk_per : time := 8 ns ); end read_binary_file; architecture behav of read_binary_file is signal input : signed(15 downto 0); begin read_file : process file input_file : text open read_mode is ".\HPGex2_Na22\data_chA_r00020.bin"; variable line_buf : line; variable byte_high, byte_low : std_logic_vector(7 downto 0); variable raw_data : std_logic_vector(15 downto 0); variable open_status : file_open_status; begin -- 检查文件是否成功打开 file_open(open_status, input_file, ".\HPGex2_Na22\data_chA_r00020.bin", read_mode); if open_status /= open_ok then report "Failed to open target binary file" severity failure; end if; while not endfile(input_file) loop -- 读取两个字节(根据文件字节序调整读取顺序) read(line_buf, byte_high); read(line_buf, byte_low); -- 拼接为16位数据,此处假设文件为大端格式;若为小端则改为byte_low & byte_high raw_data := byte_high & byte_low; input <= signed(raw_data); wait for clk_per; end loop; file_close(input_file); wait; end process; end behav;
说明
- 若二进制文件采用小端存储(低字节在前),需将
raw_data := byte_high & byte_low改为raw_data := byte_low & byte_high。 - 新增的文件打开状态检查可以帮助快速定位文件路径错误等问题。
内容的提问来源于stack exchange,提问作者Matei-Răzvan Obogeanu
相关产品推荐
相关产品推荐

