title: Modeling hardware registers using C struct and union
body: <p>I'm working on an embedded CPU, and need to write C tests that verify the entire system. One of the things to check is access to all registers in the system.</p>
  
  <p>I already have the register modeled using a combination of struct (to differentiate the register fields) and union (to be able to access the register as a whole).
  For example:</p>
  
  <pre><code>typedef unsigned long Uint32;
  
  typedef volatile struct
  {
      volatile Uint32 Divider:    4;      //3:0
      volatile Uint32 Unused:     28;     //31:4
  }XClkRstDivBits; 
  
  typedef union
  {
      Uint32 all;
      XClkRstDivBits bit;
  }XClkRstDivRegs;
  </code></pre>
  
  <p>In this way, I can access only the register field, or access the entire register:</p>
  
  <pre><code>#define REG_ADDRESS 0x000A
  volatile XClkRstDivRegs *ClkRstDivReg = (XClkRstDivRegs *) REG_ADDRESS;
  
  ClkRstDivReg-&gt;all = 0xA5A5A5A5; //Access entire register
  ClkRstDivReg-&gt;bit.Divider = 0x5;
  </code></pre>
  
  <p>I have a few registers defined in this way, some have a few fields, all allocated differently.
  Note the 'Unused' part, most registers have a few unused or reserved bits, which are not written to and are read as zero.</p>
  
  <p>I want to write a a macro that can read from a register and check if the data on the register equals to the one I expect. But, I want this function to be able to:</p>
  
  <ol>
  <li>Work on all registers</li>
  <li>Automatically zero or disregard the Unused bits when comparing the result to the expected result.</li>
  </ol>
  
  <p>The macro should look like this:</p>
  
  <pre><code>#define READ_AND_COMPARE_REG(Reg, ExData, Rdata) ...
  </code></pre>
  
  <p>Where Reg is the pointer to the register ; ExData is an unsigned 32 bit data that contains the expected data, but without a mask on the unused bits, Rdata is an unsigned 32 bit variable to store the read from the register.</p>
  
  <p>Thanks in advance to all.</p>