# Embedded C

## Pages

### I2C bus arbitration

We strongly recommed you to see the previous tutorial to understand the basics of I2C bus communication.

### Lets move to I2C bus arbitration

I2C is designed for multi master purpose. So that in a single bus more than 1 masters can be connected.

#### Consider a scenario when both the masters (Master1 and Master2) start the communication at the same time !!!??

In this condition only the bus arbitration occurs.

If Master1 started the communication by pulling the clock low then the Master2 cannot able to control the clock untill the SCL is released by the Master1 (Master2 is considered as a slave in this condition). After the stop bit is observed by the Maste2 then it will start the communication.

The physical setup of the I2C bus helps the Master2 not to disturb the communication when the Master1 is communicating.

As the structure of I2C bus is wired AND condition if one line is pulled low then the line stays low.

when the Master2 changes the line to high the the line must go high, If not then the bus is occupied by the some other device which puts the line to low such as Master1 here.

Master2 will not get it's the data on the bus as long as there is no stop sequence. It will not touch the line and it leaves the SCL, SDA.

If the master cannot make the data line to go high, then it looses the arbitration and needs to back of and wait untill the stop sequence is seen.

Later it can check the line and make attempt when the line is free.

Let us take a small example where the Maste1 and Master2 wants to communicate with the same Slave (addr: 1111001). Master1 wants to write data 01010101 and Master2 wants to write data 01101110 to the slave.

The slave acknowlendges it and so for both the masters are in the impression that it owns the bus because so for they have transmistted same data on the bus.

Now, each master wants to transmit it's own data to the slave.
Master1 - 010 and Master2 - 011   what will go in the bus 0 or 1 ???

The moment when the data does not math Maste2 arbitration will be lost and it backs off because Master2 tries the Move the SDA high the data on the SDA remains low as it is a wired AND configuration (as Master1 already occupies it).

The Master2 does not get its data on the bus as long as there has been no STOP sequence presense on the bus till then it wont touch the bus.

This is how the I2C bus arbitration works.

### ARi Interview Questions on Embedded C, C++, RTOS

The following questions are ARi embedded c interview questions on C, Embedded, I2C, RTOS, UART, RS232, RS485

1) What is the output of the following C Program?
#include<stdio.h>
int main()
{
char ch = 256;
printf("%d",ch);
return 0;
}

2) What is the output of the following C Program?
#include<stdio.h>
int main()
{
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
printf("%d",*(*(a+2)));
return 0;
}

3) What will happen when the program is compiled?
#include<stdio.h>
#include<conio.h>
int main()
{
int a[5];
int b = a[6];
printf("%d",b);
getch();
return 0;
}
Answer: Program will compile successfully b is junk value

4) Difference between Structure and Union ?

5) How will you define Enum? and explain about it?

