Friday, 9 September 2016

UART EMULATION IN MICROCONTROLLERS

“This blog describes how to emulate UART using Simple GPIO, Timer and external Interrupt”
Emulated UART requires in the application where UART peripheral available on the controller is not free to communicate with other device through UART communication.
UART will be emulated through simple GPIO pins, External Interrupt ant Timer peripherals. GPIO pins will be used as Transmitter and receiver pin.  Timer peripheral used for generating timing event according to UART communication baud rate.
Figure below show the simple block diagram of UART emulation through Microcontroller.


In this Simple GPIO pins will be as Tx and Rx pins. Data will be transmitted by SET and RSEST of transmitter pin at specific time interval on timer overflow event. Data transmission is handled by Transmitter module. MCU detect receiving data through external Interrupt event and reading Rx pin status. Receiving function is handled by Receiver module. Data generator module handles all data formatting and communication status flag monitoring.
Transmitter Working
The principle behind simulating UART transmitter is configure transmitter pin in output mode and changing signal level between GND and VDD at timer overflow  interrupt event according to data to be transmitted. In this transmitter overflow period will be half of the bit period that depends on the baud rate.
For example if our baud rate is 9600 bps then bit period will be around 104 usec and half of the bit period will be 52 usec. Timer will be configured to generate interrupt after every 52 usec if timer is enabled.
At idle state timer will be disabled and Tx pin output status will be High (VDD). When there will be data transmission request CPU Low (Start Bit) the Tx Pin and Enable Timer module configured to half bit period. In timer interrupt there will be Counter that will be increment by one after every interrupt event. After Start Bit transmission CPU will monitors the monitor the Counter value. At each even Counter value CPU change the status of Tx pin according to data to be transmitted. When complete 8 or 9 bit data is transmitted CPU pulls the Tx pin to VDD (End bit) and after successful transmission of End Bit clear the Counter Value and disable the Timer module.
For example we have to transmit 8-bit data 0x55. As shown in figure above 8 bit data to be transmitted is 0x55. So the complete frame structure will be:


Figurer below show the Timing diagram and Tx Pin status according to data 0x55:


As shown in figure above Initially Tx pin will be in idle state (pulled VDD) and TC (Transmission Complete) flag will be high. When there will request for data transmission CPU pulls the transmitter Pin to ground, TC flag and enable Timer Module configured to half but period. In Timer Overflow interrupt routine CPU increment the Counter Flag by one each time. On the even value of Counter CPU change the Tx Pin status according to data. After complete data transmission CPU disable the timer and clear the Counter value. After complete data transmission CPU set the TC (Transmission Complete) flag to 1.
Receiver Working
Principle behind simulating UART receiver is firstly detect the start bit using external interrupt on Rx pin and then taking 3 sample of the Rx signal at ODD value of Counter. If three samples are same then CPU consider it a valid data bit and if samples are different then CPU SET the FE (Framing error) Flag configure Receiver Module to Idle state. After successfully start bit detection CPU clear the RC (Reception complete) Flag. And after complete byte reception (detection of End Bit) CPU RC flag.


As shown in figure above receiving procedure starts after detecting external interrupt on Rx pin. Rx pin is configured to external interrupt on falling low event. When start bit (0) of data occurs on the Rx pin CPU get interrupted. After interrupt event CPU Reset the RC flag, disable the External interrupt on Rx pin and enable timer module configured to half data bit rate overflow time period. In Timer Overflow interrupt routine CPU increment the Counter Flag by one each time. On the ODD value of Counter CPU poll the Rx Pin status.
 If all three samples are same CPU consider it a valid data bit. CPU ignores the even counter values. In the same way CPU detects all data bits and when CPU receives completed data byte it will disable the timer, clear Counter, set RC flag and enable External interrupt to receive next byte.
If all three samples are not same CPU consider it as Corrupted data and set FE flag. After this CPU configure receiver module to idle state.

Same procedure will be follow for 9-bit data transmission or with parity bit communication. This procedure explained id for half duplex communication. For full duplex communication it will require two timer modules, each for Transmitter and Receiver Module.

Thursday, 11 August 2016

UART Communication

UART stands for universal asynchronous receiver and transmitter. UART is an asynchronous half duplex communication protocol. It is called universal because of configurable parameters such as speed, frame format and can be configured to meet the needs of a given communication requirement. There is no clock signal between transmitter and receiver. Both transmitter and receiver may work on different clock speed.  Two devices communicate with each other through three signals TX, RX and GND as shown in figure below:

