Inicialização de memória com arquivos .MIF e .HEX

De MediaWiki do Campus São José
Ir para navegação Ir para pesquisar

Criando arquivos de inicialização de memória hexadecimal (Intel-Format)

O Editor de memória permite-lhe introduzir, ver e editar o conteúdo da memória de um bloco de memória do dispositivo Altera implementado em um arquivo de inicialização da memória (.mif) ou hexadecimal (.hex) arquivo no formato Intel. No Editor de memória, você pode preencher as células selecionadas com hexadecimal, binário, octal, ou valores decimais; editar células individuais, ou preencher um intervalo de endereços com uma seqüência de repetição de valores a partir de um ponto de partida. incrementando ou decrementando valores. Além disso, tanto no Editor de memória como no Editor de Texto, você pode associar aos bits "x" para indicar "don't care" e "u" para "never match". Quando você tem um número binário, por exemplo: 1x1u 1100, o "x" indica um bit "don't care" no qual tanto o valor "1" como o "0" são permitidos. Um endereço binário com bits do tipo "don't care" ou "never match" não pode totalmente convertido em endereço real. A porção do endereço que não pode ser convertido é preenchido com símbolos "x". No Editor de memória as palavras de dados que contêm bits do tipo "don't care" ou "never match" podem perder alguma precisão dos seus valores.

FONTE: http://quartushelp.altera.com/9.1/mergedProjects/design/med/med_pro_med_files.htm

Criação do arquivo .mif e .hex no Editor de Memória Quartus II

O procedimento para a criação de um arquivo de memória no Quartus II é descrita a seguir:

  • No menu [File], clique em [New].
  • Na caixa de diálogo [New], clique no ícone [+] para expandir o item [Memory Files].
  • Em [Memory Files], selecione o tipo desejado e clique em [OK].
  • Digite o número de palavras e o tamanho da palavra e clique em [OK].
  • O editor de memória apresentará a memória com os endereços todos preenchidos com zero.
  • No menu [File], clique em [Save] e na caixa de diálogo, salve o arquivo com a extensão .mif.

Configurando o editor de Memória. No menu [View] é possivel alterar a forma como os dados da memória são visualizados.

  • Para ver os equivalentes ASCII do conteúdo das memórias, clique em [Show ASCII Equivalents].
  • Para rearranjar a disposição, use [Cell per Row], [Address Radix] e [Memory Radix].
  • Usando o [Show Delimiter Spaces], você inserirá um espaço entre cada 4 (ou 2) digitos quando o radix é binário (ou hexadecimal).
  • Algumas das funções do menu [View] são acessíveis clicando com o botão direito do mouse no editor de memória.
  • Experimente as possíveis variações do menu [View]

Criação do arquivo .mif no Editor de Texto do Quartus II

  • No menu [File], clique em [New].
  • Na caixa de diálogo [New], clique no ícone [+] para expandir o item [Other Files].
  • Em [Other Files], selecione [Text File] e clique em [OK].
  • Digite o texto seguindo as regras de sintaxe descritas abaixo.
  • No menu [File], clique em [Save as...] e na caixa de diálogo, salve o arquivo com a extensão .mif.

Arquivo .m para a criação de um arquivo .mif a partir de um arquivo de audio

Utilize o código abaixo no matlab para gerar o arquivo .mif. % Converta o arquivo DTMF.ogg para DTMF.wav usando o Audacity % Importando os dados do arquivo DTMF.wav, que pode ter sido gerado em qualquer sistema newData1 = importdata('DTMF.wav'); vars = fieldnames(newData1); for i = 1:length(vars)

   assignin('base', vars{i}, newData1.(vars{i}));

end word_len = 8; % numero de bit dos dados na memória address_len = 14; % numero de bits do endereço da memória len = length(data); zeroPad = 2^address_len-len-1; % Completa com zeros antes do inicio do sinal para preencher toda a memória % Definindo o cabeçalho do arquivo .mif fid = fopen('DTMF.mif', 'wt'); fprintf(fid, 'DEPTH = %6d;\n', 2^address_len); fprintf(fid, 'WIDTH = %6d;\n', word_len); fprintf(fid, 'ADDRESS_RADIX = HEX;\n'); fprintf(fid, 'DATA_RADIX = BIN;\n'); fprintf(fid, 'CONTENT\n'); fprintf(fid, 'BEGIN\n'); %Preenche com zeros no inicio fprintf(fid, '[0..%6.0x] : 00000000 ;\n',zeroPad);

% Gerando os pares e endereços e dados for N=1:len

   dec_num = floor(data(N)*2^(word_len-2));
   bin_num = signed2bin(dec_num,word_len);
   fprintf(fid, '%6.0x : %s ;\n', N+zeroPad, bin_num);

