Keil™, An ARM® Company

Discussion Forum

HAL design pattern?

Next Thread | Thread List | Previous Thread Start a Thread | Settings

DetailsMessage
Read-Only
Author
Ko Lo
Posted
8-Jan-2009 18:04 GMT
Toolset
C51
New! HAL design pattern?

Hi,
I'm trying to write a hardware abstraction layer.
I'm trying to figure out how to write predefined values (for all needed register) to the 8-bit registers.
I had some ideas and they were all bad and caused a lot of stupid mistakes that wasted a lot of time...
I dont want any numbers in my program.Everything must be predefined.
Now I thought of something new but I'm not sure it will work or maybe will work but will cause me future problems due to issues I'm unaware of...
The idea is that for each different register I'll define a structure with bitfields.Something like this i.e.:

#define REG ((unsigned char volatile xdata *) 0)[0x400]

typedef struct
{ BYTE field1 :3, BYTE field2 :1, BYTE field3 :4
}sReg;

((sReg) REG).field1 = PREDEFINED_VAL1;
((sReg) REG).field2 = PREDEFINED_VAL2;
((sReg) REG).field3 = PREDEFINED_VAL3;

will this work or will cause me problems by overriding
bits I don't want to be changed?or any other problem you can think of....

Does anyone have any other good idea?

Thanks!!

Read-Only
Author
Andy Neil
Posted
8-Jan-2009 18:10 GMT
Toolset
None
New! RE: HAL design pattern?

Bitfields in general can raise more questions than they solve - especially for single bits;
They are (often) no more effecient that using the normal bitwise operators, and may even be less efficient.

So it's probably easier to just stick with "masks" and the good ol' bitwise operators...

Read-Only
Author
Andy Neil
Posted
8-Jan-2009 18:15 GMT
Toolset
None
New! RE: I dont want any numbers in my program

Be careful with that one - or you could end up with stuff like

#define TEN 10

;-)

See also "Swatting magic numbers" in this thread: http://www.keil.com/forum/docs/thread13701.asp

Read-Only
Author
Ko Lo
Posted
8-Jan-2009 19:03 GMT
Toolset
None
New! RE: I dont want any numbers in my program

what happens if you put an overflow value to a bit field?

As an example:
MSB
BYTE bitfield2 :7
BYTE bitfield1 :1
LSB

bitfield1 = 5;
bitfield2 = 3;

will the byte look like this? (assuming little endian)
0000011 1 (cause 5 = 1 0 1...and the processor will take just the last bit?)

do you where can I read about this issues?most C references don't cover this subject very deeply...

Read-Only
Author
Dan Henry
Posted
8-Jan-2009 19:13 GMT
Toolset
None
New! RE: I dont want any numbers in my program

"do you where can I read about this issues?"

The same place you would read about any of C's integer conversions. Your C reference should cover integer conversions and if not, get a better reference and/or get the language standard and read about the topic there.

Next Thread | Thread List | Previous Thread Start a Thread | Settings