Device1 Tx will connect with Device2 RX and Device1 RX will connect with Device2 TX and both devices GND will be common.  It is half duplex communication protocol which share the same register for data transmission and register. So when using UART it should be kept in minds that you should transmit and receive simultaneously. At transmitter side UART done parallel to serial conversion of the data which is received from the CPU and at receiver end UART perform serial to parallel conversion on the data received through serial communication.
Frame Structure
In UART data is transferred in a proper frame structure. UART frame consist of data bits and control bits. UART frame consists of following data:
·        Start bit
·        8 or 9 data bit
·        Parity Bit (optional)
·        1 or 2 stop bit
Figure below show the data frame with 8 data bit 1 start bit and 1 stop bit:


The parity bit in UART data frame is optional.  The parity can be even or odd. The UART peripheral calculates the number of 1s present in the transmission. If the parity is configured to even and the number of 1’s is even then the parity bit is set zero. If the number of 1s is odd, the parity bit is set to a 1 to make the count even. If the parity is configured to odd, and the number of 1s is odd, then parity bit is set to 0. Otherwise it is set to 1 to make the count odd. At receiver end UART check remove this bit from the data. START bit always will be 0 and STOP bit always will be 1.
When there is no communication TX pin remains high. When Communication starts Transmitter pulls the TX pin low (START bit). After data bit STOP bit will be transmitted. Every Bit will be of certain duration. This depends on the communication Baud rate selected.
After getting START bit (Sense LOW on RX pin) receiver samples in the middle of every period and save data to UART DATA REGISTER and also give information to CPU by setting flag in register or by interrupt or CPU if enabled.  Receiver also verifies the Parity Bit and STOP bit. If there is any framing or parity receiver notifies to CPU by setting error bits in UART STATUS register.
Figure show below the transmission of Char ‘D’ without parity bit and 1 stop bit.
Char ‘D’ Decimal equivalent is 68 and hex decimal equivalent is 0x44.
Binary equivalent will be B”01000100”.


What is BAUD RATE?
BAUD rate defines the data communication rate in UART communication. Baud rate specified in bps(bits per second). So baud defines how many bits may be transferred in one second from one device to another device. For example if Baud rate defines as 9600 bps. It means 9600 bits can be transferred from one device to another device. For proper communication receiver and transmitter should be configured to same baud rate. Otherwise receiver will receive abrupt data.
One bit period at 9600 baud rate will be = 1/9600 sec = 104.16 usec
1 Byte with 1 start bit and 1 stop bit transmission time will be = 10*104.16 usec                                                                                            = 1.04 ms
So it takes 1.04 ms to transmit one byte from one device to another device.


Communication in Microcontroller

“In this blog we will discussed about wired communication modules in microcontroller, types of communications such as parallel, serial, synchronous or asynchronous communication.”

Main function of communication modules in microcontroller is for interacting with other microcontroller, peripherals, PC or other modules. These communications modules are inbuilt in microcontrollers. Communication protocols are the rules and regulation which both devices follow to communicate with each other. For example if two microcontrollers wants to communicates with UART it requires that both microcontroller should configure for same baud rate, no of stop bits and data bit to be communicated.

Parallel Communication
In parallel communication two devices communicates through several lines by communicating more than one bit at a time. In parallel communication transmitter will uses serial in and parallel out shift registers. The receive data can be directly read through 8-bit GPIO Register.


Parallel communication used for short distance communication. Example of parallel communication can be found in LCD interfacing through microcontroller. Parallel communication requires large numbers of electrical conductors wires and expensive to setup it. In parallel communication number of conductor wires increases as increase in numbers of bits to be transmitted at one time.

Serial Communication
In serial communication two devices communicates through single wire by communicating single bit at a time.  Data bits are transferred sequentially. At transmitter side there will be a parallel in serial out shift register and at receiver there will be serial in parallel out shift register.  In serial communication data is communicated in packet format by adding start and stop bits in the data.


Data is transmitted from one device to another device through single electrical conductor. Serial communication used in long distance communication and less expensive then parallel communication. Examples of serial communications protocol are as UART, USARTSPI, and I2C etc.
If both Serial and parallel channels for 1-byte communication are operated on same clock than Parallel communication speed will be 8 time faster than serial communication.
Serial communication can be Synchronous or Asynchronous.

