All about Process in Linux/Unix – Developer Perspective

PROCESS:

In Linux every thing we sees executing or taking some action will be by the process. Processes carry out tasks within the operating system. For definition ” Any program in execution is called process”.  A program is a set of machine code instructions and data stored in an executable area of memory.

Processes are separate tasks each with their own rights and responsibilities. Each individual process runs in its own address space and not interacting with another process except through secure, kernel managed mechanisms.

LINUX PROCESS:-

An instance of a program is called a Process. In simple terms, any command that you give to terminal on your Linux machine starts a new process. Having multiple processes for the same program is possible. A process itself not a process, until it comes info execution.

In a Linux system no process is independent of any other process. Every process in the system, except the initial process has a parent process. New processes are not created, they are copied, or cloned from previous processes.

Types of Process:-

  • Foreground Process: A foreground process is any command or task you run directly and wait for it complete. They run on the screen and need input from the user.

A foreground Process begins by typing a command at prompt. For example, list of files in current directory

>ls
  • Background Processes: In Linux, a background process is nothing but process running independently. They run in the background and usually do not need user input.

For example

  • Antivirus in your computer, normally it is running in background.

 

Basic command for Linux process:-

ps:

The ps command is used to provide information about the currently running process, including their process identification number(PID).

The basic syntax of ps is

>ps

When ps is used without any option, which display default  information of process currently running on the system .

The four items are labeled PID,TTY,TIME,CMD

PID-  Process identification number.

TTY- TTY is the name of console or terminal shows currently console.

TIME- Time is the amount of CPU, time in minutes and seconds that the process has been running.

CMD- Cmd is the name of the command that launched the process.

 

 

 

 

ps –e:-

ps –e command is used for list of all process running on the system in a single shot

>ps –e
  • –e show all process not just those belonging to user.

 

 

 

 

 

 

 

 

 

 

 

 

pstree:-

pstree is a command that shows the running processes as a tree fromat. It  is  used as a alternative to the ps command.

The basic syntax of the pstree is

>pstree

pstree command is similar to the ps command, but instead of listing the running processes ,it shows in a tree format.

 

 

 

 

 

 

 

 

 

 

bg:-

Linux treats everything as file, even the processes as files under /proc directories. The processes are basically program in execution, they also called jobs

The bg command is the processes that have been stopped by some interrupt signal can be continued background with bg command

Syntax for bg command

  • ./output &

 

 

 

fg:-

The  fg command  is like bg command Except that instead of sending a command in the background it runs them in foreground and occupies the current terminal and wait for process to exit.

top:-

In Linux, top is a command used to display processor activity of your linux , this command shows the  information of the system and the list of processes  which are currently running in the Linux

 

 

 

 

 

 

 

 

 

 

 

 

  • PID:Shows task’s unique process id.
  • PR: Stands for priority of the task.
  • SHR:Represents the amount of shared memory used by a task.
  • VIRT:Total virtual memory used by the task.
  • USER:User name of owner of task.
  • %CPU: Represents the CPU usage.
  • TIME+:CPU Time, the same as ‘TIME’, but reflecting more granularity through hundredths of a second.
  • SHR:Represents the Shared Memory size (kb) used by a task.
  • NI:Represents a Nice Value of task. A Negative nice value implies higher priority, and positive Nice value means lower priority.
  • %MEM: Shows the Memory usage of task.

 

Kill

kill command in Linux (located in /bin/kill), is a built-in command which is used to terminate processes manually. kill command sends a signal to a process which terminates the process.

 

EXAMPLES

> kill -9 -1        Kill all processes you can kill.

> kill -l 11         Translate number 11 into a signal name.

> kill -L             List the available signal choices in a nice table.

> kill 3453         Send the default signal, SIGTERM, to all those processes.

 

Now we will learn the Process with the developer prospective, here user can write C program using any editor wish and compile code using GCC.

Process  Identification:-

In Linux, User can be running various programs in the system, each running program must be unique identified by the kernel and program id identified by its own process is called “PID”, therefore process can be further categorized into

  • Parent process.
  • Child process.

Parent process-Parent process is processes that create other processes during run-time.

In command prompt, Command to get the parent process identity.

Header file need to include for getpid():

  • Sys/types.h
  • unistd.h
getppid()

Child process-Child process are created by the parent process by cone of it ,it will be behaves same as parent.

In command prompt, Command to get the child process identity.

Header file need to include for getppid():

  • Sys/types.h
  • unistd.h
getpid()

 

Now our first steps is to create process, fork is the system call which is used to create process. read on and follow –

Frok():-

Fork is a way to create new processes, fork() operation create a separate processes as a copy of itself then, the copy called the “child process”.

The child process has an exact copy of  the parent process. After the fork, both processes not only run the same program

The child has its own unique process ID and this PID not match the ID of any existing process

The child parent process ID is the same as the parent’s process ID.

Return value:

On success, the PID of the child is returned in the parent, and “0” is returned in the child. On failure, “-1” is returned in the parent, no child process is created and errno is set appropriately.

 

Header file need to include for fork:

 

unistd.h

 

 

 

 

 

 

 

 

 

 

 

Sleep():-

In Linux, Sleep() I s causes the calling thread to sleep either until of real-time specified in seconds have to elapsed .

Steps for sleep():-

Step 1– write a source code for sleep(), as shown in below image.

Step 2– Search for PID in all current running processes, by giving command ps.

Step 3-Enter in /proc and search that Pid by using ls command.

Step 4– Enter the Pid proc type cat status for the process states. Now you should be in /proc/pidof_yourprocess. Steps shown below.

$cd /proc <┘

$ls <┘

$cd  /proc/pid <┘

$cat status <┘

Now see the status of process, it will show process is sleeping.

 

 

 

 

 

 

 

 

 

 

 

 

 

Now check the status of process, that is sleeping.

 

 

 

 

 

 

 

 

 

wait system call

wait()  blocks the calling process until one of its child processes exits or a signal is received. After child process terminates, parent continues its execution after wait system call instruction.

Header files for wait:

  • sys/wait.h

 

 

 

 

 

 

 

 

 

 

Exec System calls family:-

 

  • Exec family of function or system call replace current process with new process.
  • There are various function used in the Exec  like
    • Execl
    • Exclp
    • Execle
    • Execve
    • Execvp
    • Execvpe

Header file need to include is

unistd.h

Example for execlp:-

 

 

 

 

 

 

 

 

Orphan process:-

Orphan processes are those processes that are still running even though their parent process has terminated or finished. A process can be orphaned intentionally or unintentionally.

An intentionally orphaned process runs in the background without any manual support. This is usually done to start an indefinitely running service or to complete a long-running job without user attention.

An unintentionally orphaned process is created when its parent process crashes or terminates. Unintentional orphan processes can be avoided using the process group mechanism.

Zombie process

Zombie processes usually occur for child processes, as the parent process still needs to read its child’s exit or crashes . Once this is done using the wait system call, the zombie process is eliminated from the process . This is known as the zombie process.

Professional Training Institute is the top embedded training institute in Bangalore, where student can learn the practical embedded system, we believe in hands on knowledge of subject such that student are not only getting the practical knowledge but also getting experience in embedded system development. All our students are able to get placed in top companies with the knowledge they gain in our institute. come and explore the possibilities, of amazing knowledge you can gain.

How Are Data Structures Useful In Embedded Systems?

How are data structures useful in embedded systems

Data Structures in Embedded Systems

This is a very common question my student is asking when we are data structure class for them. When a student joins embedded system training in our institute the data structure is not required an embedded system.
So we thought to write details description of where the data structure is used in the embedded world, so it will help another student across the world who can’t join embedded system training in Bangalore, India.
In the embedded system we are processing a large amount of data from Sensors/devices like ADC, accelerometer/gyro meter, data logger. Normally these data come to the microcontroller using UART, IIC, SPI, or Internal reading of registers like in case of internal ADC register. You can read our post which is talking about many types of sensors in an embedded system.

Most of the time data is updated in the microsecond or millisecond. It means a lot of data, so defiantly we have to save these data in the data structure. First, we will see what mechanism available in C language to save data, and then we will go through the real-time examples which type of data is saved into which type of data structure practically.

Different Data Structure in C

Data structures are arrays, structure, union, files, queues, stack, Linked lists, binary trees etc.

Arrays

To store a single data we use variables. To store a large number of data of the same data type we use arrays. The array is a collection of the same data type variable. In array, memory is allocated continuously.

