Simple training demonstration to show the use of union and structure

Dependencies:   USBDevice mbed

Fork of OddExample1 by Jon Fuge

Revision:
8:c0d351fc572f
Parent:
7:4753526f342a
Child:
9:0add51bbe65d
--- a/main.cpp	Tue Nov 26 11:52:54 2013 +0000
+++ b/main.cpp	Tue Nov 26 14:11:37 2013 +0000
@@ -1,18 +1,37 @@
 /*******************************************************************************
-* This program demonstrates the use of structures                              *
+* 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
+   };
+};
 
-typedef unsigned short myword;
+USBSerial serial; //Virtual serial port over USB. Use Teraterm as the interface
 
 int main() {
-   myword mwAddress;      // Declare variables with the new type
+   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
    
-   mwAddress = 600;
+   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
+   for(;;) {} // Loop forever
 }
\ No newline at end of file