6) What is the output of the following program?
#include<stdio.h>
#include<conio.h>
int main()
{
extern int a;
printf("%d",a);
getch();
return 0;
}
Answer: Program will not compile it will throw the undefined reference to `a' error.

7) Explain about Dynamic Memory Allocation?

8) Where is local, static, global variables are stored? and what is Bss ?

9) Explain about static variable ?

10) What is the Compilation process ?

11) What is the difference between RS232 and Rs485

12) What is I2C Start bit and Stop bit ?

13) Explain about I2C Arbitration ?

14) Explain about I2C Clock stretching?

15) Difference between NAND Flash and NOR Flash ? ( Which one is fast and more )

16) How do you vary the duty cycle of the PWM ?

17) Can we change the PWM duty cycle in runtime ?

18) Do you know about CAN ?

19) Did you use multi master I2C in your project ?

20) Why RS485 is less noise ?

21) Why Pullup resistors are needed in I2C lines SCL and SCK ?

22) How do you prioritize tasks in RTOS in you project ?

Post your doubts in the comment section

### I2C Bus Communication Protocol Tutorial with Example

#### What is I2C:

- Inter Integrated Circuit
- Bidirectional Data Transfer
- Half duplex (have only one data line)
- Synchronous bus so data is clocked with clock signal
- Clock is controlled when data line is changed

#### Speed of I2C:

low (under 100 kbps)
Fast (400 kbps)
high speed (3.4 mbps) I2C V2.0
2 wire communication :
SDA and SCL
Vtg high = 1, low = 0

when SCL = 1 data is a valid data, when SCL = 0 data changes
Basic protocol is master slave protocol
- Master controls the clock
- Slave device may hold the clock low to prevent data transfer
- no data transfer is present when clock is low
- It is a kind of wired and connection
- need to put pullup resistor
- default it is a open-drain or open-collector, so that adding pull up resistor is necessary so that it will have only two states that is 1.floating high and 2.drive low
- Default state is high when no device is pulling it low

#### Start condition:

SDA changes High to Low when SCL is High

#### Stop Condition:

SDA changes Low to High when SCL is High

#### Repeated Start:

Incase of repeated start START condition is generated instead of STOP after a frame.

#### Data Transfer:

It is byte oriented (8bit)
Ack transmited by recepient of the data
MSB first
First byte is transmitted by master and addressed slave is the recepient
Next byte is based on the last bit (R/W)
1 bit R/W
0 - master write

#### 9th Pulse ACK

ACK => SDA - low
maste only generates clock and slave pulls low the SDA line

#### I2C Multi Master:

It is a multi master bus
So bus arbitration is required
When two device tries to drive SDA to different value
It is necessary to be sure that is not interfiering with another message
If a device is trying to send logic one but hears logic 0, it immediately stops transmission and gives the other sender priority
Synch needed in SCL

Good for comm in On-board devices
Cost and complexity do not scale up with the num of devices

The complexity of supporting software components can be higher than that of scheme(EX. SPI - No need of address in SPI)

### What are hardware interrupts handled ?

When a device asserts its interrupt request signal, it must be processed in an orderly fashion. All CPUs, and many devices, have some mechanism for enabling/disabling interrupt recognition and processing:

At the device level, there is usually an interrupt control register with bits to enable or disable the interrupts that device can generate. At the CPU level, a global mechanism functions to inhibit/enable (often called the global interrupt enable) recognition of interrupts.

Systems with multiple interrupt inputs provide the ability to mask (inhibit) interrupt requests individually and/or on a priority basis. This capability may be built into the CPU or provided by an external interrupt controller. Typically, there is one or more interrupting mask registers, with individual bits allowing or inhibiting individual interrupt sources.

There is often also one non-Maskable interrupt input to the CPU that is used to signal important conditions such as pending power fail, reset button pressed, or watchdog timer expiration.

Figure 1 shows an interrupt controller, two devices capable of producing interrupts, a processor, and the interrupt-related paths among them. The interrupt controller multiplexes multiple input requests into one output. It shows which inputs are active and allows individual inputs to be masked. Alternatively, it prioritizes the inputs, shows the highest active input, and provides a mask for inputs below a given level. The processor status register has a global interrupt enable flag bit. In addition, a watchdog timer is connected to the non-Maskable interrupt input.

The interrupt software associated with a specific device is known as its interrupt service routine (ISR), or handler.

### Count the number of bits set in a integer

#### How to Check number of Bits set in a number(integer) ?

->Whenever a number increases by one the  LSB changes
->By using this technique we can easily find the number of bits set in a integer
->we can use, n &= (n-1) to find the number of bits set in a integer. Lets go to the program

count = 0;
while(n)
{
n &= (n-1);
count++;
}

#### Let us understand this Program with the help of number n = 52

count = 0

n = 52(0011 0100) & 51 (0011 0011) = 48(0011 0000)

count = 1

n = 48(0011 0000) & 47 (0010 1111) = 32(0010 0000)

count = 2

n = 32(0010 0000) & 31 (0001 1111) = 0

count = 3

### KPIT Walkin interview | Chennai 22nd April 2017 | 3 - 9 Work Experience

Share it as Fast

 Company Name KPIT Interview Type Walk In Job Title Embedded C Developer.  Model Based Development,  Project Lead and Project Manager,  Verification and validation Testing  Autosar Work Experience 3 – 9 Years Date 22nd April 2017 Job Location Banglore/Pune Interview Venue KPIT Technologies Ltd., SKCL Trition Square, 6th Floor, C3 to C7, Thiru-Vi-Ka Industrial Estate, Guindy, Chennai 600032 Interview Time 9AM – 4PM Salary Not Disclosed

### UART in PIC16F877A pic microcontroller with Proteus simulation

Before going to this tutorial you are recommended to see
1) GPIO Configuration in PIC16F877A
2) PIC16F877A Interrupt configuration

#### UART in PIC16F877A PIC microcontroller

Asynchronous communication can be configured in PIC16F877A with TXSTA(TRANSMIT STATUS AND CONTROL REGISTER) and RECEIVE STATUS AND CONTROL REGISTER(RCSTA). RC6 is a transmission pin and RC7 is a receive pin. in PIC16F877A. This RX needs to be connected to the receiver TX and viceversa for receiver.

#### TXSTA

We are going to configure Transmission as 8bit transmission(also no parity) (TX9 = 0). Enable transmission (TXEN = 0). Asynchronous transmission (SYNC = 0). Low speed mode (BRGH = 0).

#### RCSTA

Configure the receive control register as Enable Serial port (SPEN = 1). Enable continuous receive ( CREN = 1).

UART Baudrate generation
Microcontroller is going to operate on 20MHz oscillator frequency, UART is configured in Low frequency mode. So that to achieve a common Baudrate of 9600 SPBRG value is given as 31.
Below is the other baudrate values.

#### UART Transmission working in PIC16F877A

UART Receiving Opearation in PIC16F877A
More detailed explanation for this block diagram is given in the datasheet

### Embedded C Program

#include <xc.h>
#include <pic16f877a.h>

void interrupt ISR()
{
//If the received interrupt is because of
if(PIR1bits.RCIF == 1)
{
//Clear the interrupt
PIR1bits.RCIF = 0;
TXREG = (RCREG + 1);
while(TXSTAbits.TRMT == 0);
}
}

void UART_Init()
{
//Select 8bit transmission
TXSTAbits.TX9 = 0;
//Enable Transmit
TXSTAbits.TXEN = 1;
//Async mode select
TXSTAbits.SYNC = 0;
//Operate in Low Speed
TXSTAbits.BRGH = 0;

//Enable Serial Port
RCSTAbits.SPEN = 1;
RCSTAbits.CREN = 1;

//Baudrate 9600
SPBRG = 31;

//Enable global interrupt
INTCONbits.GIE = 1;
//Enable Peripheral interrupt
INTCONbits.PEIE = 1;

PIE1bits.RCIE = 1;
PIR1bits.RCIF = 0;
}

void main(void) {
//Initialize UART
UART_Init();
//Loop forever
while(1);
return;
}

Here the UART is initialized first as a 8bit transmission with 9600(approx) baudrate, both transmit and receive is enabled. To receive the interrupt on every data received through RC7 receive pin, global interrupt, peripheral interrupt needs to be enabled. RCIE bit enables the actual uart rx(receive) interrupt.

In the Interrupt service routine RCIF flag bit is used to check, the interrupt is occured by receive interrupt. If so, clear the flag RCIF. RCREG register holds the received 8bit data.

For example, We are going to transmit the next ASCII value of the received value. TRMT bit is used to stop until the transmit completion. So that If the received data is 'A' Transmit data will be 'B' and so on.

#### Proteus Hardware Simulation Circuit

Virtual Terminal in Proteus is as below
Virtual Terminal Configuration

#### What if Baudrate mismatch ?

When baudrate mismatch communication will not be proper as shown below.

#### Video tutorial

Addon - What is loopback Test ?

### Interrupts in PIC16F877A Pic microcontroller with Push button Example using Proteus

#### Before going to this tutorial, you are recommended to see

1) PIC16F877A GPIO configuration

#### What is Interrupt ?

Interrupts are used to interrupt the processor, to perform some other task. After completing the task, processor will continue it's previous task.

#### Interrupts in PIC16F877A Pic microcontroller

PIC16F877A has 15 interrupts which has one GPIO interrupt i.e., RB0/INT.

#### How to configure this GPIO as a interrupt ?

1) Configure the RB0 pin as a input
2) Enable the Global interrupt.(GIE)
3) Enable Peripheral interrupt.(PEIE)
4) Enable RB0 interrupt.(INTE)
5) Write the interrupt service routine using interrupt keyword before the function.

#### Embedded C Program

#include <xc.h>
//interrupt service routine
void interrupt ISR() {
//Check if the interrupt is because of
//RBO GPIO pin
if(INTCONbits.INTF == 1) {
//Clear the interrupt
INTCONbits.INTF = 0;
//If the LED is on
if(PORTBbits.RB1 == 1) {
//turn off the LED
PORTBbits.RB1 = 0;
}
//If the LED is off
else {
//turn on the LED
PORTBbits.RB1 = 1;
}
}
}
void main() {
//RB0 as a input
TRISBbits.TRISB0 = 1;
//RB1 as a output
TRISBbits.TRISB1 = 0;
//RB1 high so LED On
PORTBbits.RB1 = 1;
//Enable the Global interrupt
INTCONbits.GIE = 1;
//Peripheral Interrupt Enable
INTCONbits.PEIE =1;
//enable RB0 interrupt
INTCONbits.INTE = 1;
//Loop forever
while(1);
return;
}

#### Also See

Push button Example using 8051

### What is Background Debug Mode, and why do I want it?

BDM stands for `Background Debug Mode', and it is a special debug interface on some of Motorola's embedded 68K and Power PC processors. BDM allows an external debug system to control and monitor the operation of the embedded processor through a 10-pin proprietary serial interface, without any software support in the target system and without the use of an In-Circuit Emulator (ICE).