Arrays can be a single dimension or multi-dimensions.
The size of the array is declared while declaring the array data type. It means we can’t change the size of the array run time. Here are the examples of Array
ex: int arr[5]; if starting address of arr is 0x7890, here we consider integer is 4 bytes long, then the array will be saved following ways.

Address of arr[0] is 0x7890
Address of arr[1] is 0x7894
Address of arr[2] is 0x7898
Address of arr[3] is 0x789c
Address of arr[4] is 0x78a0

Practical Example:

int AdcValue[100]: Read ADC value and save it into an array. Data will be read and save into an array.
float Temperature [50]: Here we are saving the temperature of the wheel and saving it into an array. We will take an average of all 50 elements and then find the average.
char UserName[40][20]: Here save 40 user name into an array, each size is 20 bytes long maximum.

Structure:

The structure is a group of different or same data type elements. In structure, we can have a float, int, char, etc data types grouped together. The memory allocated to structure elements is continuous, the first element occupies the memory address equal to the structure address, and next it stores the second element in memory.

Example:

struct Sen
{
char ch;
float receiveddata;
short count;
} senvar;

Here the sizeof structure senvar is 12 bytes, but if we calculate individual variable sizes than it becomes 1+4+2= 7 bytes. This is because the 32 bit systems stores the data in 32 bit aligned. First, if it stores character then if it stores float 4-byte size, then it would not store the data next to the character since if it stores then 4 bytes not stored in one 4 byte sequence. 3 bytes stored in one row and 1 byte in another row.

Example:
structure start address 0xffff5560
char ch stored at 0xffff5560
flaot receiveddata stored at 0xffff5564
short count stroed at 0xffff5568

So to save the memory while declaring the data in a structure we keep the elements aligned to 4 bytes size all integers, floats at one place then characters and short integers another place.
using structure packing instruction to the compiler we pack the data nest to each other for GCC compiler with code blocks you can use #pragma pack(1) to pack the structure.

Structure with bitfields:

To store the data in bit or bitfield of a memory we use structure fields.
In microcontroller we use registers, to access the bitfields of the register we can use structure/union bitfields.

Example:
struct reg{
unsigned int bit1:1;
unsigned int bit2:1;
unsigned int bitfield1:4;
unsigned int bitfield2:7;
unsigned int bitfield3:9;
unsigned int bitfield4:5;
unsigned int bitfield4:5;
} controlreg1;
here the bit1 is the bit name, 1 is the size of the bit
here the bitfield1 is the bitfield name, 4 is the size of the bitfield, etc.

Union:

The union also can be used to store the variables of different data types. Here all the data stored in the same memory location, the size of the union is equal to the biggest variable data it is holding.
we can also use the union to access both the register and bitfields.
Example: for example, we can define the structure in a union to access both register and
bitfields.
union {
unsigned int reg32;
struct {
unsigned int b1:6;
unsigned int b2:4;
unsigned int b3:6;
unsigned int b4:8;
unsigned int b5:8;
};
}reg2;

Practical Example:

typedef struct
wpan_endpoint_table_entry_t
{
/// Endpoint ID, 0 to 254 255 (0xFF) is used as an end-of-//table marker.
uint8_t endpoint;
/// This endpoint’s profile ID. See WPAN_PROFILE_* macros //for
some known profile ids
uint16_t profile_id;
/// Function to receive all frames for invalid clusters, or //clusters
with a \c handler.
wpan_ep_handler_fn handler;
/// Structure used to track transactions and conversations on
//ZDO/ZDP and
struct wpan_ep_state_t FAR *ep_state;
/// This endpoint’s device ID.
uint16_t device_id;
//Lower 4 bits are used, upper 4 are reserved and should 0
uint8_t device_version;
const wpan_cluster_table_entry_t *cluster_table;
} wpan_endpoint_table_entry_t;

Stack:

The stack is a first in Last out FILO concept. It is like we put the books one above the other than picking it from the top one after the other. we will be storing the data to stack by push() operation and data retrieving are done by pop() function.

Example program to create a stack structure:

The stack is normally used in the embedded system to saved the return of function and local variables.

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 2
struct Stack
{
int data;
struct Stack *next;
}*top;
typedef struct Stack stack;
int count =0;
int main()
{
push(20);
push(10);
disp();
pop();
pop();
pop();
free(top);
return 0;
}

void push(int d)
{
stack *newdata;
if(++count > MAXSIZE)
{
printf(“\n stack is full”);
return 0;
}
newdata= (stack *)malloc(sizeof(stack));
newdata->data = d;
newdata->next=top;
top=newdata;
}
void pop()
{
if(–count == -1)
{
printf(“\n stack is empty”);
return 0;
}
printf(“\ndata popped is = %d”, top->data);
top=top->next;
}

disp()
{
stack *ptr;
for(ptr=top; ptr; ptr=ptr->next)
printf(“\n%d “, ptr->data);
}

Queue Structure:

Queue structure is the FIFO concept first in first out data type. It is similar to the queue of a people standing to collect the ticket in front of a counter. Here the first person standing in front of the queue takes the ticket first, and the next person takes the ticket next.it goes on. In Queue data structure also the first data stored will be read back first and the last data stored will be read last.

Here Is The Practical Example Of A Queue

1. Declare A Queue

/* Declare a variable of type xQueueHandle. This is used to store the queue * that is accessed by all three tasks. */
static xQueueHandle gCellMesgQueue;
/* The queue is created to hold a maximum of 3 structures of type TaskMesg. */
gCellMesgQueue = xQueueCreate( 16, sizeof( TaskMesg ) );

2. Update queue when we received a message

