Sunday, 9 October 2016

Bluetooth Low Energy


Advertising:
By definition the Central and Peripheral are in a connection from the first data exchange.A central device must know that a peripheral device exists to be able to connect with it. A peripheral will therefore advertise its presence using the BLE advertising mode. In this mode, the device uses theGeneric Access Profile (GAP) to send out a bit of information - an advertisement - at a steady rate. This advertisement is what other devices, like your phone, pick up. It tells them about the presence of a BLE device in the neighbourhood, and whether that device is willing to talk to them.

Advertising mode is one-to-many, whereas connected mode is one-to-one


Advertisements are very limited in size. The general GAP broadcast's data breakdown is illustrated in this diagram:


The BLE stack eats part of our package's 47B, until only 26B are available for our data

Every BLE package can contain a maximum of 47 bytes (which isn't much), and we don't get to use all of it:

- The BLE stack require 8 bytes (1 + 4 + 3) for its own purposes.
- The advertising packet data unit (PDU) therefore has at maximum 39 bytes. But the BLE stack once again requires some overhead, taking up 8 bytes (2 + 6).
- The PDU's advertising data field has 31 bytes left, divided into advertising data (AD) structures. Then:

  - The GAP broadcast must contain flags that tell the device about the type of advertisement we're sending. The flag structure uses three bytes in total (one for data length, one for data type and one for the data itself). The reason we need the first two bytes - the data length and type indications - is to help the parser work correctly with our flag information. We have 28 bytes left.
  - Now we're finally sending our own data in its own data structure - but it, too, requires an indication of length and type (two bytes in total), so we have 26 bytes left.

All of which means that we have only 26B to use for the data we want to send over GAP.

For many applications, advertisements may be all that's needed. This may be when:
- A peripheral only wants to periodically broadcast a small amount of information that can fit in an advertisement.
- It's also okay for this data to be available to any central device within range, regardless of authentication.

But sometimes you'll want to provide more information or more complex interactions than one-way data transfers. For that you'll need to set up a "conversation" between your BLE device and a user's phone, tablet or computer. This conversation is based on connected mode, which describes a relationship between only two devices: the peripheral BLE device and the central device.

For now, advertising and connected modes cannot co-exist. This is because a BLE peripheral device can only be connected to one central device (like a mobile phone) at a time. The moment a connection is established, the BLE peripheral will stop advertising. At that point, no other central device will be able to connect to it, since they can't discover that the device is there if it's not advertising. New connections can be established only after the first connection is terminated and the BLE peripheral starts advertising again.The latest Bluetooth standard allows advertisements to continue in parallel with connections, and this will become a part of mbed's BLE_API before the end of 2015.

Connection

When in a connection, the Central will request data from the Peripheral at specifically defined intervals. This interval is called the connection interval. It is decided and applied to the link by the Central, but a Peripheral can send Connection Parameter Update Requests to the Central. The connection interval must be between 7.5 ms and 4 s according to the Bluetooth Core Specification.

If the Peripheral doesn’t respond to packages from the Central within the time-frame called connection supervision timeout, the link is considered lost. It is possible to achieve higher data throughput by transmitting multiple packets in each connection interval. Each packet transferred can be up to 20 bytes.

However, if current consumption is important and a Peripheral has no data to send, it can choose to ignore a certain number of intervals. The number of ignored intervals is called the slave latency. While in a connection, the devices will hop through all the channels in the frequency band, except for the advertising channels, in a way that is completely transparent to the application.
  
  • Generic Attribute profile (GATT)
GATT is the layer where the data values are actually transferred.

Roles
In addition to the roles in GAP, BLE also defines two roles, a GATT Server and a GATT Client, that are completely independent of the GAP roles. The concept is the device containing data is a Server, while the one accessing it is a Client.
For the LED Button example, the Peripheral device (with its LED and button) is in the role of Server and the Central is in the role of Client.

GATT hierarchy
A GATT Server organizes data in what is called an attribute table and it is the attributes that contain the actual data.
Attribute













An attribute has a handle, a UUID, and a value. A handle is the index in the GATT table for the attribute and is unique for each attribute in a device. The UUID contains information on the type of data within the attribute, which is key information for understanding the bytes that are contained in the value of the attribute. The UUID will not be unique within a device and there may be attributes with the same UUID.

Characteristic
A characteristic consists of at least two attributes: a definition of the characteristic and an attribute that holds the value for the characteristic.
For the LED Button example, we use a characteristic for the current button state and one for the current LED state.

Descriptors
Any attribute within a characteristic declaration that is not the characteristic value, is by definition a descriptor. A descriptor is something that provides more information about a characteristic, for instance a human-readable description of the characteristic.
However, there is one special descriptor that is worth mentioning in particular: the Client Characteristic Configuration Descriptor (CCCD). This descriptor is added for any characteristic that supports the Notify or Indicate properties.
Writing a ‘1’ to the CCCD enables Notify, while writing a ‘2’ enables Indicate. Writing a ‘0’ disables both Notify and Indicate.

Service
A service consists of one or more characteristics, and is a logical collection of related characteristics.
For the LED Button example, both characteristics will be grouped into one service.

Profile
A profile can be defined to collect one or more services into a use case description. A profile document includes information on services that are available and how they are used. Therefore, this document will often contain information on what kind of advertising and connection intervals should be used, whether security is required, and similar. It should be noted that a profile does not have an attribute in the attribute table.
For the LED Button example, we use a characteristic for the current button state and one for the current LED state.


  • Standard versus custom services and characteristics
The Bluetooth SIG has defined a number of profiles, services, characteristics, and attributes based on the GATT layer of the stack. However, with Bluetooth low energy all service implementations are part of the application and not the stack, meaning it is possible for an application to support whichever profiles or services it wants to, as long as the stack supports GATT. Because support for profiles and services is in the application, it is possible to create custom services in the application.
For the LED Button example, there is no Bluetooth SIG service that covers this use case, so it will be implemented as a custom service, with two custom characteristics.

UUIDs
All attributes have a UUID. A UUID is a 128 bit number that is globally unique. The Bluetooth Core Specification separates between a base UUID and an alias.

Base UUID
The following Base UUID is used by Bluetooth SIG for all their defined attributes, and with all Bluetooth SIG attributes, the last 16 bits (the alias) is enough to identify them uniquely.
Full UUID — 0x00001234-0000-1000-8000-00805F9B34FB
Corresponding Base UUID — 0x0000xxxx-0000-1000-8000-00805F9B34FB
Do not use the Bluetooth SIG Base UUID for any custom development. Instead, generate your own Base UUID to create new UUIDs.
For the LED Button example, 0x0000xxxx-1212-EFDE-1523-785FEABCD123 will be used as the base.

Alias
The alias is the remaining 16 bits that are not defined by the Base UUID. The Bluetooth Core Specification does not include any rules or recommendations for how to assign aliases, so you can use any scheme you want for this.
For the LED Button example, 0x1523 is used for the service, 0x1524 for the LED characteristic, and 0x1525 for the button state characteristic.

  • On-air operations and properties
All on-air operations happen by using the handle, since this uniquely identifies each attribute.
Use of the characteristic is dependent on its properties. Possible properties are:
• Write
• Write without response
• Read
• Notify
• Indicate
More properties are defined in the Bluetooth specification, but these are the most commonly used.

Write and Write without response
Write and Write without response allow the GATT Client to write a value to a characteristic in a GATT Server. The difference between them is that Write without response happens without any application level acknowledgment, only radio acknowledgments.

Read
The Read property makes it possible for the GATT Client to read the value of a characteristic in a GATT Server.

Notify and Indicate
Notify and Indicate allow a GATT Server to make the GATT Client aware of changes to a characteristic. The difference between Notify and Indicate is that Indicate has application level acknowledgment, while Notify does not.

For the LED Button example, the characteristic to control the LED and the characteristic for the current button state are the two custom characteristics used in the LED Button service.
For the LED characteristic, the Central needs to be able to set its value, and possibly read it back. Since the application level acknowledgments aren’t needed, you can use the Write without response and Read properties. For the button characteristic, the Client needs to be notified when the button changes state, but application level acknowledgment isn’t needed. Only the Notify property is needed for this.

The characteristic to control the LED and the characteristic for the current button state are the two custom characteristics used here in the LED Button service. For the LED characteristic, the Central needs to be able to set its value, and possibly read it back. Since the application level acknowledgments aren’t needed, you can use the Write without response and Read properties. For the button characteristic, the Client needs to be notified when the button changes state, but application level acknowledgment isn’t needed. Only the Notify property is needed for this.

  1. BLE Stack


The BLE stack implements the core BLE functionality as defined in the Bluetooth Core Specification 4.1. The stack is included as a precompiled library and it is embedded inside the BLE Component.
The BLE stack implements all the mandatory and optional features of Low Energy Single Mode compliant to Bluetooth Core Specification 4.1. The BLE Stack implements a layered architecture of the BLE protocol stack as shown in the following figure.


Generic Access Profile (GAP)
The Generic Access Profile defines the generic procedures related to discovery of Bluetooth devices and link management aspects of connecting to Bluetooth devices. In addition, this profile includes common format requirements for parameters accessible on the user interface level.
The Generic Access Profile defines the following roles when operating over the LE physical channel:
  • Broadcaster role: A device operating in the Broadcaster role can send advertising events. It is referred to as a Broadcaster. It has a transmitter and may have a receiver.
  • Observer role: A device operating in the Observer role is a device that receives advertising events. It is referred to as an Observer. It has a receiver and may have a transmitter.
  • Peripheral role: A device that accepts the establishment of an LE physical link using any of the connection establishment procedures is termed to be in a "Peripheral role." A device operating in the Peripheral role will be in the "Slave role" in the Link Layer Connection State. A device operating in the Peripheral role is referred to as a Peripheral. A Peripheral has both a transmitter and a receiver.
  • Central role: A device that supports the Central role initiates the establishment of a physical connection. A device operating in the "Central role" will be in the "Master role" in the Link Layer Connection. A device operating in the

Generic Attribute Profile (GATT)
The Generic Attribute Profile defines a generic service framework using the ATT protocol layer. This framework defines the procedures and formats of services and their Characteristics. It defines the procedures for Service, Characteristic, and Descriptor discovery, reading, writing, notifying, and indicating Characteristics, as well as configuring the broadcast of Characteristics.
GATT Roles
  • GATT Client: This is the device that wants data. It initiates commands and requests towards the GATT Server. It can receive responses, indications, and notifications data sent by the GATT Server.
  • GATT Server: This is the device that has the data and accepts incoming commands and requests from the GATT Client and sends responses, indications, and notifications to a GATT Client.
The BLE Stack supports both roles simultaneously for a custom profile use case.

Attribute Protocol (ATT)
The Attribute Protocol layer defines a Client/Server architecture above the BLE logical transport channel. The attribute protocol allows a device referred to as the GATT Server to expose a set of attributes and their associated values to a peer device referred to as the GATT Client. These attributes exposed by the GATT Server can be discovered, read, and written by a GATT Client, and can be indicated and notified by the GATT Server. All the transactions on attributes are atomic.

Security Manager Protocol (SMP)
Security Manager Protocol defines the procedures and behavior to manage pairing, authentication, and encryption between the devices. These include:
  • Encryption and Authentication
  • Pairing and Bonding
  • Pass Key and Out of band bonding
  • Key Generation for a device identity resolution, data signing and encryption
  • Pairing method selection based on the IO capability of the GAP central and GAP peripheral device

  

Friday, 2 May 2014

Declarations and Types


  1. Storage classes
  2. Type specifiers / Data Types
  3. Type qualifiers
  4. Declarators and variable declarations
  5. Typedef declarations

1.       C Storage Classes

The "storage class" of a variable determines whether the item has a "global" or "local" lifetime. C calls these two lifetimes "static" and "automatic." An item with a global lifetime exists and has a value throughout the execution of the program. All functions have global lifetimes.

Automatic variables, or variables with local lifetimes, are allocated new storage each time execution control passes to the block in which they are defined. When execution returns, the variables no longer have meaningful values.

C provides the following storage-class specifiers:
                                                1.1 auto
                                                1.2 register
                                                1.3 static
                                                1.4 extern
                                               
Items declared with the auto or register specifier have local lifetimes. Items declared with the static or externspecifier have global lifetimes.

                           1.1            Auto
A variable declared inside a function without any storage class specification, is by default an automatic variable. They are created when a function is called and are destroyed automactically when the function exits. Automatic variables can also be called local variables because they are local to function. By default assigned garbage value by compiler:

Void main()
{
      int detail;
      Or
      Auto int detail; //Both are same
}

                           1.2            Register
Register variable informs the compiler to store the variable in register instead of memory. Register variable has faster access than normal variable. Frequently used variables are kept in register. Only few variables can be placed inside register. We can never get address of variables stored in register.

register int number;

                           1.3            Static
A static variable tells the compiler to persist the variable until the end of program. Instead of creating and destroying a variable every time when it comes into and goes out of scope, static is initialized only once and remains into existence till end of program. A static variable can either be internal or external depending upon the place of declaration. Scope of internal static variable remains inside the functional in which it is defined. External static variable remain restricted to scope of file in which they are declared.
They are assigned 0(zero) as default value by the complier.

Example 1:

void test():
main()
{
      test() ;
      test() ;
      test() ;
}
void test()
{
      static int a=0;
      a = a+1;
      printf (“%d\t”,a);
}

Output:
1     2     3



Example 2:

int GLOBAL ;

int function( void )
{
    int LOCAL ;
    static int *lp = &LOCAL;   /* Illegal initialization */
    static int *gp = &GLOBAL;  /* Legal initialization   */
    register int *rp = &LOCAL; /* Legal initialization   */

}

In C, if an object that has static storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a NULL pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these rules.

                           1.4            extern
The extern keyword is used before a variable to inform the compiler that this variable is declared somewhat else. The extern declaration does not allocate storage for variables.


2.       C Type Specifiers / Data Types
Data Type specifies how we enter data into our programs and what type of data we enter.
Primary Data types: These are fundamental data types in C namely integer(int), floating(float) and void.
Derived Data types / Extended Data types: Derived data types are like arrays, structures & Pointers.



Void
The void type specifies that no value is available. It is used in three kinds of situations:
S.N.
Types and Description
1
Function returns as void
There are various functions in C which do not return value or you can say they return void. A function with no return value has the return type as void. For example void exit (int status);
2
Function arguments as void
There are various functions in C which do not accept any parameter. A function with no parameter can accept as a void. For example, int rand(void);
3
Pointers to void 
A pointer of type void * represents the address of an object, but not its type. For example a memory allocation function void *malloc( size_t size ); returns a pointer to void which can be casted to any data type.

Void Pointers: Suppose we have declare integer pointer, character pointer and float pointer then we need to declare 3 pointer variables. Instead of declaring different types of pointer variable it is feasible to declare single pointer variable which can act as integer pointer, character pointer.

void *ptr;
char cnum;
int inum;

ptr = &cnum; //ptr has address of character data
ptr = &inum; //ptr has address of integer data
ptr = &fnum; //ptr has address of float data

Void pointer declaration is shown above. When have declared 3 variables of integer, character & float type. When we assign address of integer to void pointer, pointer will become Integer pointer. When we assign address off Character Data type pointer it will become Character Pointer. Similarly we can assign address of any data type to the void pointer. It is capable of storing address of any data type.

Integer type:
Integers are used to store whole numbers.



Floating type:
Floating types are used to store real numbers.

Character type:
Character types are used to store characters value.



3.       Type Qualifier: The keywords which are used to modify the properties of a variable are called type qualifiers.
Standard C language recognizes the following two qualifiers:
  • const
  • volatile
The const qualifier is used to tell C that the variable value cannot change after initialization.
const float pi=3.14159;
Now pi cannot be changed at a later time within the program.
The volatile qualifier declares a data type that can have its value changed in ways outside the control or detection of the compiler (such as a variable updated by the system clock or by another program). This prevents the compiler from optimizing code referring to the object by storing the object's value in a register and re-reading it from there, rather than from memory, where it may have changed.


4.       Declarators and variable declarations



   4.1            Simple Variables:
The declaration of a simple variable, the simplest form of a direct declarator, specifies the variable's name and type. It also specifies the variable's storage class and data type.
Storage classes or types (or both) are required on variable declarations. Untyped variables (such as var;) generate warnings.
You can use a list of identifiers separated by commas (,) to specify several variables in the same declaration. All variables defined in the declaration have the same base type. For example:
int x, y;        /* Declares two simple variables of type int */
int const z = 1; /* Declares a constant value of type int */

The variables x and y can hold any value in the set defined by the int type for a particular implementation. The simple object z is initialized to the value 1 and is not modifiable.

   4.2            Arrays
An "array declaration" names the array and specifies the type of its elements. It is possible to make arrays whose elements are basic types. Thus we can make an array of 10 integers with the declaration.
int x[10];
The square brackets mean subscripting; parentheses are used only for function references. Array indexes begin at zero, so the elements of x are:
Thus Array are special type of variables which can be used to store multiple values of same data type. Those values are stored and accessed using subscript or index.
Arrays occupy consecutive memory slots in the computer's memory.
x[0], x[1], x[2], ..., x[9]
int array [8] = {2, 4, 6, 8, 10, 12, 14, 16};
Two Dimensional Arrays
C language supports multidimensional arrays. The simplest form of the multidimensional array in the two dimensional array. Two dimensional array is declared as follows,
type array-name[row-size][column-size]
Example:
int a[3][4];




a[0][0]  a[0][1]  a[0][2]  a[0][3]




a[1][0]  a[1][1]  a[1][2]  a[1][3]




a[2][0]  a[2][1]  a[2][2]  a[2][3]

   4.3            Pointers
pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is:
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable.
int    *ip;    /* pointer to an integer */
double *dp;    /* pointer to a double */
float  *fp;    /* pointer to a float */
char   *ch     /* pointer to a character */

   4.4            Enumeration
An enumeration consists of a set of named integer constants. An enumeration type declaration gives the name of the (optional) enumeration tag and defines the set of named integer identifiers (called the "enumeration set," "enumerator constants," "enumerators," or "members"). A variable with enumeration type stores one of the values of the enumeration set defined by that type.
enum identifier { enumerator-list }
Enumerations provide an alternative to the #define preprocessor directive with the advantages that the values can be generated for you and obey normal scoping rules.
The following rules apply to the members of an enumeration set:
  • An enumeration set can contain duplicate constant values. For example, you could associate the value 0 with two different identifiers, perhaps named null and zero, in the same set.
  • The identifiers in the enumeration list must be distinct from other identifiers in the same scope with the same visibility, including ordinary variable names and identifiers in other enumeration lists.
  • Enumeration tags obey the normal scoping rules. They must be distinct from other enumeration, structure, and union tags with the same visibility.
Examples:
enum DAY            /* Defines an enumeration type    */
{
    saturday,       /* Names day and declares a       */
    sunday = 0,     /* variable named workday with    */
    monday,         /* that type                      */
    tuesday,
    wednesday,      /* wednesday is associated with 3 */
    thursday,
    friday
} workday;
The value 0 is associated with saturday by default. The identifier sunday is explicitly set to 0. The remaining identifiers are given the values 1 through 5 by default.


   4.5            Structures
Structure is user defined data type available in C programming, which allows you to combine data items of different kinds.

Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is this:

struct [structure tag]
{
   member definition;
   member definition;
   ...
   member definition;
} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure:

struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
} book; 