Using a low-cost interface cable to your PC's printer port, and the right software on your PC, you can perform most of your debugging directly on your target hardware at very low cost.

### Multiple Blinking LED using PIC16F877A with Proteus Simulation

#### Recommended To Know before you go to this tutorial

1. How to configure PIC16F77A as a GPIO
2. Simple Blinking LED tutorial with PIC16F77A

In this tutorial Blue, Green, Red, Yellow these 4 LEDs are turned on and off with some delay. It is one of the application of GPIO configuration.

#### Embedded C Program

#include <xc.h>
void main(void) {
//PORTA pin 0 as output
//Direction register configuration
TRISA = 0;
//Initialize the variable
//used for the delay
int i = 0;
//loop for ever
while(1)
{
//LED 4 OFF
RA3 = 0;
//LED 1 ON
RA0 = 1;
//Delay function
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
//LED 1 OFF
RA0 = 0;
//LED 2 ON
RA1 = 1;
//Delay
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
//LED 2 OFF
RA1 = 0;
//LED 3 ON
RA2 = 1;
//Delay function
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);

//LED 3 OFF
RA2 = 0;
//LED 4 ON
RA3 = 1;
//Delay
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);
for(i = 1; i< 6000; i++);

}
return;
}

#### Proteus Simulation Output