And This is how we put message into queue
if(gCellTaskStarted)
{
cellTaskMesg.id = id;
cellTaskMesg.data = data;
xStatus = xQueueSendToBackFromISR( gCellMesgQueue, &cellTaskMesg,
&xHigherPriorityTaskWoken );
Once we received message into ISR we can update queue. This activity is asynchronous and whenever message received then we update into queue.

3. Continuously check the available message into a queue and take action

for( ;; )
{
if( uxQueueMessagesWaiting( gCellMesgQueue ) == 16 )
{
}
xStatus = xQueueReceive( gCellMesgQueue, &recvCellTaskMesg, 10
/*portMAX_DELAY*/ );
if( xStatus == pdPASS )
{
/* Data was successfully received from the queue, print out the received
* value and the source of the value. Based on received message id take
* action*/
switch( recvCellTaskMesg.id)
{
case E_CELL_TASK_MESG_ID_CELL_RX_BUF_RDY:
//vPrintStringAndNumber( “From Sender 1 = “, recvCellTaskMesg.id );
// for testing we can print message id and check.
CellTaskProcessRxBuf();
break;
case MESG_ID_CELL_STATE_TMR_EVT:

CellStateTimeout();
break;
case MESG_ID_CELL_MDM_RESET:
CellCommand_CmdReset(1);
……….
………
Like this based on message id we can take different action.

Linked Lists:

Arrays use the fixed memory and it allocates memory during compile time.
Linked lists are the data structures, the memory for these is allocated during run time means while the program is running.
Here how much data we want that much memory only we are going to allocate.
No memory is wasted. Extra memory is not allocated.
There are two types of linked lists, one is a singly linked list and another is a doubly-linked list.

Singly Linked List:

The singly-linked list means data is stored in the structural element and one pointer is pointing to the next data structure. Like this, the data structure nodes will be added and the size of the list increases.

Data Structures in embedded system, Singly Linked List:

Doubley Linked List:

Data is stored in data structure and it is having two pointers. One pointer pointing to the next element and the other pointer pointing to the previous element. We traverse the list in both directions one is starting to end called forward direction and the other is an end to start called reverse direction.

Doubley linkted list, data structure

Here is a practical example of link-list in embedded system

if (Alarm_list->Counter > 1) {
for(i = 0;i < Alarm_list->Counter-1;i++) {
for(j = 1;j < Alarm_list->Counter;j++) {
if (Alarm_list->plog[j].uStamp > Alarm_list ->blog[i].uStamp) {
u32SortTick = Alarm_list ->blog[i].uStamp;
u32SortCode = Alarm_list ->blog[i].u16EvtCode;
Alarm_list ->plog[i].uStamp = Alarm_list ->blog[j].uStamp;
Alarm_list ->plog[i].u16EvtCode = Alarm_list ->blog[j].u16EvtCode;
Alarm_list ->plog[j].uStamp = u32SortTick;
Alarm_list ->plog[j].u16EvtCode = u32SortCode;
}
}
}

Here Alarm_list is the list, as and when we get some alarm we make new node and update the information into the list, on the other side of code we are continuously monitoring the list, and if an alarm is generated for any of the thread then we process at a centralized location.

Binary Trees:

The data structure is arranged like a tree. The first node is called the root and the next it will connect to elements one is left and the other is right. A node above it is called the parent node and below the above node is called child nodes. The nodes at the end of the tree are called leaves of the tree.

Normally binary tree is used to sorting the data, more frequently is used where continuously data is coming and going, and always we need to present into sorting. Here we have shown many data structures, which are frequently used embedded systems. In this document, we are shown particle and real-time example code which I had written during my professional career. You can consider the following points while choosing data types in your projects.

Array:

When similar data type needs to save multiple numbers, like ADC value, temperature data, per minute motor revolution count, etc.

Structure

When we need multiple data type need to save and maintain. For example, if we read voltage, current, power factor time, etc. Another example is Task status, last action status, the command sent, the last response received, etc.

Structure Bit filed

In embedded bit filed is widely used, like consider we are updating Bit filed data bitwise also the possibility of data update on full integer. Like
Typedef volatile
struct
_ARM_I2C_STAT
US {
uint32_t busy : 1; ///< Busy flag
uint32_t mode : 1; ///< Mode: 0=Slave, 1=Master
uint32_t direction : 1; ///< Direction: 0=Transmitter,
1=Receiver
uint32_t general_call : 1; ///< General Call indication
(cleared on start of next Slave operation)
uint32_t arbitration_lost : 1; ///< Master lost arbitration
(cleared on start of next Master operation)
uint32_t bus_error : 1; ///< Bus error detected (cleared
on start of next Master/Slave operation)
uint32_t reserved : 26;
} ARM_I2C_STATUS;

Nested Union and Structure

Consider we have to read data from EEPROM byte by byte serially and saved them such a way that while using we want to use in a group of 4,4 bytes. In this case, we can make data structure which is nested with union and structure, as shown below
structure meter_Data{
unsigned int Voltage[2];
unsinged int Current[2];
char Hour;
char Min;
char Sec;
char Day;
};
union read_memory{
unsinged char readbytes[20];
structure meter_Data myMeter;
};
Now union read_memory can be used to read data one by one and while using we can use them as a group of 4 bytes which is an integer or as one byte which is character.

Binary Tree

The binary tree is used when the number of data is entering and leaving, Tree and we need to present always data into sorted order.

Here is a Professional Training Institute which is famous for practical embedded training, we focus on Data structure in practical ways. Our training methods are one on one which leads us to focus on each and every student and give them a complete practical training on C and Data structure. So if you are looking for embedded systems training in Bangalore then come and meet us once to explore in detail. We provide job oriented embedded system training and help our students until their job.

INTERFACING LCD 16*2 WITH 8051

INTERFACING LCD 16*2 WITH 8051

SUMMERY:

Connecting LCD 16*2 display to the 8051 microcontroller in 8 bitration method and also passing two commands.

COMPONENTS RECQURIED:

o 8051 Microcontroller
o 16*2 LCD Display
o Switch
o Binary Wires
o Power Supply

PIN DIAGRAM:

 

 

 

 

 

 

 

 

 

SOURCE CODE:


#include 
# define lcd P0 
sbit rs=P1^0; 
sbit e=P1^1; 
sbit b=P1^2; 

void dealy50ms(int a); 
void intial(char b); 
void delay1s(unsigned char c); 
void write1(); 
void write2(); 
void write3(); 
void write4(); 
void button() 
{
	int k=1; 
	while(k==1)
	{ 
		if(b==0)
		{ 
			intial(0x01); 
			k=0; 
		}
	}
} 

void display(char *d); 

int main() 
{ 
	b=1; 
	while(1)
	{ 
		intial(0x38); 
		intial(0x0c); 
		intial(0x01); 
		intial(0x80); 
		write1(); 
		intial(0xc0); 
		write2(); 
		button(); 
		intial(0x80); 
		write3(); 
		intial(0xc0); 
		write4(); 
	} 
} 

void display(char *d)
{ 
	for(*d;d!=NULL;d++)
	{ 
		lcd=*d;
		rs=1; 
		e=1; 
		delay1s(1); 
		e=0;
	}
} 
void write1()
{ 
	display("Done LCD16*2 ");
}

void write2() 
{
	display(" SUCESS ");
}

void write3() 
{
	display("Thank");
}

void write4()
{
	display("YOU");
}

void intial(char b) 
{
	lcd=b;
	rs=0;
	e=1;
	dealy50ms(2);
	e=0; 
} 

void dealy50ms(int a) 
{
	inti=0; 
	for(i; i < a ; i++) 
	{
		TMOD=0x01;
		TH0=0xff; 
		TL0=0xfc;
		TR0=1; 
		while(!TF0);
		TF0=0;
		TR0=0; 
	}
}

void delay1s(unsigned char c)
{
	int i,j;
	for(i=0;i < c;i++)
	{
		for(j=0;j<20;j++) 
		{
			TMOD=0x01; 
			TH0=0xff; 
			TL0=0xfc; 
			TR0=1;
			while(!TF0);
			TF0=0;
			TR0=0;
		}
	}
}

EXPLIANATION:

Now we will go through code and understand how LCD is working. Any C programalways start with main function. In our code main function contains.


int main()
{ 
	b=1; 
	while(1)
	{ 
		intial(0x38); 
		intial(0x0c); 
		intial(0x01); 
		intial(0x80); 
		write1(); 
		intial(0xc0); 
		write2(); 
		button(); 
		intial(0x80); 
		write3(); 
		intial(0xc0); 
		write4(); 
		} 
	}
}
Main function is started
intial(0x38); command 0x38
intial(0x0c);Passing 0x0C value for Display ON, Cursor OFF
intial(0x01);Passing 0x01 value for Clear the screen
intial(0x80);Passing 0x80 value for Force curser to the 1st line in first position
Write1();Calling write1 function to pass the “Done LCD 16*2 ” string to display function

Next how to send the commands through intial function to LCD


void intial(char b) 
{ 
	lcd=b; 
	rs=0; 
	e=1; 
	dealy50ms(2); 
	e=0; 
}
In Intial function, Passing the command from Microcontroller P0 to LCD through parallel communication from Microcontroller(P0.0-P0.7) to LCD(D0-D7). “rs” register pin used to set 1 or 0 is used to sending commands. “e” enable pin used to given value to LCD as making high to low.
Professional Training Institute is highly focus on practical embedded system training in Bangalore, Above post is writtern by our student Joy and Prathavi. We wish bright carrer ahead to both of them.

Next is interfacing button to the LCD to send different string data

 


void button()
{ 
	int k=1; 
	while(k==1)
	{ 
		if(b==0)
		{
			intial(0x01); 
			k=0; 
		} 
	}
}
In button function, Run the while part to check every time the value of k. b is connected to the switch when it pressed it becomes zero, It is initially high condition(1). Passing the value 0x01 to clear the screen. Once button is clicked the value of “k” changed to 0 to exit the while loop.

Next to pass the string value to the LCD through display function

 


void display(char *d)
{ 
	for(*d;*d!=NULL;d++) 
	{ 
		lcd=*d; 
		rs=1; 
		e=1; 
		delay1s(1); 
		e=0; 
	} 
}
Display function getting the string’s first address. rs is the register pin used to intimate the LCD as it is a data not a command. e is a enable pin used to given value to LCD as making high to low.

Next delay function for 50ms

 


void dealy50ms(int a)
{
	inti=0; 
	for(i;i<a;i++)
		{
			TMOD=0x01;
			TH0=0xff; 
			TL0=0xfc; 
			TR0=1; 
			while(!TF0); 
			TF0=0; 
			TR0=0; 
			} 
		}
}
Here is the delay function for 50ms you maximize the value through passing number to make higher, this is done trough using Timer concept

Next is the delay for 1s

 


void delay1s(unsigned char c)
{ 
	inti,j; 
	for(i=0;i<c;i++) 
	{ 
		for(j=0;j<20;j++) 
		{ 
			TMOD=0x01; 
			TH0=0xff; 
			TL0=0xfc; 
			TR0=1; 
			while(!TF0); 
			TF0=0; 
			TR0=0; 
		} 
	} 
}
Here is the same but used delay function for 1s you maximize the value through passing number to make higher, this is done through using Timer concept

From above the program it is written for 8 bitration of 16*2 LCD display for 2 commands. Here I used common initialisation command for all 16*2 LCD display which is in intial( ); and the strings are written in write1..4( ) functions and the display commands of working procedures also written in the display( ) function and also two different delays are represented as 50ms and 1s in delay50ms( ) and delay1s( ) function which is written in timer concept.
Professoinal Training Institute is focus in Practical embedded system training in Bangalore. This post is written by our student Joy and Prathavi, based on their executed experiments during training. we wish then for their bright career ahead.

Alternet Working Source Code:


#include 
#define Display_Port P0
// Selecting a display port P0 
sbit RS = P1^0; 
// Selecting Resistor Selection 
Port P1.0 
sbit EN = P1^1; 
// Port P1.1 for Enable Pin 
sbit button = P1^2; 
void delay_ms(int d);
// Function Prototype to generate mili second delay 
void lcd_data(char display_data); 
// Function Prototype to send information on LCD display 
void lcd_int(); 
// Function Prototype to initilization of Basics LCD Commands 
void lcd_command(char command); 
// Function Prototype to send commands on LCD Port 
/* .................Begining of Main Function .....................*/ 

void main() 
{ 
	inti=0; 
	int j=0; 
	int k=0; 
	int l=0; 
	int check = 1; 
	unsigned char a[9]="EMBEDDED"; 
	unsigned char b[8]="DESIGN"; 
	unsigned char c[6]="THANK"; 
	unsigned char d[4]="YOU"; 
	button =1; 
	lcd_int(); 

// LCD Initilization 
// button = 1; 

	while( a[i] != '\0' )
	{
		lcd_data(a[i]);
		i++;
		delay_ms(50);
	} 
	lcd_command(0xC0); // Command to Move Cursor to next line 
	while(b[j] != '\0') 
	{
	lcd_data(b[j]);
	j++; 
	delay_ms(50);
	}
	lcd_command(0x0C); // Command to set Display ON Curser OFF 
	//delay_ms(2000); // Delay for 2sec 
	while(check==1)
	{ 
		if(button == 0)
		{
			lcd_command(0x01); // Command To clear screen 
			check = 0; 
		} 
	} 
	while(c[k]!='

#include 
#define Display_Port P0
// Selecting a display port P0 
sbit RS = P1^0; 
// Selecting Resistor Selection 
Port P1.0 
sbit EN = P1^1; 
// Port P1.1 for Enable Pin 
sbit button = P1^2; 
void delay_ms(int d);
// Function Prototype to generate mili second delay 
void lcd_data(char display_data); 
// Function Prototype to send information on LCD display 
void lcd_int(); 
// Function Prototype to initilization of Basics LCD Commands 
void lcd_command(char command); 
// Function Prototype to send commands on LCD Port 
/* .................Begining of Main Function .....................*/ 
void main() 
{ 
inti=0; 
int j=0; 
int k=0; 
int l=0; 
int check = 1; 
unsigned char a[9]="EMBEDDED"; 
unsigned char b[8]="DESIGN"; 
unsigned char c[6]="THANK"; 
unsigned char d[4]="YOU"; 
button =1; 
lcd_int(); 
// LCD Initilization 
// button = 1; 
while( a[i] != '\0' )
{
lcd_data(a[i]);
i++;
delay_ms(50);
} 
lcd_command(0xC0); // Command to Move Cursor to next line 
while(b[j] != '\0') 
{
lcd_data(b[j]);
j++; 
delay_ms(50);
}
lcd_command(0x0C); // Command to set Display ON Curser OFF 
//delay_ms(2000); // Delay for 2sec 
while(check==1)
{ 
if(button == 0)
{
lcd_command(0x01); // Command To clear screen 
check = 0; 
} 
} 
while(c[k]!='\0') 
{ 
lcd_data(c[k]);
k++;
delay_ms(50); 
}
delay_ms(20); 
lcd_command(0xC0); // Move cursor to nest line 
while(d[l]!='\0') 
{ 
lcd_data(d[l]); 
l++; 
delay_ms(50); 
} 
while(1);
} 
/*................. END of Main Function .........................*/ 
/*................. Delay Sub Routile............................*/ 
void delay_ms(int d) 
{
inti,j; 
for(i=0; i<d; i++)
for(j=0; j<1257; j++); 
}
/*.....Sub Routine to send information over LCD...............*/ 
void lcd_data(char display_data)
{
Display_Port = display_data; 
RS = 1; 
EN = 1; 
delay_ms(1); 
EN = 0; 
} 
/*....... Sub Routine to send Commands over LCD Display.............*/ 
void lcd_command(char command) 
{ 
Display_Port = command; 
RS = 0; 
EN = 1; 
delay_ms(1); 
EN = 0; 
} 
/*........... Sub Routine to initilize the Commands............*/ 
void lcd_int()
{
lcd_command(0x38); 
delay_ms(10); 
lcd_command(0x0F); 
delay_ms(10); 
lcd_command(0x01); 
delay_ms(10); 
lcd_command(0x80);
delay_ms(10); 
}
') { lcd_data(c[k]); k++; delay_ms(50); } delay_ms(20); lcd_command(0xC0); // Move cursor to nest line while(d[l]!='

#include 
#define Display_Port P0
// Selecting a display port P0 
sbit RS = P1^0; 
// Selecting Resistor Selection 
Port P1.0 
sbit EN = P1^1; 
// Port P1.1 for Enable Pin 
sbit button = P1^2; 
void delay_ms(int d);
// Function Prototype to generate mili second delay 
void lcd_data(char display_data); 
// Function Prototype to send information on LCD display 
void lcd_int(); 
// Function Prototype to initilization of Basics LCD Commands 
void lcd_command(char command); 
// Function Prototype to send commands on LCD Port 
/* .................Begining of Main Function .....................*/ 
void main() 
{ 
inti=0; 
int j=0; 
int k=0; 
int l=0; 
int check = 1; 
unsigned char a[9]="EMBEDDED"; 
unsigned char b[8]="DESIGN"; 
unsigned char c[6]="THANK"; 
unsigned char d[4]="YOU"; 
button =1; 
lcd_int(); 
// LCD Initilization 
// button = 1; 
while( a[i] != '\0' )
{
lcd_data(a[i]);
i++;
delay_ms(50);
} 
lcd_command(0xC0); // Command to Move Cursor to next line 
while(b[j] != '\0') 
{
lcd_data(b[j]);
j++; 
delay_ms(50);
}
lcd_command(0x0C); // Command to set Display ON Curser OFF 
//delay_ms(2000); // Delay for 2sec 
while(check==1)
{ 
if(button == 0)
{
lcd_command(0x01); // Command To clear screen 
check = 0; 
} 
} 
while(c[k]!='\0') 
{ 
lcd_data(c[k]);
k++;
delay_ms(50); 
}
delay_ms(20); 
lcd_command(0xC0); // Move cursor to nest line 
while(d[l]!='\0') 
{ 
lcd_data(d[l]); 
l++; 
delay_ms(50); 
} 
while(1);
} 
/*................. END of Main Function .........................*/ 
/*................. Delay Sub Routile............................*/ 
void delay_ms(int d) 
{
inti,j; 
for(i=0; i<d; i++)
for(j=0; j<1257; j++); 
}
/*.....Sub Routine to send information over LCD...............*/ 
void lcd_data(char display_data)
{
Display_Port = display_data; 
RS = 1; 
EN = 1; 
delay_ms(1); 
EN = 0; 
} 
/*....... Sub Routine to send Commands over LCD Display.............*/ 
void lcd_command(char command) 
{ 
Display_Port = command; 
RS = 0; 
EN = 1; 
delay_ms(1); 
EN = 0; 
} 
/*........... Sub Routine to initilize the Commands............*/ 
void lcd_int()
{
lcd_command(0x38); 
delay_ms(10); 
lcd_command(0x0F); 
delay_ms(10); 
lcd_command(0x01); 
delay_ms(10); 
lcd_command(0x80);
delay_ms(10); 
}
') { lcd_data(d[l]); l++; delay_ms(50); } while(1); } /*................. END of Main Function .........................*/ /*................. Delay Sub Routile............................*/ void delay_ms(int d) { inti,j; for(i=0; i<d; i++) for(j=0; j<1257; j++); } /*.....Sub Routine to send information over LCD...............*/ void lcd_data(char display_data) { Display_Port = display_data; RS = 1; EN = 1; delay_ms(1); EN = 0; } /*....... Sub Routine to send Commands over LCD Display.............*/ void lcd_command(char command) { Display_Port = command; RS = 0; EN = 1; delay_ms(1); EN = 0; } /*........... Sub Routine to initilize the Commands............*/ void lcd_int() { lcd_command(0x38); delay_ms(10); lcd_command(0x0F); delay_ms(10); lcd_command(0x01); delay_ms(10); lcd_command(0x80); delay_ms(10); }

Interview Q and A 9

Interview Q and A 9



Ques 1. How to know the given controller is little endian or big endian ?

#include <stdio.h>
#include <stdlib.h>
int main()
{
    unsigned int x=0xaa55;
    unsigned char *p=&x;
if(*p == 0x55)
{
    printf("\n Little endian");
    printf("%x = %x\n",p, *p);
    printf("%x = %x\n",(p+1),*(p+1));
}
else
    printf("\n Big endian");
    return 0;
}


Ques 2. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a=5;
    {
      int a=9;
      printf("\n %d",a);
    }
    printf(" %d",a);
    return 0;
}

Ans. 9 5


Ques 3. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a=5;
    {
      a=9;
      printf("\n %d",a);
    }
    printf(" %d",a);
    return 0;
}

ans :  9 9



Ques 4. What is the difference between General purpose os and RTOS ?

RTOS :
  Rtos scheduling is based on priority
  Resopnse time is predictable
  kernel is preemptive or upto maximum degree
  priority inversion is a major issue
  it has less memory

Ex: Free RTOS, vxworks, RT linux, PSOS, VRTX, Lynx

General Purpose OS:
  GPOS scheduling  can be adjusted dynamically for optimized throuhput.
  Resopnse time is not predictable
  kernel is non preemptive or upto maximum degree
  priority inverson is unnoticed.
  it is having large memory.
 Ex: Microsoft windows, Redhat Linux, Apple MacOS


Ques 5. explain the meaning of below declaration?

const int PI, int const PI, const int *p,  int * const p, const int *const p;

const int PI : PI is a integer constant.
int const PI : PI is a integer constant.
const int *p:  p is a pointer to constant integer, data present in p is constant and ponter is not constant.
int * const p: pointer p is constant and data is not constant.
const int * const p: both pointer p and data are constant. 


Ques 6. what are the bitwise operators and its types?

bitwise operators are as mentioned below:

| bitwise or operator   
& bitwise and operator
~ bitwise 1's complement operator
^ bitwise xor operator
<< bitwise left shift operator
>> bitwise right shift operator.


Ques 7. which operator is suitable for checking perticular bit is set or not?
 >> and & operators.


Ques 8. what is the output for the below code?
int main()
{
    int a=3;
    int x=-15;

    a+x > 5? puts("a+x > 5 "): puts("a+x < 5");

    return 0;
}


ans: a+x < 5


Ques 9. write a program to swap two numbers without using third variable?

swap(int *p, int *q)
{
  *p=*p+*q;
  *q= *p-*q;
  *p=*p-*q;
}


Ques 10. write a program to pass array as argument to a function?

fun(int p[])
{
  int i=0;
  for(; i<3; i++)
  printf(" = %d \n", p[i]);

}

int main()
{
    int a[3] ={2,3,4};
    fun(a);
    return 0;
}


Ques 11. what is ohms law?
ohms law states that the current through the conductor is directly proportional to the voltage across
the two points of the conductor with resistance is constant.


Ques 12. what is the difference between call by value and call by reference ?
	call by value means we are passing copy of the original arguments to the formal arguments of the function.
             here the value changed in the formal arguments will not affect the original arguments 
	call by referece means we are passing the address of the arguments to the formal arguments of the function.
             here the value changed in the formal arguments will affect the original arguments.

Ques 13. what is the output for the below code if integer size is 4 bytes?

int main()
{
	int x=-1;
	printf("%x ", (x>>1));
	return 0;
}

ans : ffffffff


Ques 14. what is the equivalent pointer expression for the array element arr[i][j][k][m]?

ans:     *(*(*(*(arr+i)+j)+k)+m)


Ques 15. what is the output for the below code?

int main()
{
	int *p, **q, ***r;
	int x=9;
        p=&x;
	q=&p;
	r= &q;
	printf("%d %d %d", *p, **q, ***r);
	return 0;
}

ans: 9 9 9



Ques 16. what is the requirement of infinite loop in embedded system?

	Since embedded system has to continuously work and respond to the inputs, and some other jobs in loop. 
to make the system to run continuously for long time it has to be kept in infinite loop. 
Otherwise it will run only once and stops.



Ques 17: explain about ALU?
 ALU is present in the microprocessors  and microcontrollers. it will do the arithmetic and logic operations
 that is required to be done on instructions. The cpu is powerful if the design of the ALU good. It consumes
 more power and it releases more heat. This is why faster cpus consume more power releases more heat.

Interview Q & A 8

Interview Q & A 8



1. write a code for removing repeated digits in a number?
ex : number = 45678678 here the digits 6,7,8 has to be removed.



2. write a code to search the largest element in the array of your choice?



3. write a program to convert the integer string to number using atoi function.?


4. write a source code to find the sum of 1/3+1/5+1/7+ ....+1/n using recursive function?


5. write a code for linked list print function in reverse order?


6. what is the difference between address of variable and address of ponter variable, 
   explain using an example?


7. write a source code for insert a char/word/substring into a string?


8. can we return multiple values from the function explain with an example?


9.  what is the output for the below code?
	static int k= 8;
	int main()
	{
		if(-k)
		printf("%d", k);
		printf("error");
	}


10. what are the errors in the below source code?

int add();
int main()
{
	printf("function ",add());
}

int add()
{
	int x=5,y=4,z;
	z=x+y;
	printf("%d",z);
}


11. explain for the below code, the memory allocated is safe or not?

struct person
{
char per_name[10];
int per_age;
};
int main()
{
struct person *per;
per=(struct per*)malloc(sizeof(struct person));
free(per);
return 0;
}


12. explain the memory is safe for the below mentioned code?

struct person *per;
per=(struct person*)malloc(sizeof(struct person)*100);
char pername[] = "ptinstitute.in" ;
per = *pername;
free(per);
return 0;


13 what is the output for the below code explain?

char *name="ptinstitute.in";
char  name1[]="ptinstitute.in";
printf("%d %d ",strlen(name),strlen(name[]));
printf(" %d %d",sizeof(name++),sizeof(name[0]));


14. what is the output for the below program explain?
int main()
{
	int x=4,y=2,p,q,r;
	p=x||y;
	q=p&&x;
	r=p^q;
printf("%c %x %d",p,q,r);
return 0;
}


15. what is the output for the below code explain?

int main()
{
int p=4;
for( ;p++;printf("%d",p))
{
printf("ptinstitute.in");
}
return 0;
}

16. what is the output for the below program?

int main()
{
static int m=3;
main();
printf("%d",m++);
return 0;
}


answers:

10.  no errors. 
     output: 9 function

11. safe, because memory is allocated to pointer per.

12. here memory allocated to per , 
    then per = *pername         //it stores the 'p' in the per variable.
    we copying the ascii value of p to pointer p which gives runtime error.
    the allocated memory is not freed, so memory leakage happened here.

13. the prototype of strlen is
       size_t strlen ( const char * str );
    we need to pass the address of the string to find the length.
    in the program we passing strlen with name[], we are passing without index.
    we suppose to pass the address of the string. that is why it gives compile time error.
14. ascii character for 1, 1 0

15. it gives an lengthy loop, in the for loop we incrementing p++ in condition checking position,
    p++ doing continuously and the loop stops after p=0.

16 It gives an runtime error like stack over flow issue.
   here we are not exiting the recursive function main, it is calling continuously main recusively.



Interview Q & A 7

Interview Q & A 7



Ques 1. what is the priority inversion?
	If a low priority task holds the shared resource using semaphore that is required by the high priority task.
The high priority task has to wait till it completes the task. This is done by increasing the low priority 
task to high till it completes the task and once the finishes the task then it releases the resource to
high priority task. This is called priority inversion.


Ques 2. what are different memory segments of a program?

The memory segments are 

Stack segment:
	Here the local variables , arguments passed to the function, function return address, 
interrupt return address will be stored in stack. Stack grows from high memory to low memory.

Heap segment : This segment is used to allocate memory dynamically. It grows from low memory ot high.
we can allocate memory to pointers here.	
	
Uninitialised data segment:
Uninitialised data will be stored here.

Initialised data segment:
Initialised data will be stored here

Code segment:
The code and the constants will be stored here.


Ques 3. what is the difference between polling and interrupt?
	Polling : the system checks the IO devices is they need any cpu service and then do its service, this is called polling
        Interrupt: the IO device request the cpu to execute its service. this is called interrupt.

Some difference between interrupt and polling as follows:
Inerrupt:
	Device notify cpu that it needs cpu attention.
	Interrupt is a hardware mechanism
	An interrupt request line indicates the device needs a cpu service
        Interrupt handler services the device.
	The cpu is disturbed only when the device needs service, here the cpu cycles are saved.
        An inetrrupt can occur at any time
        Inerrupt is in efficient if the devices interrupting the cpu frequently

Polling:
	CPU checks in regular interval if any device is ready for service. 
	Polling is software mechanism.
	Command ready bit indicates the device is ready for service.
	CPU service the device
	Cpu has to check whether a device needs service regularly this wastes lots of cpu cycles.
        CPU Polls the devices at regular intervals. 
	polling becomes inefficient if the cpu finds the device rarly ready for the service.
	

Ques 4. what is semaphore?
 Semaphore is proposed by Dijkstra in 1965 is very significant technique, for solving the synchronisation issue in parallel processing.
Semaphore is simply nonnegative variable holding a number and shared between threads. 
This variable is used to solve critical section problem and to achieve process sychronisation mechanism.

There are two types of semaphores
  Binary semaphore: it is also called as mutex lock. when the thread want to use a resource then it take the
  semaphore uses the resource then it release the semaphore.

  Counting semaphore: it is used when the resources are more than one. If the thread wants to use the 
  resource then it take the semaphore and decrease the semaphore count, if another thread wants the resource then 
  it take the semaphore and decrement the count. After using the resource they release the semaphore and increment the count. 



Ques 5. what is mutex?

	Mutual exclusion object shortly called as Mutex.  Mutex is a locking mechanism. The thread uses the mutex, 
lock the mutex uses the resources then the same thread unlock the mutex. Only one process can use the mutex at a time.
Mutex allows the all threads to use mutex but one at a time.
The program requests the system to create a mutex object for a resource with an ID. when the thread wants to use the resource 
it will lock the mutex uses the resource then it unlocks the resource.


Ques 6. What is synchronous communication?
example communication happened between two people over the telephone.
communication happened with respect to clock signal is called synchronous communication.
synchronous devices require the clock has to be same in receiver and transmitter.
The receiver can sample the signal at the same time interval as the transmitters send the data.


Ques 7. what is watchdog timer?

the watchdog timer continuously counts and some malfunction occured in the system it will reset the system.
The watchdog timer has to be serviced before the watchdog timer expires. if some malfunction occured in system, then it wouldnot service
the watchdog timer. then it will reset the system.


Ques 8. Find the size of the structure ?

struct st1{
int var1;
char ch1;
int var2;
float f1;
};

Ans : 16 bytes.
 In 32 bit system the memory is allocaed in 32 bit size. To make the memory accessing faster it write/reads 32 bit data at a time.
thats why it allocates 4 bytes to char.and others to 4 bytes as usual. in case of char one byte for data and other 3 bytes store garbage.
to effectively use the memory all chars to be placed at one place, other 4 byte sized datatypes at another location.
we can pack the datatypes using #pragam pack(1) defination above the main function.


Ques 9. Convert Binary to decimal for the below numbers?
11001111

ans: 
1 * 2^0 = 1 *1 = 1
1 * 2^1 = 1 *2 = 2
1 * 2^2 = 1 *4 = 4
1 * 2^3 = 1 *8 = 8
0 * 2^4 = 1 *0 = 0
0 * 2^5 = 1 *0 = 0
1 * 2^6 = 1 *64 = 64
1 * 2^7= 1 *128 = 128
------------------------
                  207


Ques 10. find the size for the following?

char arr[6];
int iarr[8];
int *p;

the sizeof arr is 6 bytes
the sizeof iarr is 32 bytes
the sizeof p is 4 bytes


Ques 11. write the truth table for xor gate & or gate?

the truth table for XOR gate:
A   B   O/p
1   1    0
0   0    0
1   0    1
0   1    1

the truth table for OR gate:
A   B   O/p
1   1    1
0   0    0
1   0    1
0   1    1



Ques 12. what is the output for the below code?

#include< stdio.h >
#include< stdlib.h >

int main()
{
    int  arr[8] ={0,1,2,3,4,5,6,7,8};
    int i;
    for(i=2; i<8 ;i++)
        arr[arr[i]] = arr[i];
    for(i=0; i<8 ; i++)
        printf("%d ", i, arr[i]);
    return 0;
}

ans: 0 1 2 3 4 5 6 7

Artificial Intelligence

Artificial Intelligence

Definition Of Artificial Intelligence:

Artificial intelligence is the ability of a computer program or a machine to think and learn.

There are so many benefits to artificial intelligence. We can use AI in medical research, Aerospace, face recognition, railways, education, business, health care, banking and so on.

Nowadays Artificial Intelligence is the part of human life and humans are surrounded by AI technology like smart sensors, automatic parking systems, etc. By using artificial intelligence we can be simplifying the administrative tasks, smart content, personalized learning, global learning, and new efficiencies in the education system.

By using the right Artificial Intelligence technology your business may save time and money automating the process and we can increase the productivity and quality of the product in the business.

Nowadays most of the industries using artificial intelligence to improve their performance, Mainly in transportation, healthcare, finance, manufacturing, industries, Advertising. By using the AI in business we can increase the sales, identify the fraud attempts, improve customer satisfaction. We can increase the manufacturing output and efficiency, can improve the marketing and advertising also, at the same time by using AI in business we can save time and money by automating the process and can avoid the human error.

There are 4 kinds of AI is there

  • Reactive Machine
  • Limited memory
  • Theory of mind
  • Self-Awareness

Reactive Machine

There is a basic type of artificial intelligence. They do not store Memories. They do not use past experiences to determine future actions. They simply understand the world and according to that will react.

Limited Memory

It is mostly used in self-driving cars. They will detect the movement of vehicles around constantly, the static data such as lane marks, traffic signals, curves, humps in the road will be added to the artificial intelligence machine. It helps individual cars to avoid getting hit by a nearby vehicle.

Theory of Mind

Here machines should be thinking like a human brain. Will load all different kinds of human thinking ways. According to human thinking, the machine will be a response, but this is very difficult for how we (humans) formed society because they allowed us to have social interactions. If AI systems are true to walk among us. They will have to be able to understand that each of us has thoughts, feelings, and expectations for how we will be treated.

Self–Awareness

One of the pitfalls for machines becoming a self-awareness is that consciousness in humans is not well-defined enough, which would make it difficult if not impossible for programmers to replicate such a state in algorithms for AI.

Interview QA5

Interview QA5



Ques 1. what is the use of voltile qualifier?

If the variable is declared as volatile , the variable may updated by external program or hardware.
The volatile variable is not optimized by the compiler.
The volatile always read from memory instead of from registers.


Ques 2. what is the use of const keyword?
If the variable is declared as const. then the value of the varible would not be changed by the program.
it is not updated by the user.

const int MAX = 78;
const char STR[10] = "welcome";



Ques 3. what is the use of static variables?

If the variable is declared as static globally, then it is accessible only inside the file where it is declared.
we could not access outside the file.

If the local varible is declared as static inside the function then it is accessible inside the function only.
The varible is initialised only in first call to function. In the next call of the function static variable hold
the previous value will not initialise .

The static variable stored in memory.
The life of the variable is till the program is running.



Ques 4. write a c program to validate the user name and password?

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char username[4][20]={ "user1", "user2", "user3", "user4"};
    char password[4][20] = {"password123", "password456", "password678", "password567"};
    char usern[20], passwordn[20];
    int i=0, j=0, k=0, uname=0, passw=1;

    while(1)
    {
    printf("\n enter the username to login:");
        scanf("%s", usern);
    printf("\n enter the password to login:");
        scanf("%s", passwordn);

    for(i=0; i<4; i++)
    if(strcmp(username[i], usern) == 0)
    {
        uname=1;
            for(j=0; j<4; j++)
            if(strcmp(password[j], passwordn) == 0)
            {
                printf("\n both username and password correct.");
                passw=1;
                break;
            }

    }
    if(uname==0)
        printf("\n entered the wrong username");
    if(passw ==0)
        printf("\n entered the wrong password.");
    else
        break;
    k++;
    if(k==3)
    {
     printf("\n you are exceeded 3 chances to enter password and username.");
     break;
    }
    }
    return 0;
}
 


5. what is optimization in c program?

Optimization is the method of improving the code efficiency and quality.
c program can become less in size, occupies less memory space, speed execution is more. 

The methods of code optimization are:
1. Optimization in loops: 
1.1 unroll small loops: 
 	Instead of calculating and storeing the known constant values, we can directly calculate and initialise.

     factorial number calculation:

program1:
int main()
{
    int fct[6];
	int i;
        fct[0] =1;
	for(i=1; i<6; i++)
		{
		    fct[i] = fct[i-1] *i;		
		}
1, 2 6 24 120
    return 0;
}


program 2: modified program of program1
int main()
{
    int fct[6] = {1, 2, 6, 24, 120};

    return 0;
}

1.2. Avoid calculation in loops:
   we should avoid calculating the in loops which will give same value in all iterations.

example1:
int main()
{
    int x=3, y=4, z=6, m=4;
    int g[100], p;

    for(p=0; p<100; p++)
        g[p] = (x*y+z*m) * p;

    return 0;
}


optimized code of example1:
int main()
{
    int x=3, y=4, z=6, m=4;
    int g[100], p;

    int temp= (x*y+z*m);
    for(p=0; p<100; p++)
        g[p] =  temp* p;

    return 0;
}

1.3. Avoid pointer dereference in loop: 
   since it creates lots of work in memory to access the data each time, so dereference 
   before the loop using some temporary variable.

example1:
int main()
{
    int x=0, p;
    int *q=&x;

    for(p=0; p<100; p++)
        *q = *q+p;
    printf("\n %d ", *q);

    return 0;
}

optimized code of example1:

int main()
{
    int x=0, p;
    int *q=&x;
    int t=*q;

    for(p=0; p<100; p++)
        *q = *q+p;
    *q=t;
     printf("\n %d ", *q);

    return 0;
}

1.4. user register storage class for loop variables: it will increase the speed of accessing the variables.

example1:
int i, temp=0;
for(i=0; i<100; i++)
{
   temp= temp+i;
}

optimized code for example1:
int temp=0;
register int i=0;
for(i=0; i<100; i++)
{
   temp= temp+i;
}

2. Increasing Speed of mathemetical calculation:

2.1 avoid not required division operations, since division operation decreases the speed of execution.

	int x=2,y=3,z=4,m=5,n=6;
	x=y+z+(x/y/z/m)+n;

    we can make modify it as
        x = y+z+(x/(y*z*m)) + n ;  

2.2 Multiplication and Division by power of 2 : 
we can use << for multiplication by 2 and we can use >> for division by 2. 
These shift operations are faster than multiplication and division operation so we can 
use them. the compiler will optimize the code incase of complex expression code
it is advised to do bitshifting.

multiplying by 6 : m= (m<<1)+ (m<<2)
multiplying by 7: m= m<<3 - m
devide by 4      : m = m>>2

2.3 : simplying the complex code expression: 
by simplyfying the expression we can reduce the number of mathematical computations.

Ex:
     z=  a*b +a*b*c+ a*b*c*d 
     z= a*b*(c*(1+d))
here we reduced the 6 multiplication 3 addtion to 3 multiplication and 1 addition.

3 Optimizing the switch statements:

 In c switch statements if case labels are continuous then the compiler creates a jump table and it is faster.
 If it is not then it will creates a if else statements. Compiler will put the most frequent conditions first and
 rarely used at later. so keep the most used cases first and rarely used labels later.

 
ex1: 
 switch(exp)
{
case x:
        different expression
	break;
case y:
        different expression
	break;
case z:
	common statements1;
        different expression
	common statements2;
	break;
case m:
	common statements1;
        different expression
	common statements2;
	break;
case n:
        different expression
	break;
}

modified of example1 for code optimization:

 switch(exp)
{
case x:
        different expression
	break;
case y:
        different expression
	break;
case z:
case m:
common statements1;
switch(exp)
	{
        different expression
	break;
case m:
        different expression
	break;
}
	common statements2;
case n:
        different expression
	break;
}

4. prefer int instead of char or short:
 since the char are converted to int then do the calculation after doing the calculation
 it again converted to char.
 if it doing in a loop it affects lot on performance.

5. pre-increment is preferred than post -increment
  
In pre increment the value is just increment by 1 and copies the value to variable location. 
In post increment the value is copied to temporary variable then it inremented and then it copies the value to variable. 

6. order of expression evaluation:

   ex1 : A || B   Here if A is true then no need to check the B so first we have to keep the exprission most of the times evaluates to true.
   ex2 : A && B   Here if A is false then no need to check the B so first we have to keep the exprission most of the times evaluates to false.


6. can we pass structure be passed by value to a function?

yes, we can pass structure to function by value.

#inclue<stdio.h>
#include <stdlib.h >
struct s{
int d;
}s2;

fun(struct s s2)
{
printf("%d \n ", s2.d);
}

int main()
{
    s2.d=45;
fun(s2);
    return 0;
}


7. why cannot we pass arrays to function by value?
	since array have many elements so individual elements we can pass,
     but without the address we cannot access all the elements. so we cannot pass arrays by value to function.

8. difference between macro and inline funtion?

difference in evaluation:
  - the macro is replaced by it code during preprocessing
  - the inline function is parsed by the compiler.

 - In macro the expression passed as arguments are copied to the variables.
 - in inline the expression passed as arguments are evaluated then copied to variables.

#include

#define CUBE(M) M*M*M
inline int cube(int m)
{
	return m*m*m;
}

int main()
{
	printf(" %d",CUBE(1+2));
	printf(" %d",cube(1+2));
	return 0;
}

output:
7 27

for macro it become  1+2*1+2*1+2 = 1+2+2+2= 7
for inline function  3*3*3 = 27

- macro would not check the type of the arguments
- inline funtion check the type checking for arguments passed.

- macro always expanded by the preprocessor 
- inline function is depend on the compiler decesion to replace it by its code.



9. is the recursive function can be inline?

The compiler decides whether the declared function is inline or it can be treated as normal  function.
The recursive functions are treated as normal function by the compiler even though we declared it as inline.

#include <stdio.h>

int cnt=0;
inline int cube(int m)
{
    cnt++;
    if(cnt<=3)
        cube(m);
    else
    return m*m*m;
}

int main()
{
    int x;
    x=cube(2);
    printf("\n %d",x);
    return 0;
}


10. #define abc(x,y) x##y concatenates but abc( abc(x,y)) gives warning why?

abc(x,y) gives xy which substituted in the inside function .
For the outer function will get 1 argument instead of two , so it gives compiler error.



11. can we declare volatile variable?
 yes we can declare. the variable is constant for the program it is declared.
 but the external program or hardware can change it.

Interview Q & A 6

Interview Q & A 6



Ques 1. write a c program to print "Goodmorning" without using ; ?

ex1:
#include <stdio.h>
#include <stdlib.h>
int main()
{
if(printf("\n Goodmorning"))
}

ex2:
#include <stdio.h>
#include <stdlib.h>
int main()
{
while(!printf("\n Goodmorning")){}
}

ex3:
#include <stdio.h>
#include <stdlib.h>
int main()
{
switch(!printf("\n Goodmorning")){}
}


Ques 2. exchange / swap two numbers without using third variable?

program 1:

#include <stdio.h>
#include <stdlib.h>
int main()
{
 int m,n;
 m=2;
 n=5;
 m = m+n;
 n = m-n;
 m = m-n;
 printf("\n m =%d n=%d ", m,n);
    return 0;
}

program 2:
int main()
{
 int m,n;
 m=2;
 n=5;
 m = m+n-(n=m);

 printf("\n m =%d n=%d ", m,n);
    return 0;
}
program 3:
int main()
{
 int m,n;
 m=2;
 n=5;
 m=m^n;
 n=m^n;
 m=m^n;
 printf("\n m =%d n=%d ", m,n);
 return 0;
}
program 4:
int main()
{
 int m,n;
 m=2;
 n=5;
 m = m - ~n - 1;
 n = m + ~n + 1;
 m = m + ~n + 1;

 printf("\n m =%d n=%d ", m,n);
    return 0;
}




Ques 3. what is dangling pointer in c?

Initially a pointer has been pointing some variable location, later the pointer pointing to the memory location
is deleted. but the pointer still pointing to same memory location.
This pointer is called dangling pointer. the error is called dangling pointer error.

#include <stdio.h>
#include <stdlib.h>

int main()
{
 int m=34;
 int *p=(int*)malloc(4);
 *p=m;
 free(p);
 printf("\n m =%d ", *p);
    return 0;
}



Ques 4. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>
int * fun()
{
   int x=44;
    return &x;
}

int main()
{
 int m=34;
 int *p;
 p =fun();

 printf("\n m =%d ", *p);
 return 0;
}

Ans: runtime error/ garbage value prints, since the scope of the local variable 
x is only inside the function fun(), so we can get the address of this variable.
so this is called dangling pointer error.

solution: if we make x as static then it works.



Ques 5. what is wild pointer in c?

A pointer which is not initialised is called wild pointer, 
it returns the some random address and garbage value.

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int *p;

 printf("\n p =%u =%d", p,*p);
 return 0;
}

