Simple training demonstration to show the use of union and structure

Dependencies:   USBDevice mbed

Fork of OddExample2 by Jon Fuge

Committer:
jf1452
Date:
Tue Nov 26 14:11:37 2013 +0000
Revision:
8:c0d351fc572f
Parent:
7:4753526f342a
Child:
9:0add51bbe65d
Example of using Union

Who changed what in which revision?

UserRevisionLine numberNew contents of line
jf1452 1:d9da28105bef 1 /*******************************************************************************
jf1452 8:c0d351fc572f 2 * This program demonstrates the use of union *
jf1452 8:c0d351fc572f 3 * Word occupies the same memory space as Lo,Hi allowing conversion between *
jf1452 8:c0d351fc572f 4 * 16-bit numbers and two 8-bit numbers *
jf1452 1:d9da28105bef 5 * *
jf1452 1:d9da28105bef 6 * Jon Fuge *
jf1452 2:db81cad8cb64 7 * V1.0 25/11/2013 First issue of code *
jf1452 1:d9da28105bef 8 *******************************************************************************/
dan 0:7dec7e9ac085 9
jf1452 2:db81cad8cb64 10 #include "mbed.h"
jf1452 8:c0d351fc572f 11 #include "USBSerial.h"
jf1452 8:c0d351fc572f 12
jf1452 8:c0d351fc572f 13 union uWord16 // Declare a new union
jf1452 8:c0d351fc572f 14 {
jf1452 8:c0d351fc572f 15 uint16_t Word; // Word occupies two bytes
jf1452 8:c0d351fc572f 16 struct // this structure occupies the same space as Word
jf1452 8:c0d351fc572f 17 {
jf1452 8:c0d351fc572f 18 // ARM is little endian and stores the low byte first, then the high byte
jf1452 8:c0d351fc572f 19 uint8_t Lo, Hi; // Lo and Hi occupy one byte each
jf1452 8:c0d351fc572f 20 };
jf1452 8:c0d351fc572f 21 };
jf1452 3:0f80147842c2 22
jf1452 8:c0d351fc572f 23 USBSerial serial; //Virtual serial port over USB. Use Teraterm as the interface
jf1452 6:5f4be4b8db14 24
dan 0:7dec7e9ac085 25 int main() {
jf1452 8:c0d351fc572f 26 uWord16 Converter; // Declare Converter as a variable of type uWord16
jf1452 8:c0d351fc572f 27
jf1452 8:c0d351fc572f 28 Converter.Word = 0x1234; // load Word with a recognisable number
jf1452 8:c0d351fc572f 29
jf1452 8:c0d351fc572f 30 wait (10); // Wait 10 seconds to connect port
jf1452 5:eb5c6ae5938b 31
jf1452 8:c0d351fc572f 32 serial.printf("uiWord=%X\n\r", Converter.Word);
jf1452 8:c0d351fc572f 33 serial.printf("cHighByte=%X\n\r", Converter.Hi);
jf1452 8:c0d351fc572f 34 serial.printf("cLowByte=%X\n\r", Converter.Lo);
jf1452 6:5f4be4b8db14 35
jf1452 8:c0d351fc572f 36 for(;;) {} // Loop forever
jf1452 3:0f80147842c2 37 }