Simple training demonstration to show the use of union and structure

Dependencies:   USBDevice mbed

Fork of OddExample1 by Jon Fuge

main.cpp

Committer:
jf1452
Date:
2013-11-26
Revision:
8:c0d351fc572f
Parent:
7:4753526f342a
Child:
9:0add51bbe65d

File content as of revision 8:c0d351fc572f:

/*******************************************************************************
* This program demonstrates the use of union                                   *
* Word occupies the same memory space as Lo,Hi allowing conversion between     *
* 16-bit numbers and two 8-bit numbers                                         *
*                                                                              *
* Jon Fuge                                                                     *
* V1.0 25/11/2013 First issue of code                                          *
*******************************************************************************/

#include "mbed.h"
#include "USBSerial.h"
 
union uWord16 // Declare a new union
{
   uint16_t Word; // Word occupies two bytes
   struct // this structure occupies the same space as Word
   {
      // ARM is little endian and stores the low byte first, then the high byte
      uint8_t Lo, Hi; // Lo and Hi occupy one byte each
   };
};

USBSerial serial; //Virtual serial port over USB. Use Teraterm as the interface

int main() {
   uWord16 Converter; // Declare Converter as a variable of type uWord16
    
   Converter.Word = 0x1234; // load Word with a recognisable number

   wait (10); // Wait 10 seconds to connect port
   
   serial.printf("uiWord=%X\n\r", Converter.Word);
   serial.printf("cHighByte=%X\n\r", Converter.Hi);
   serial.printf("cLowByte=%X\n\r", Converter.Lo);

   for(;;) {} // Loop forever
}