Feb 28, 2012

C/C++ Tricks

These are some tricks I learned and implemented during my time at UTS (especially in Embedded Software and DADS). These should work in both C and C++, although it largely depends on your compiler/IDE implementation...

Structs and Unions

  • Union: Access a memory location with different variables
  • Struct: A data structure that can be accessed with '.' (ie struct.variable)
The union below creates an int that has its MSB and LSB easily accessible i.e. variable.b.lo will access the least significant bits of variable.i because it shares memory space

NOTE: writing to one union variable will change the value of ALL variables in the union!!!

typedef union BYTES
{
    unsigned int i;
    struct
    {
       unsigned char lo;
       unsigned char hi;
    } b;
} bytes;


Enumerated Data Types


Enums basically convert strings into their machine equivalent. In the BOOLEAN example below FALSE will be set to a value of 0 and TRUE to 1. The more values you put their index will increase by 1.

enum BOOLEAN
{
    FALSE,
    TRUE
};


Defines

The following define is an in-line function that will delay our PIC by a specific number of microseconds. It will basically rewrite any instances of a keyword to whatever we want, including functions or constants.
#define Common_DelayUs(x) { unsigned char _dcnt; \
_dcnt = (x)*((20000000)/(12000000)); \
while(--_dcnt != 0) \
continue; }


Resources

A good resource on C++ data structures
http://www.cplusplus.com/doc/tutorial/other_data_types/

A resource I use most frequently is Peter McLeans lab resources for Embedded Systems. This guy knows his stuff.
http://services.eng.uts.edu.au/pmcl/embsw/index.htm

No comments:

Post a Comment

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!