Synchronous communication
In Synchronous communication transmitter and receiver work on the same clock signal.  This clock signal is provided by the master device who initiates the communication.  Receiver will detect the data according to timing of clock signal. Data transfer rate in Synchronous communication is faster as compare to asynchronous communication.


In synchronous communication there will be one master device and all devices are slave device. To start communication master will first generate start communication frame. In synchronous communication all the slave devices are addressed or selected through control signal from master device. Example of Synchronous communication protocols are SPI and I2C.

Asynchronous Communication
In asynchronous communication there is common clock signal between transmitter and receiver. To start communication it is required that sender and receiver should be configured on the same communication parameters such and data communication speed etc. In asynchronous communication bits are grouped together and control bit such as Start and stop bit also added with data to be transfer. To properly receives data receiver will oversampling the data.


Asynchronous communication is slow due to increase in extra control bit with every byte of data. If we are transmitting 8 bit data with two control bit start and stop bits than there will be 25% overhead.  Example of asynchronous communication is UART.




Continued...........

GPIO Pins in Microcontroller

GPIO Stands for General Purpose Input and Output pins in microcontroller. Peripherals in microcontrollers such as UART, ADC, SPI, DAC etc. will interact with the external environment through GPIO pins. To communicate with external environments core uses GPIO pins. For example to transmit or receive data from devices core will manages TX and RX pins for that purpose.  Depending on the operation required GPIO pins can be configured in PUT or OUT put mode. For example if controller giving any command to external environment GPIO pin will be in OUT put mode and if controller getting data for manipulation GPIO pin will be in INPUT mode.
In microcontroller there are different modes for INPUT and OUT put. These mode can be selected through peripheral registers in microcontroller.  
GPIO Input Mode
GPIO input mode can be selected by writing GPIO data direction and control registers. GPIO input mode is of following types:
High Impedance Mode
This mode is also called Tri-State or Floating point mode. In this mode pin status is not deterministic until external source is applied. By Default controllers pins are in floating point mode. Advantage of using High Impedance State is that controller pin can be pulled to high or low with less current. It is used in ADC sense when it required keeping ADC sense signal to be low.
Pull Up/Pull down Mode
In Pull up mode controllers pin will remain high until it is forced to ground by external source. In this mode a week pull up resistor is connected to VDD (controller supply) internal to pin microcontroller. In pull down mode controllers pin remains low until external supply is not applied. In this mode a week pull down resistor to ground. Pull up and pull down is used to ensure a defined state of input pin. This mode is used for external interrupt pins, ADC etc.

All GPIO input pins uses the concept of hysteresis to prevent spurious changes in state when an input value changes. Hysteresis is implemented on GPIO by setting two thresholds for a digital input which are VIH and VIL typically enumerated in the “Electrical Characteristics” section of microcontroller datasheets. VIH is the input-high voltage and represents the minimum voltage that must be applied to drive the pin high. VIL is the maximum input-low voltage needed to drive the pin low. This means if the input voltage is greater than VIL and less than VIH, the value at the pin depends on whether the past input value was above VIH, in which case the pin is high, or below VIL, which means the pin is low.


GPIO OUT MODE
GPIO input mode can be selected by writing GPIO data direction and control registers. In Microcontroller output mode is of following types:


PUSH –PULL MODE
Push-Pull Output Configuration uses two Mosfet or transistors. One is N-Channel and another is P-Channel Mosfet. The Upper switch will be ON when the output has to be driven high. It will connect controller pin directly with VDD. Lower switch will be ON when output has to be driven LOW. In this mode Pin State is deterministic. It will have any one state either High or Low Push Pull configuration will have the capability to Source or Sink the Current.  


OPEN DRAIN MODE
In this mode, the physical GPIO pin behaves same way as drain of MOSFET. The drain is open to connect it to any external element. The source is grounded and gate of internally driven. It has two states: either High-impedance or Low. The output pin is driven low by firmware, the voltage at pin is zero. When the output pin is driven high by firmware, the voltage can be either high or low


. It is mostly used for I2C bus where external pull-up resisters are used widely. It can be also used in Interrupt line where it is connected to multiple interrupt sources.

Tuesday, 5 July 2016

Memory Allocation in C for Variables