Here, All the LED's are turned on and off one by one with some delay.

#### Video Tutorial

Also See Multiple Bliking LED for 8051

### What is the processor support provided for debugging ? Explain JTAG/BDM ?

A standard specifying how to control and monitor the pins of compliant devices on a printed circuit board. Each device has four JTAG control lines. There is a common reset (TRST) and clock (TCLK). The data line daisy chains one device's TDO pin to the TDI pins on the next device.  The protocol contains commands to read and set the values of the pins (and, optionally internal registers) of devices.

This is called "boundary scanning". The protocol makes board testing easier as signals that are not visible at the board connector may be read and set. The protocol also allows the testing of equipment, connected to the JTAG port, to identify components on the board (by reading the device identification register) and to control and monitor the device's outputs. JTAG is not used during normal operation of a board.

Refers to the transfer of executable code from a host to a target, typically using an RS-232 serial line. The target must have resident software (e.g., EPROM) that can read the incoming data, translate it if necessary (the file format may be ASCII hex for example) and load and run the code.

If the target board has no resident software, then an ICE is required. The ICE connects to the host via RS-232 typically and accepts the download and loads the code into memory.

### Blinking LED using PIC microcontroller PIC16F877A and Proteus simulation

Before Going to this PIC16F877A LED blinking tutorial, we are recommending you to see how to configure a pin in PIC microcontroller PIC16F877A as input or outtput. From the link below

If you have learned how to configure the PIN as a output using TRIS directio register. You can go forward to use it in a application. i.e., Blinking LED using PIC16F877A pic microcontroller.

#### PICF16F877A Blinking LED Circuit (Proteus)

In this circuit Oscillator frequency is used as 8MHz. and a RA0 is connected to the LED through a 400 ohm resistor.

#### Embedded C Program

#include <xc.h>
void main(void) {
//PORTA pin 0 as output
TRISA0 = 0;
//Initialize the variable
int i = 0;
//loop for ever
while(1)
{
//LED ON
RA0 = 1;
//Delay
for(i = 1; i< 6000; i++);
//LED OFF
RA0 = 0;
//Delay
for(i = 1; i< 6000; i++);
}
return;
}

#### PIC16F877A blinking LED Proteus Output

Whenever the RA0 is high LED will blink, and when it is low it will not blink. A small delay is given to visually see the led blink in a real world.

### Configure GPIO in PIC16F877A example with PROTEUS simulation

#### GPIO in PIC16F87XA

GPIO in PIC16F877A is divided into 5 ports that is PORTA, PORTB, PORTC, PORTD, PORTE. We can configure a GPIO pin as a input or output. In all the microcontroller that can be set with the direction register.
Incase of PIC16F877A we can use a direction register TRIS. For every port there will be one TRIS direction register port. Consider the PORTA, which has TRISA. The address is given below.

#### What is the use of TRIS ❓

As given above TRISA, TRISB, TRISC, TRISC, TRISD, TRISE is used as direction register. So that writing into this register will configure the particular GPIO port as a input or output.

#### How to configure input and output with TRIS ❓

For this we need to refer the datasheet of the PIC16F877A. Setting a TRISA bit (= 1) will make the corresponding PORTA pin an input (i.e., put the corresponding output driver in a High-Impedance mode). Clearing a TRISA bit (= 0) will make the corresponding PORTA pin an output (i.e., put the contents of the output latch on the selected pin). This is common for other ports also.

Reading the PORTA register reads the status of the pins, whereas writing to it will write to the port latch. All write operations are read-modify-write operations. Therefore, a write to a port implies that the port pins are read, the value is modified and then written to the port data latch.

#### Example program to  cofigure the RA0 in PORTA bit 0 pin as output

#include <xc.h>
void main(void) {
TRISA0 = 0;
int i = 0;
while(1)
{
RA0 = 1;
for(i = 1; i< 6000; i++);
RA0 = 0;
for(i = 1; i< 6000; i++);
}
return;
}

### How to create a project using MPLAB IDE

Before going to this tutorial, Have you installed the MPLAB X ide and XC8 compile. Then click the link below to download and install it ðŸ˜Š.

#### How to create a project using MPLAB IDE