output:  it gives garbage value or prints nothing. NULL pointer means pointing to memory location 0, 
wild pointer means it pointing to some unknown location and gives some garbage value.



Ques 6. what is the advantage and disadvantage of arrays in c?

The advantage : once the array is declared the memory is allocated and we can access each element by using the array indexes.
                it can store elements of the same data type.
               we can declare array for different data types like int , float, struct, union.
               we can initialise the array while declaration.
		an array pointing to the address of the other elements is called pointer array.
disadvantage: if the array index goes out of boundary then there is a huge mistake, some wanted data will be 
              overwritten or the program may crash.
              if array size is more than the usable then the remaining memory is wasted.


array declaration example:
int arr[4];
char str[33];
short int sarr[34];
float fr[12];
int (*funptr[4])();
long *larr[21];
double **p[5];



Ques 7. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>

int main()
{
 double d1=33.44, d2=33.55, d3=66.78;
 double *dptr[3] ={&d1, &d2, &d3 };

 printf("\n %e", *dptr[0]);
 return 0;
}

ans : 3.344 e+001

Here dptr is a pointer array  it points to the elements d1,d2,d3.



Ques 8. explain about do while loop and write a program?
	do while loop we can use to execute the code in the loop before checking the condition.
	it executes the loop atleast one time.