Accessing Structure Members
To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure:

#include <stdio.h>
#include <string.h>

struct Books
{
   char title[50];
   char author[50];
   char subject[100];
   int   book_id;
};

int main( )
{
   struct Books Book1;        /* Declare Book1 of type Book */
   struct Books Book2;        /* Declare Book2 of type Book */

   /* book 1 specification */
   strcpy( Book1.title, "C Programming");
   strcpy( Book1.author, "Nuha Ali");
   strcpy( Book1.subject, "C Programming Tutorial");
   Book1.book_id = 6495407;

   /* book 2 specification */
   strcpy( Book2.title, "Telecom Billing");
   strcpy( Book2.author, "Zara Ali");
   strcpy( Book2.subject, "Telecom Billing Tutorial");
   Book2.book_id = 6495700;

   /* print Book1 info */
   printf( "Book 1 title : %s\n", Book1.title);
   printf( "Book 1 author : %s\n", Book1.author);
   printf( "Book 1 subject : %s\n", Book1.subject);
   printf( "Book 1 book_id : %d\n", Book1.book_id);

   /* print Book2 info */
   printf( "Book 2 title : %s\n", Book2.title);
   printf( "Book 2 author : %s\n", Book2.author);
   printf( "Book 2 subject : %s\n", Book2.subject);
   printf( "Book 2 book_id : %d\n", Book2.book_id);

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

   4.6            Unions
union is a special data type available in C that enables you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.
                Defining a Union
To define a union, you must use the union statement. The union statement defines a new data type, with more than one member for your program. The format of the union statement is as follows:
union [union tag]
{
   member definition;
   member definition;
   ...
   member definition;
} [one or more union variables]; 

The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data which has the three members i, f, and str:

union Data
{
   int i;
   float f;
   char  str[20];
} data

Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. This means that a single variable ie. same memory location can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For example, in above example Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by character string.
Accessing Union Members
To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use union keyword to define variables of union type. Following is the example to explain usage of union:
#include <stdio.h>
#include <string.h>

union Data
{
   int i;
   float f;
   char  str[20];
};

int main( )
{
   union Data data;       

   data.i = 10;
   data.f = 220.5;
   strcpy( data.str, "C Programming");

   printf( "data.i : %d\n", data.i);
   printf( "data.f : %f\n", data.f);
   printf( "data.str : %s\n", data.str);

   return 0;
}
When the above code is compiled and executed, it produces the following result:
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming

Here, we can see that values of i and f members of union got corrupted because final value assigned to the variable has occupied the memory location and this is the reason that the value if str member is getting printed very well. Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having union:

#include <stdio.h>
#include <string.h>

union Data
{
   int i;
   float f;
   char  str[20];
};

int main( )
{
   union Data data;       

   data.i = 10;
   printf( "data.i : %d\n", data.i);
  
   data.f = 220.5;
   printf( "data.f : %f\n", data.f);
  
   strcpy( data.str, "C Programming");
   printf( "data.str : %s\n", data.str);

   return 0;
}

When the above code is compiled and executed, it produces the following result:

data.i : 10
data.f : 220.500000
data.str : C Programming

Here, all the members are getting printed very well because one member is being used at a time.



5.       Typedef
Type definitions make it possible to create your own variable types. The C programming language provides a keyword called typedef, which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers:

typedef unsigned char BYTE;

After this type definitions, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example:.

BYTE  b1, b2;

In the following example we will create a type definition called “intpointer” (a pointer to an integer):

      #include<stdio.h>

      typedef int *int_ptr;

      int main()
      {
            int_ptr myvar;
            return 0;
      }

It is also possible to use type definitions with structures. The name of the type definition of a structure is usually in uppercase letters. Take a look at the example:

      #include<stdio.h>

      typedef struct telephone
      {
            char *name;
            int number;
      }TELEPHONE;

      int main()
      {
            TELEPHONE index;

            index.name = "Jane Doe";
            index.number = 12345;
            printf("Name: %s\n", index.name);
            printf("Telephone number: %d\n", index.number);

            return 0;
      }

Note: The word struct is not needed before TELEPHONE index;



typedef vs #define
The #define is a C-directive which is also used to define the aliases for various data types similar totypedef but with following differences:
  • The typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, like you can define 1 as ONE etc.
  • The typedef interpretation is performed by the compiler where as #define statements are processed by the pre-processor.

Sources:
5. http://www.geeksforgeeks.org/g-fact-53/