Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Bitfields vs masks for SFRs
Is there a MISRA preferred route for accessing individual bit(s) in an SFR in an embedded micro? In MISRA C1 Rule 110 stated that "unions shall not be used to access the sub-parts of larger data types" and in the explanatory text said that the preferred method was the use of unsigned integer types and masks. However in C2 the rule has changed to "no unions" and this particular recommendation doesn't seem to have made it into the text anywhere.

Notwithstanding rule 18.4, on a micro I am working with at present the compiler writer provides access in the header file to each SFR through a union which overlays both a bitfield structure for the SFR and an unsigned object covering the whole width of the SFR. So if I want to extract (say) a 12-bit A/D value from an SFR location that contains the result as well as some other info e.g. status bits I can access this either as ADCchan.B.RESULT (where RESULT is a bitfield 12 bits wide) or ADCchan.U & 0x00000fffU.
Embedded systems development for over 850 years
The is currently no MISRA "preferred" route for access to SFRs so the choice is down to the organisation, project or individual.

If you are confident that your compiler vendor has mapped the bitfield structure onto the SFR correctly then you might wish to use this access mechanism, deviating Rule 18.4 for these SFRs. However, you would need to be sure that the size of accesses that the compiler makes are compatible with the processor manufacturer's specification for the SFR. For example, if you have an SFR that occupies 2 bytes and you want to access a single bit field in that SFR then, provided your machine is byte-addressable, the compiler could access just the byte that contains the field, or the whole SFR. Whether this affects the behaviour of your program or not will depend on the SFR in question.

If you are explicit over the size of the SFR access then you have more control over the situation and are less likely to modify the machine state inadvertently.
Posted by and on behalf of the MISRA C Working Group

Forum Jump:

Users browsing this thread: 1 Guest(s)