#include <stdio.h>
#include <stdlib.h>
int main()
{
 int i;
 do {
    printf("\n this is do while loop");
 } while(i !=0);
 return 0;
}



Ques 9. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>
int i;
i=45;
main()
{
printf("\n %d", i);
return 0;
}

ans:
it gives compilation error, since assignment outside main function is not allowed.



Ques 10. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>
static int i=10;
int main()
{
for(i=0; i<5; i++)
{
    static int a=3;
    printf("%d ", a++);
}
 return 0;
}

ouput : 3 4 5 6 7

static variable initialises only once, so the variable a prints 3,4,5,6,7



Ques 11. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>

static int i=10;
int main()
{
{
    static int a=3;
    printf("%d ", a++);
}
    printf("%d ", a);
 return 0;
}

output:
it gives compiler error because the static variable declared within the block is local to the block.
we cannot access outside of it.



Ques 12. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>
static int a=10;
void fun();
int main()
{

   printf("%d ", a++);
   printf("\nmain b= %d",b);
 return 0;
}
int b=323;
void fun()
{
printf("\n b= %d",b);
}

output: compiler error since the global variable b has to be declared above the main function.



Ques 13. what is the output for the below code in two different files file1.c and file2.c?

//file1.c

#include <stdio.h>
#include <stdlib.h>
extern int sum();
static int i=3, j=5;
int main()
{
    int p;
    p=sum();
    printf("%d ", p);
    return 0;
}