end fprintf(fid, 'END;'); fclose(fid); </syntaxhighlight>

O script acima utiliza a função signed2bin que está definida como:

MATLAB fuction signed2bin

function R = signed2bin(D,N) %SIGNED2BIN Convert decimal integer to a binary string. % % SIGNED2BIN(D) returns the binary representation of D as a string. % D must be a non-negative integer smaller than 2^51-1 % or a negative integer smaller than 2^51. % % SIGNED2BIN(D,N) produces a binary representation with at least % N bits. % % Example % signed2bin( 13) returns '01101' % signed2bin(-13) returns '10011' % signed2bin( 13,8) returns '00001101' % signed2bin(-13,8) returns '11110011' % See also DEC2BIN, BIN2DEC, DEC2HEX, DEC2BASE.

% Copyright 2012 IF-SC, Campus São José % Author: Marcos Moecke % $Revision: 1.0 $ $Date: 02/07/2012$

% % Input checking % if nargin<1

   error(nargchk(1,2,nargin,'struct'));

end if nargin == 1

   N = ceil(log2(abs(D))+1);

end if isempty(D)

   s = ;
   return;

end

if ~(isnumeric(D) || islogical(D) || ischar(D))

   error('MATLAB:signed2bin:InvalidDecimalArg','D must be numeric.');

end D = round(D); if (D > 2^(N-1)-1)|(D < -2^(N-1))

   error('MATLAB:signed2bin:N is to small');

end

   if  D >= 0
       rest = D;
       R = '0';
   else % número negativo representar em complemento 2
       rest = D+2^(N-1);
       R = '1';
   end
   for k = (N-2):-1:0
       binary = floor(rest/(2^k));
       rest = rest - binary*(2^k);
       R = strcat(R, num2str(binary));
   end

end </syntaxhighlight>

Use como exemplo este arquivo DTMF. Este arquivo precisa ser convertido para DTMF.wav usando o Audacity.

formato .mif

O arquivo .mif é um arquivo de texto ASCII (com a extensão mif.), que especifica o conteúdo inicial de um bloco de memória (CAM, RAM, ou ROM), isto é, os valores iniciais para cada endereço. Este arquivo é usado durante a compilação do projeto e/ou simulação. Você pode criar um arquivo de inicialização da memória no Editor de memória do Quartus II, no In-System Memory Content Editor, ou com um Editor de Texto.

Um arquivo separado é necessário para cada bloco de memória. Em um arquivo de inicialização de memória, você deve especificar a profundidade de memória e valores de largura. Além disso, você pode especificar radix dos dados como binário (BIN), hexadecimal (HEX), octal (OCT), decimal com sinal (DEC), ou decimal sem sinal (UNS) para visualizar e interpretar os endereços e os dados da memória. Os valores de dados devem coincidir com o radix especificado.

Ao criar um arquivo de inicialização da memória no Editor de Texto Quartus II, você deve começar com as palavras chave DEPTH, WIDTH, ADDRESS_RADIX e DATA_RADIX. Você pode usar Tab "\t" e espaço " " como caracteres separadores, e pode inserir múltiplas linhas de comentários entre os caracteres "%", ou comentários simples com o traço duplo "--". Os endereços e valores dos dados são digitados a seguir aos pares entre as palavras chave CONTENT BEGIN e END, conforme mostrado no exemplo a seguir.

Nota: Em testes realizados usando o Quartus II em conjunto com o Modelsim-Altera, o uso do DATA_RADIX = DEC não funcionou para a representação de valores negativos. A solução encontrada foi converter os valores em representação binária e armazená-los no arquivo .mif com DATA_RADIX = BIN.

% multiple-line comment multiple-line comment %

-- single-line comment

DEPTH = 32; -- The size of data in bits WIDTH = 8; -- The size of memory in words ADDRESS_RADIX = HEX; -- The radix for address values DATA_RADIX = BIN; -- The radix for data values CONTENT -- start of (address : data pairs) BEGIN

00 : 00000000; -- memory address : data 01 : 00000001; 02 : 00000010; 03 : 00000011; 04 : 00000100; 05 : 00000101; 06 : 00000110; 07 : 00000111; 08 : 00001000; 09 : 00001001; 0A : 00001010; 0B : 00001011; 0C : 00001100;

END; </syntaxhighlight>

<html>

<colgroup><col> <col> <col class="whs15"> </colgroup><tbody> </tbody>

Address : Data Pairs Syntax Rules

Definition

Example

A : D

Addr[A] = D

2 : 4
Address: 01234567
Data:    00400000

[A0..A1] : D

Addr[A0] to [A1] contain data D

[0..7] : 6
Address: 01234567
Data:    66666666

[A0..A1] : D0 D1

Addr[A0] = D0,
Addr[A0+1] = D1,
Add [A0+2] = D0,