1. File -> New Project
2. Select Standalone project. (If you wish to select others click that option also you can see the description below)
3. Select the family or directly enter the name of the device.
4. Select the debugger you want to use. (Mostly preferred is ICD3)
5. Select the compiler
6. Give the name of the project
7. Finish to create the project

#### Create a .c file for the project

1. Select source files
2. Right click and select New -> main.c
3. Give a name for the .c file
4. Save it.

#### Generate Hex file

1. Modify the code as required
2. Click Build or clean and build.
3. In Output window build successful will come if the compilation is passed.
4. Also it will give the path of the generated hex file.

See the video tutorial below

3. First install the MPLAB IDE (MPLABX-v3.55-windows-installer)

4. Then install the 8 bit compiler (xc8-v1.41-full-install-windows-installer)

5. After installation open the MPLAB ide from the path
"C:\Program Files (x86)\Microchip\MPLABX\v3.55\mplab_ide\bin\mplab_ide.exe"

That's it, you are set up to program and compile for PIC controller.

### What is an In Circuit Debugger ?

ICE is an electronic tool that allows for debugging beyond the capabilities of a standard software debugger. An ICE is essentially a hardware box with a 2 to 3 foot cable attached to it. At the end of the cable is a multi-pin connector connected to a CPU processor chip, which is identical to the processor on the target board. The target processor is removed from your target board, and the connector plugged in.

The ICE allows for trapping the following types of activities: read/write to an address range, read/write a specific value from an address range, setting a breakpoint in EPROM, mapping emulator memory to target board memory, and other similar features. It also turns the host (a PC for example) into a debug station with supplied software. This allows for debugging of the target board even though the target does not have a keyboard, screen, or disk.

### What is a break point ?

A point in a program that, when reached, triggers some special behavior useful to the process of debugging; generally, breakpoints are used to either pause program execution, and/or dump the values of some or all of the program variables.

Breakpoints may be part of the program itself; or the programmer as part of an interactive session may set them with a debugging tool for scrutinizing the program's execution.

### Difference between memory mapped IO and mapped IO

Use of the same instructions and bus to communicate with both main memory and input/output devices. This is in contrast to processors that have a separate I/O bus and special instructions to access it.

The I/O devices are addressed at certain reserved address ranges on the main memory bus. These addresses cannot therefore be used for RAM. Motorola and Mostec architectures, among others, use memory mapped I/O.

### What is a monitor program ?

A monitor is a program installed in the micro controller, which provides basic development and debug capabilities. Typical capabilities of a micro controller monitor include: loading object files into system RAM, executing programs, examining and modifying memory and registers, code disassembly, setting breakpoints, and single-stepping through code.

Some simple monitors only allow basic functions such as memory inspection, and the more sophisticated monitors are capable of a full range of debug functions. Monitors can either communicate with a dumb terminal or with a host computer such as a PC. Much of the work of the monitor (such as user interface) can be offloaded to the host PC running a program designed to work with the monitor. This makes it possible to reduce the size and complexity of the code that must be installed in the target system.

### What is a Compiler and Linker ?

Compiler is a program that converts another program from some source language (or programming language) to machine language (object code). Some compilers output assembly language, which is then converted to machine language by a separate assembler.

A compiler is distinguished from an assembler by the fact that each input statement does not, in general, correspond to a single machine instruction or fixed sequence of instructions. A compiler may support such features as automatic allocation of variables, arbitrary arithmetic expressions, control structures such as FOR and WHILE loops, variable scope, input/output operations, higher-order functions and portability of source code.

Linker is a program that combines one or more files containing object code from separately compiled program modules into a single file containing loadable or executable code This process involves resolving references between the modules and fixing the relocation information used by the operating system kernel when loading the file into memory to run it.

### What is Just In Time (JIT) Compiler ?

#### What is Just In Time (JIT) Compiler ?

JIT means Just in Time compiler this technique was pioneered by the commercial Smalltalk implementation currently known as Visual Works, in the early 1980s. Currently it is also used by some implementations of the Java Virtual Machine under the name JIT (Just In Time compilation). A virtual machine implementation approach, used to speed up execution of byte-code programs. To execute a program unit such as a method or a function, the virtual machine compiles its byte codes into (hardware) machine code. The translated code is also placed in a cache, so that next time that unit's machine code can be executed immediately, without repeating the translation.

### Line Following | Obstacle avoiding | Light Following | Anti Falling Robot using Arduino

The following video contains the output of line following, obstacle avoiding, light following and anti falling robot. All of these robots are made up of arduino uno. The code for all of the robots will be available soon. Click below for the program for all the robots.

See the fastest line following robot here

### How are Logic Analyzers used for troubleshooting ?

Logic analyzers (LAS) are normally used for trouble shooting the hardware under development. It is also used to validate the timing performance of the system. A logic analyzer has a set of pod to which a flat cable is connected. These pods are address, data and control pods. There hardware under test shall have provision to insert the other end of the logic analyzer probe; under respective pods namely data, address, and control.