//file2.c

#include <stdio.h>
#include <stdlib.h>
extern int sum();
static int i=3, j=5;
int main()
{
    int p;
    p=sum();
    printf("%d ", p);
    return 0;
}

output:
It gives compiler error, since the global static variables declared i,j are only accessed in file1.c file, 
we cannot access it in file2.c file.
global static variables declared accessed only in the file where they are declared.



Ques 14. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>
int main()
{
int k=0;
{
   static int p=5;

PRINT:
    printf(" %d", p);
    p++;
    k++;
}
    if(k<4)
        goto PRINT;
    return 0;
}

output|: 5 6 7 8

The life of static varible still exists the control come out and go inside the block.



Ques 15. what tells the prototype of a function ?

prototype of a function is declaration of a function.
it tells the return type of the function,
it tells the input arguments the function takes.
it tells the function name

ex:
int fun(float, char);


Ques 16. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>
int main()
{
const int k=20;
int *p;
p=&k;
*p=34;

printf("%d", *p);
    return 0;
}

output: 34
we can modify the constant variables in c using pointers.



Ques 17. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>

int search(char);
int (*fun())(char c);

int main()
{
    int m=0;
    int (*p)(char);
    p=fun();
    m=(*p)('h');
    printf("%d", m);
    return 0;
}