In this blog we will disused about the variables, initialization of variables, Local and Global Variables, Static Variables, RAM memory architecture and variables memory allocation in embedded C.

What are variables and constants?
Variables in C language are memory location identified by some name and program can manipulate this memory data. Each variable has some type of data type. Which define the type of data it can store and range of data. Variables are stored in the RAM memory location during execution time and used for saving critical data during run time.

Constants variables are name of memory location and usually stored in the program memory. They are temporarily stored in the RAM memory when they are examined. Constant value cannot be change during program execution.
For a specific compiler, range of these variables may vary from one system to another system.  In general range of data types are as follows:

Data Types
No Of Bits
Ranges
Unsigned Char
 8 bit
0 to 255
Signed Char
8 bit
-128 to +127
Unsigned int
16 bit
0 to 65535
Signed int
16 bit
-32768 to +32767
Unsigned long int
32 bit
  0  to 4294967295
Signed ling int
32 bit
-2147483648 to  +2147483647
Floating data
32 bit
-3.4E38 to +3.4E38

LOCAL Variables

Local variables are those whose scopes are limited up to a module. When we declare a variable in any function its scope will be up to this function. These variables are store in the stack memory. When exit from function occurs all variables losses there data.
For example following variable initialize local to function:

void function1(void)
{
unsigned char var1;
unsigned char var2;
unsigned int var3;
}

On function call these variables get memory allocation in the stack memory.
If we initialize data in function using dynamic memory allocation then it wills stores in the heap memory to save data. In heap memory if we not free the memory locations then it will not losses there data.

void function2(void)
{
unsigned chr *ptr1=malloc(10); // reserve 10 memory location
}

Global Variables
Global Variables are those which are declared globally. Scope f these variables are global. More than one function can access these variables. After reset controller copies these data to ram memory, during program execution these variables retain there values until power does not removed.
For example following variables are declared globally:
unsigned char var1,var2=0;
unsigned int varb3=0;
void main(void)
{
unsigned char var4, var5;

while(1)
{                  // software code
}
}

In the above example var1, var2, var3 are declared globally outside of main function and var4, var5 are declared local to main function. In following program var4 and var5 also work as global variable until there any type of reset. After entering in main function program remain in the while (1) loop.

Static variable
Static variables are those variables which are allocated a static memory location during initialization. All global variables are static in nature. It is also possible to declared static variable in a function. For example:

void function2(void)
{
          unsigned char var1;
          static unsigned char var2;      // static variable
}

In this example var2 is initialized as static variable. When function is called var2 allocated in the ram memory and retain there value after exit from function.  If you call these variable in another function then compiler will give error.

Memory Modal of Microcontroller
Memory model of microcontroller defines the memory allocation for Code memory, variable memory, stack memory, heap memory etc. When a program is loaded in microcontroller memory following data is stored in the memory:
·        Program to be executed
·        Constant variables
·        Initialized global static variables
·        Local Memory & Dynamic memory allocated data
When first time program is loaded in microcontroller all these data except local variables stores in the flash memory. In general Memory modal may be defined as shown in figure below:


Executable program, constants, read only data stores in the Flash memory’s Read Only section. After source code all the read write data stores in the flash memory.

After reset RAM memory always is in undefined state. All the variables declared initialized or not initialized, constants have to be store in the RAM memory to work program correctly. This all work done by the some software code that is inserted by the compiler before the main() routine. This small software code copies all the read write data from memory to ram memory. For variables memory allocation will be in the form as shown in figure below:


After flash memory RAM memory starts.  In ram memory firstly the constant, initialized static, global variable are allocated then uninitialized or zero initialize (ZI) variables are allocated to ZI data section. The small software code also zeroes all the ram location after ZI section.

After this LOCAL variables are allocated to RAM memory. Local variable can be allocated in the stack memory and Heap memory according to declaration of variables. If variables are declared using Dynamic memory allocation then variables allocated in the heap memory. Stack memory starts after the ZI section and grows down to lower memory location.
Heap memory starts lower memory RAM location and grows in up direction.

In this case there may be case when stack and heap memory collides. If this memory collision occurs then program may work abruptly.  When we dynamically allocate memory using malloc() or alloc() it will return a pointer variable which tell the memory availability. If the memory is available then it will return the pointer to allocated memory location. If memory is not free it will return a NULL value.