Addr[A0+3] = D1,

until A0+n = A1

[0..7] : 5 6
Address: 01234567
Data:    56565656

A : D0 D1 D2

Addr[A] = D0,
Addr[A+1] = D1,
Addr[A+2] = D2

2 : 4 5 6
Address: 01234567
Data:    00456000

</html>

FONTE: http://quartushelp.altera.com/9.1/mergedProjects/reference/glossary/def_mif.htm

Hexadecimal (Intel-Format) File (.hex)

An ASCII text file (with the extension .hex). A Hexadecimal (Intel-Format) File can be used in the Quartus II software to store the initial memory values for a memory block, such as CAM, RAM, or ROM, that is implemented in an Altera device, or to build software project executables.

Hexadecimal (Intel-Format) Files are used as input files in the Quartus II software in the following ways:

The Memory Editor can create a Hexadecimal (Intel-Format) File for memory initialization in the Compiler and Simulator. You can also use a Memory Initialization File (.mif) to provide memory initialization data.

The In-System Memory Content Editor can use and create a Hexadecimal (Intel-Format) File to import and export data.

You can store configuration data for one or more Altera devices in an output file called a Hexadecimal (Intel-Format) Output File (.hexout). The Hexadecimal (Intel-Format) Output File format is an ASCII text file with the extension .hexout to avoid overwriting initial memory content files that have the extension .hex.

The data width of a Hexadecimal (Intel-Format) File is always a multiple of 8 bits. When you initialize a memory block that is not the same width as the Hexadecimal (Intel-Format) File, the Quartus II software wraps or pads the file as described below:

<html>

<colgroup><col class="whs15"> <col class="whs15"> </colgroup><tbody> </tbody>

File data width greater than memory width

File data width smaller than memory width

Memory size is a multiple of 8:

  • When the Hexadecimal (Intel-Format) File data width is a multiple of the memory width, the Quartus II software wraps the data to subsequent addresses.
     

  • When the Hexadecimal (Intel-Format) File data width is not a multiple of the memory width, the Quartus II software pads the data to a multiple of the memory width just greater than the Hexadecimal (Intel-Format) File data width.

    For example, with a memory width of 24 (Address: 040000002A124FFF72) and a Hexadecimal (Intel-Format) File data width of 32 (Address: 00000001FF), the Quartus II software pads the 32 bit Hexadecimal (Intel-Format) File data width to 48 bits (the multiple of 24 just greater than 32), and then wraps the 48 bits around the 24 bit memory width, resulting in:

    Address: 00002A
    Address: 124FFF

Memory size is not a multiple of 8:

 

The Quartus II software wraps the data to the memory width equal to the multiple of 8 and just greater than the actual memory width, and then truncates the memory block to the actual size of the memory width, which is not a multiple of 8.

  • RAM / ROM<symbol name="Em Dash">—The Quartus II software pads the memory block with zeroes next to the MSB (most significant bit).
     </symbol>

  • MAX II User Flash Memory (UFM)<symbol name="Em Dash">—The Quartus II software pads the memory block with ones next to the LSB (least significant bit).</symbol>

</html>

If the size of the Hexadecimal (Intel-format) File does not match the size of the memory you are initializing, the Quartus II software performs as described below:

<html>

<colgroup><col class="whs21"> <col class="whs21"> </colgroup><tbody> </tbody>

File data depth greater than memory depth

File data depth smaller than memory depth

Ignores extra data.

  • RAM / ROM<symbol name="Em Dash">—The Quartus II software initializes the addresses with no data to zero.</symbol>

  • MAX II User Flash Memory (UFM)<symbol name="Em Dash">—The Quartus II software initializes the addresses with no data to the hexadecimal value of <F...F>.</symbol>

</html>

Note: File data depth refers to the number of addresses that you are initializing. The Quartus II software fills addresses that you are not initializing with zeros or <F...F>, depending on whether it is UFM or not.

Note: In the Quartus II software, you have the option of reading or writing Hexadecimal (Intel-Format) Files in the byte addressable (Intel hexadecimal format) mode, or the word-addressable mode. You can choose between the two modes by changing the Read or write Hexadecimal Files (.hex) using byte addressing (Intel format) option in the Quartus II software. Setting this option in the More Compilation Process Settings dialog box in Settings dialog box applies only to the current project. Alternatively, you can apply this option to any Quartus II project with settings in the Memory Editor page in the Options dialog box. Turning on this option for the current project overrides the global setting.

The Quartus II software always reads word addressable Hexadecimal (Intel-Format) Files in the word addressable mode even if the Read or write Hexadecimal Files (.hex) using byte addressing (Intel format) option is turned on.

FONTE: http://quartushelp.altera.com/9.1/mergedProjects/reference/glossary/def_hexfile.htm