int search(char d)
{
    return d;
}

int (*fun())(char g)
{
    return search;
}


output:
104

p=fun()
m=(*p)('h')
m=(*fun())('h') // since p=fun();
m= (*&search())('h')  // since fun returns &search
m= search('h')
m=104.



Test your C skills

Interview Q & A 4



Ques 1. what happens for the below code since the array subscrit is more
 than the size of the array?

#include <stdio.h>
#include <stdlib.h>
int main()
{
	int arr[3] ={3,4,5};
	arr[5]=4343;
}

options:
A. The arr[5] hold the value no issue.
B. Some valid data will be overwritten and the program may crash.
C. compiler error
D. the array size increases


Ques 2. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int m=1, n=1;
    for(; m; printf("%d %d\n", m++, n), m=n++<=2);   

    return 0;
}

options:
A. 1 1 1 2 1 3
B. 1 1 2 2 3 3
C. 2 1 3 2 4 2
D. 1 1 0 2 0 3
 

Ques 3. which of the below options is correct about the uart communication?

options:
A. Uart reads the buffer register and transmit data in parallel.
B. Transmit data in buffer register, UART adds start bit, parity, stop bits to the data, then tranmit data in parallel.
C. Transmit data in buffer register, UART adds start bit, parity, stop bits to the data, then tranmit data in parallel.
D. Transmit data in buffer register, UART adds start bit, parity, stop bits to the data, then tranmit serially.