Usually LAS is an intelligent system where in you can select set the triggers using the scripts that is available within the LAS. Once the trigger occur the data is captured in the buffer in the LAS, which can be latter printed, or stored or analyzed.

### What is BIT (Built-in-Test) ?

BIT (Built-in-Test) is a periodic diagnostic software is built in your software which helps to detects failure on the ` hardware interfaces that with the system.

### What is protocol analyzer ?

Protocol analyzer is any device that captures and interprets the network traffic between two or more connected computer systems. The traffic can then be decoded so that it is possible to see what processes are occurring. By examining the flow of traffic, protocol analyzers can be used to find out where problems (such as bottlenecks or the failure of a network device) are on a LAN.

Advanced protocol analyzers can also provide statistics on the traffic that can help to identify trends that may in future lead to further problems with the network.

Also See

protocol analyzer examples
protocol analyzer wireshark
protocol analyzer hardware
wireless protocol analyzer
serial protocol analyzer
protocol analyzer and packet sniffer
protocol analyzer open source
protocol analyzer vs port scanner

### How do you troubleshoot timing based requirements ?

There are two ways to troubleshoot timing based as shown below,

The timing based requirements can be tested either using a logic analyzer, where in you set he trigger and start the timing, calculate the difference between start and the end timing.

You can instrument your code using (say some compiler suite gives this provision) and then use code test, code tap to collect the tags and then through analysis we can verify the timing requirements.

Also See
hardware troubleshooting definition, what is software troubleshooting, hardware troubleshooting pdf, hardware troubleshooting interview questions and answers, troubleshooting computer hardware problems and solutions, hardware troubleshooting guide

### How are embedded systems designed to make troubleshooting easier ?

By the help of generic monitor that you have in the code, which can be invoked only

Certain mode ( referred as slots, ), this piece of code sits inside the box and let the tester know what is happening within the box. Normally these piece of code is 100% dormant.

### What are JTags ?

#### Joint Test Action Group:

JTAG is a standard specifying how to control and monitor the pins of compliant devices on a printed circuit board.

Each device has four JTAG control lines. There is a common reset (TRST) and clock (TCLK). The data line daisy chains one device's TDO pin to the TDI pins on the next device.

The protocol contains commands to read and set the values of the pins (and, optionally internal registers) of devices. This is called "boundary scanning". The protocol makes board testing easier as signals that are not visible at the board connector may be read and set.

The protocol also allows the testing of equipment, connected to the JTAG port, to identify components on the board (by reading the device identification register) and to control and monitor the device's outputs.

JTAG is not used during normal operation of a board.

Bootloader is a software written in some high level language, it is usually flashed into the EERPROM, one power up it is first invoked and reads the first stage in from a fixed location on the Flash, called the "boot block". When this program gains control, it is powerful enough to load the actual application and hand control over to it.

### How to analyze or troubleshoot communication protocol ?

#### Troubleshooting communication protocol

Normally communication protocols are completely tested using protocol analyzers.

### What is the difference between simulator & emulator?

Emulator is a system that performs in exactly the same way as another, though perhaps not at the same speed. A typical example would be emulation of one computer by (a program running on) another. You might use an emulation as a replacement for a system whereas you would use a simulation if you just wanted to analyze it and make predictions about it.

Attempting to predict aspects of the behavior of some system by creating an approximate (mathematical) model of it. This can be done by physical modeling, by writing a special-purpose computer program or using a more general simulation package, probably still aimed at a particular kind of simulation (e.g. structural engineering, fluid flow). Typical examples are aircraft flight simulators or electronic circuit simulators. A great many simulation languages exist,

### What are In-circuit/Emulators/Debuggers?

A debugger is a software program used to break program execution at various locations in an application program after which the user is presented with a debugger command prompt that will allow him to enter debugger commands that will allow for setting breakpoints, displaying or changing memory, single stepping, and so forth.

ICE is an electronic tool that allows for debugging beyond the capabilities of a standard software debugger. An ICE is essentially a hardware box with a 2 to 3 foot cable attached to it. At the end of the cable is a multi-pin connector connected to a CPU processor chip, which is identical to the processor on the target board. The target processor is removed from your target board, and the connector plugged in. The ICE allows for trapping the following types of activities: read/write to an address range, read/write a specific value from an address range, setting a breakpoint in EPROM, mapping emulator memory to target board memory, and other similar features. It also turns the host (a PC for example) into a debug station with supplied software. This allows for debugging of the target board even though the target does not have a keyboard, screen, or disk.

### What is logic analyzer?

Logic would suggest that there are two types of logic analyzers. The first type is a logic analyzer, which enables timing analysis, whilst the second type enables state analysis. In reality, however, instruments often use a combination of these two functions.

The state analyser allows you to monitor whether the operating sequence in a digital circuit matches the expected sequence. In this instance the clock signal is put on the model to be tested and interrupts the data sampling. The logic analyser must therefore be able to function at this speed. The analyser functions synchronously in this mode.

The timing analyser is often used to determine the cause of an error detected by the state analyser. It enables you to find out, for example, if a specific signal has occurred too late or too early or if a glitch has caused false triggering. The analyser functions asynchronously in this mode.

The type of application will determine the minimum number of channels that the logic analyser should have. When choosing a logic analyser the following key criteria are important: speed, width and depth. In other words, a logic analyser must be able to capture events as quickly as possible and must offer a sufficient number of channels and memory capacity. The predefined capability of an analyser is also linked to its triggering capacity.

The disassembly software and probe adapters on a logic analyser play a crucial role in the efficiency when analyzing a complex processor with hundreds of connections. Due to the huge range of processor types currently on the market, each logic analyser must be compatible with literally hundreds of probe adapters. The disassembly software should also give a clear view of which instructions are actually executed and which conditional branches are actually taken.

### What is trouble shooting ? and why is trouble shooting difficult in embedded systems ?

#### What is trouble shooting?

The process of finding and resolving the bug in a software or hardware.

#### Why is trouble shooting difficult in embedded systems?

Most of the embedded system it deals with hardware and software, hence if any malfunction of the system requires appreciable knowledge to first isolate the problem as hardware of software. Also we have to adopt to the crude way of debugging like putting trace, analyzing the behavior, of the system etc., This makes the trouble shooting little tricky.

### Swapping - Demand Paging

#### Swapping/Demand paging

A kind of virtual memory where a page of memory will be paged in if an attempt is made to access it and it is not already present in main memory. This normally involves a memory management unit which looks up the virtual address in a page map to see if it is paged in. If it is not then the operating system will page it in, update the page map and restart the failed access. This implies that the processor must be able to recover from and restart a failed memory access or must be suspended while some other mechanism is used to perform the paging.

### Virtual Memory

#### Virtual memory

A technique in which a large memory space is simulated with a small amount of RAM, a disk, and special paging hardware. For example, a virtual 1-megabyte address space can be simulated with 64K of RAM, a 2-megabyte disk, and paging hardware. The paging hardware translates all memory accesses through a page table. If the page that contains the memory access is not loaded into memory a fault is generated which results in the least used page being written to disk and the desired page being read from disk and loaded into memory over the least used page.

### MMU support

A hardware device or circuit that supports virtual memory and paging by translating virtual addresses into physical addresses.

The virtual address space (the range of addresses used by the processor) is divided into pages, whose size is 2^N, usually a few kilobytes. The bottom N bits of the address (the offset within a page) are left unchanged. The upper address bits are the (virtual) page number. The MMU contains a page table, which is indexed (possibly associatively) by the page number. Each page table entry (PTE) gives the physical page number corresponding to the virtual one. This is combined with the page offset to give the complete physical address.

A- PTE may also include information about whether the page has been written to, when it was last used (for a least recently used replacement algorithm), what kind of processes (user mode, supervisor mode) may read and write it, and whether it should be cached.

### What is a Process?

A process is a single executable module that runs concurrently with other executable modules. For example, in a multi-tasking environment that supports processes, like OS/2, a word processor, an Internet browser, and a database, are separate processes and can run concurrently.

Processes are separate executable, loadable modules as opposed to threads, which are not loadable. Multiple threads of execution may occur within a process. For example, from within a data base application, a user may start both a spell check and a time consuming sort. In order to continue to accept further input from the user, the active thread could start two other concurrent threads of execution, one for the spell check and one for the sort. Contrast this with multiple .EXE files (processes) like a word processor, a database, and Internet browser, multi-tasking under OS/2 for example.

### Real-Time Kernels

A real-time kernel is a set of software calls that provide for the creation of independent tasks, timer management, inter-task communication, memory management, and resource management.

### Basic concepts of RTOS

Atomic an operation is said to be atomic if it can be completed without interruption.

Context Switch the process of changing execution from one process to the next. The time required to perform a context switch will have a significant impact on performance. So, knowing how much information is stored as part of a task's context may be important to you. The minimum amount of information required to perform a context switch is largely processor dependent, however, the RTOS vendor may have chosen to include some extra information that will slow down the context switch.

Cooperative multitasking in a cooperative multitasking environment, generally the current running task will be allowed to run until it completes or until it chooses to yield to another task. Yielding to another task may be explicit through a call to a yield function or it may be implied through a call to a function that may cause it to wait for an event or resource.

Counting Semaphore a mechanism for synchronizing processes and their access to resources.

Critical Section a section of code in a program that must be executed while no other piece of code is running. Typically, this means that all interrupts must be disabled. So, critical sections should be kept as small as possible.

Deadlock: Deadlock is a condition where multiple processes may be waiting for a resource to be made available which will never become available. Generally, the programmer must design the system to prevent deadlock from occurring. The typical approach to preventing deadlock in an embedded system is for tasks to always request needed resources in a predefined order.

Deferred interrupt processing Deferred interrupt processing is an approach used to minimize interrupt latency by reducing the amount of time spent inside interrupt service routines. Typically, the interrupt handler sends a message to the operating system indicating that the interrupt has occurred allowing the operating system to invoke a task to handle the external event. The improved interrupt latency due to this approach should result in more deterministic behavior of the system.

Event: An event is generally a mechanism provided by the RTOS to permit communications between processes.

Interprocess communications: Processes or tasks generally need a synchronized method of communications. The relationship between the tasks could be various, including one-to-one, one-to-many, or many-to-many. An RTOS needs to provide mechanisms to permit all of these kinds of communications. Common mechanisms include mailboxes, queues, and events.

Memory management Real-time operating systems frequently provide specialized memory management routines to help solve common embedded system problems. An RTOS may provide the ability to allocate memory in fixed sized blocks or from distinct memory pools, each of which may have special purposes. For example, distinct server processes may have unique memory pools for allocation. Typically the goal is to help avoid memory fragmentation that could lead to a system failure.

Mailbox a mechanism provided by an RTOS for interprocess communications. A process may have a mailbox that other processes can send messages to.

Multitasking/Time slicing A CPU typically can only have a single state or context. Essentially, the CPU can only do one thing at a time. Multitasking the process of frequently changing context to make it appear as if the CPU were performing multiple tasks simultaneously. This task switching may occur on either a cooperative or preemptive multitasking basis.

Mutual Exclusion Refers to ensuring that a shared resource cannot be accessed simultaneously to prevent unwanted interaction. One example of the need for mutual exclusion would be keyboard I/O. Generally; an operating system must ensure that only one process can have access to the keyboard at a time

Preemptive multitasking in a preemptive multitasking system, a supervisor or scheduling task can change which task is currently executing without the permission of the current task. In a preemptive system, the scheduler will generally switch tasks at a periodic interval known as the time slice.

Priority In a real-time operating system, tasks can be assigned a priority. Usually, the scheduler will allow higher priority tasks to run before lower priority tasks are allowed to run. However, there may be a lot of variations between different real-time operating systems and how they treat tasks varying priorities. Some systems will not allow lower priority tasks to execute at all until the higher priority tasks have completed. Other systems may assign larger time slices to higher priority task; yet still allow low priority tasks to execute with a smaller time slice.

Priority Inheritance Priority inheritance, an approach to dealing with the problem of priority inversion, allows a low-priority task to become high priority if it owns a resource that a high-priority task is waiting for. The goal of priority inheritance is to minimize the amount of time high-priority tasks are required to wait for needed resources.

Priority Inversion In a system where a high- and a low-priority task may both need access to the same resource, it is possible that the high-priority task may have to wait for the low-priority task to complete. This is called priority inversion. In such a situation, the low-priority task may not get its time slice until other high-priority tasks complete.

Process/Thread/Task A process, thread, or task is a unit of execution. The use of these terms may be somewhat indistinguishable at times, especially from one RTOS to the next. However, some environments actually define more than one of these. For example, under Windows NT, a process is usually an executable program. And that process may have multiple smaller threads associated with it. Sometimes, as is the case with Windows NT, the terminology in part describes how much context information is associated with it.

Queue a mechanism provided by an RTOS for interprocess communications. Usually, one process acts as a consumer, removing messages from the queue. And, one or many processes may act as producers adding messages to the queue.

Reentrant/Non-Reentrant Reentrant code is code, which does not rely on being executed without interruption before completion. Reentrant code can be used by multiple, simultaneous tasks. Reentrant code generally does not access global data. Variables within a reentrant function are allocated on the stack, so each instance of the function has its own private data. Non-reentrant code, to be used safely by multiple processes, should have access controlled via some synchronization method such as a semaphore.

Resource a resource is usually a mechanism provided by the RTOS to synchronize access to an object within the system, which requires mutually exclusive access. The object within the system, also frequently called a resource, may be a physical device such as a keyboard or an EEPROM, or just a system variable.
Scheduler The scheduler is the portion of the RTOS responsible for determining which task will run next. Real-time operating systems use a wide variety of algorithms for making this selection. Sometimes it is as simple as just allowing the next available process with the highest priority to run. Other systems may have a hybrid prioritized round-robin system where tasks are only allowed to run for a specific time slice before the next task is run.

Semaphore a mechanism for ensuring mutual exclusion or synchronizing processing related to a resource. Time slice The largest amount of time that a task will be allowed to run in a preemptive multitasking system before the scheduler may invoke a new task.

#### Scheduler scheduling policies are as follows

• First-Come-First-Served (FCFS)
• Shortest-Job-First (SJF)
• Priority Scheduling (PS)
• Round-Robin Scheduling (RR)
• Multi-level feedback queues (MLF)
• Real-time scheduling