Ques 4. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
    enum color{red, green, blue}s;
    printf("%d\n",sizeof(s));
    return 0;
}

options:
A. 2
B. 4
C. 1
D. 8


Ques 5. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int x=1, y=3, z=8, m=0, n=2;
    x = (x || (y=z)) && (m || (y=n));
    printf("%d %d %d %d %d",x,y,z,m,n);

    return 0;
}

options:
A. 1 2 0 8 2 
B. 1 0 2 2 8
C. 1 2 8 0 2
D. 0 2 2 1 8


Ques 6. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>
int add( int x, int y)
{
    return x+y;
}

int sub( int x, int y)
{
    return x-y;
}

int mul( int x, int y)
{
    return x*y;
}

int divide( int m, int n)
{
    return m/n;
}

int (*f[4])(int x, int y)={add, sub, mul,divide};

int main()
{
 int x=3, y=2, i;

 for(i=0; i<=3; i++)
    printf("%d ", (*f[i])(x, y));

    return 0;
}


options:
A. compiler error
B. 5 1 6 1
C. runtime error
D. 5 1 6 1.5


Ques 7. what are the features of the function?

  - code is more readable.
  - testing the code is easier
  - recursive call can be done for functions
  - each functionality can be kept seperately


Ques 8. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>

int * fun();

int main() {
      int *q;
      q=fun();
      printf("%d",*q);
      return 0;
    }

int * fun() {
      int g=25;
      g--;
      g--;
      return &g;
      }

options:
A. 23
B. 25
C. compiler error
D. runtime error


Ques 9. How the build process happens in c program?

options:
A. Preprocessing, compilation, linking
B. compilation, Preprocessing, linking
C. linking, Preprocessing , compilation
D. none of the above


Ques 10. when we found the undefined function error while building the c program?

options:
A. linking
B. preprocessing
C. compilation
D. none of the above


Ques 11. using volatile keyword for the below code is valid ?

#include <stdio.h>
#include <stdlib.h>
volatile int m=3;
    int main() {
      int h=3,i;
      for(i=0; i<5; i++)
        h=m;
      return 0;
    }

options:
A. since it is in loop not valid
B. it is valid the value of m may change
C. it gives compiler error
D. none of the above


Ques 12. if one wants to transmit data to 4 receivers within the distance of 50 feet with a speed of 6mbs
so which protocol is suitable for this?

options:
A. rs232
B. rs245
C. rs422
D. rs485


Ques 13. which of the following is correct?

options:
A. SPI speed is lesser than I2C and UART
B. SPI uses the chip select signals to select the slaves
C. Multi master is possible in SPI communication
D. SPI will communicate with one slave



Answers

1. B 2. A 3. D 4. B 5. C 6. B 8. D 9. A 10. A 11. B 12. C 13. B

En-Query

Your Name*
Subject*
Phone Number*
Email Address*

Message*