Tuesday 21 April 2020

Interfacing LED with Arduino

Aim:

Light Emitting Diodes (LED) is the most commonly used components, usually for displaying pins digital states. Typical uses of LEDs include alarm devices, timers and confirmation of user input such as a mouse click or keystroke. The main aim of this project is how to interface a single LED to arduino.
images (1)

Description:

Interfacing LED:
Fig. 1 shows how to interface the LED to microcontroller. As you can see the Cathode is connected through a resistor to GND & the Anoode is connected to the Microcontroller pin. So when the Port Pin is HIGH the LED is ON & when the Port Pin is LOW the LED is turned OFF.
intetrface led
Interfacing LED with Arduino

We now want to flash a LED in arduino board. It works by turning ON a LED & then turning it OFF & then looping back to START. However the operating speed of microcontroller is very high so the flashing frequency will also be very fast to be detected by human eye.

Block Diagram
1. interfacing single led

Schematic:

Code:

// ***********************************************************
// Project: Interfacing Single LED to Arduino
// Author: Hack Projects
// Module description: Operate single LED
// ***********************************************************
const int LED = 13; 
void setup()
{
  pinMode(LED,OUTPUT);
}
void loop()
{
  digitalWrite(LED,HIGH);
  delay(1000);
  digitalWrite(LED,LOW);
  delay(1000);
}

Downloads:

The code was compiled in Atmel Studio 6 and simulation was made in Proteus v7.7.
To download code and proteus simulation click here.


Further Reading suggestions:


You may also like,
  • Interfacing keypad with Arduino
  • nterfacing DAC with Arduino
  • Interfacing with UART of Arduino controller
  • Interfacing SPI communication with Arduino
  • Arduino Displaying Custom Characters on LCD 
  • Arduino Graphical LCD
  • RTC interfacing using I2C in Arduino
  • Interfacing ultrasonic sensor with Arduino
  • Interfacing GPS Modu with Arduino
  • Interfacing GSM Module with Arduino
  • Interfacing PWM in Arduino
  • Interfacing ADC with Arduino
  • Scrolling string on LCD using Arduino

Monday 9 December 2019

C Interview Questions Set-5


21. How can I open a file so that other programs can update it at the same time?

Your C compiler library contains a low-level file function called sopen() that can be used to open a file in shared mode. Beginning with DOS 3.0, files could be opened in shared mode by loading a special program named SHARE.EXE. Shared mode, as the name implies, allows a file to be shared with other programs as well as your own. 
Using this function, you can allow other programs that are running to update the same file you are updating. 
The sopen() function takes four parameters: a pointer to the filename you want to open, the operational mode you want to open the file in, the file sharing mode to use, and, if you are creating a file, the mode to create the file in. The second parameter of the sopen() function, usually referred to as the operation flag parameter, can have the following values assigned to it: 
Constant Description O_APPEND Appends all writes to the end of the file 
O_BINARY Opens the file in binary (untranslated) mode
O_CREAT If the file does not exist, it is created
O_EXCL If the O_CREAT flag is used and the file exists, returns an error
O_RDONLY Opens the file in read-only mode
O_RDWR Opens the file for reading and writing
O_TEXT Opens the file in text (translated) mode
O_TRUNC Opens an existing file and writes over its contents
O_WRONLY Opens the file in write-only mode
The third parameter of the sopen() function, usually referred to as the sharing flag, can have the following values assigned to it:
Constant Description
SH_COMPAT No other program can access the file
SH_DENYRW No other program can read from or write to the file
SH_DENYWR No other program can write to the file
SH_DENYRD No other program can read from the file
SH_DENYNO Any program can read from or write to the file

If the sopen() function is successful, it returns a non-negative number that is the file’s handle. If an error occurs, 1 is returned, and the global variable errno is set to one of the following values:
Constant Description
ENOENT File or path not found
EMFILE No more file handles are available
EACCES Permission denied to access file
EINVACC Invalid access code
Constant Description

22. How can method defined in multiple base classes with same name can be invoked from derived class simultaneously

ex:

class x
{
public:
m1();

};

class y
{
public:
m1();

};

class z :public x, public y
{
public:
m1()
{
x::m1();
y::m1();
}

};


23. Write a program to interchange 2 variables without using the third one

a=7;
b=2;
a = a + b;
b = a - b;
a = a - b;


24. What is the result of using Option Explicit?

When writing your C program, you can include files in two ways.
The first way is to surround the file you want to include with the angled brackets < and >.
This method of inclusion tells the preprocessor to look for the file in the predefined default location.
This predefined default location is often an INCLUDE environment variable that denotes the path to your include files.
For instance, given the INCLUDE variable
INCLUDE=C:\COMPILER\INCLUDE;S:\SOURCE\HEADERS;
using the #include version of file inclusion, the compiler first checks the
C:\COMPILER\INCLUDE
directory for the specified file. If the file is not found there, the compiler then checks the
S:\SOURCE\HEADERS directory. If the file is still not found, the preprocessor checks the current directory.
The second way to include files is to surround the file you want to include with double quotation marks. This method of inclusion tells the preprocessor to look for the file in the current directory first, then look for it in the predefined locations you have set up. Using the #include file version of file inclusion and applying it to the preceding example, the preprocessor first checks the current directory for the specified file. If the file is not found in the current directory, the C:COMPILERINCLUDE directory is searched. If the file is still not found, the preprocessor checks the S:SOURCEHEADERS directory.
The #include method of file inclusion is often used to include standard headers such as stdio.h or
stdlib.h.
This is because these headers are rarely (if ever) modified, and they should always be read from your compiler’s standard include file directory.
The #include file method of file inclusion is often used to include nonstandard header files that you have created for use in your program. This is because these headers are often modified in the current directory, and you will want the preprocessor to use your newly modified version of the header rather than the older, unmodified version.

25. What is the benefit of using an enum rather than a #define constant?

The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.
1) The first advantage is that enumerated constants are generated automatically by the compiler. Conversely, symbolic constants must be manually assigned values by the programmer.
For instance, if you had an enumerated constant type for error codes that could occur in your program, your enum definition could look something like this:
enum Error_Code
{
OUT_OF_MEMORY,
INSUFFICIENT_DISK_SPACE,
LOGIC_ERROR,
FILE_NOT_FOUND
};
In the preceding example, OUT_OF_MEMORY is automatically assigned the value of 0 (zero) by the compiler because it appears first in the definition. The compiler then continues to automatically assign numbers to the enumerated constants, making INSUFFICIENT_DISK_SPACE equal to 1, LOGIC_ERROR equal to 2, and FILE_NOT_FOUND equal to 3, so on.
If you were to approach the same example by using symbolic constants, your code would look something like this:
#define OUT_OF_MEMORY 0
#define INSUFFICIENT_DISK_SPACE 1
#define LOGIC_ERROR 2
#define FILE_NOT_FOUND 3
values by the programmer. Each of the two methods arrives at the same result: four constants assigned numeric values to represent error codes. Consider the maintenance required, however, if you were to add two constants to represent the error codes DRIVE_NOT_READY and CORRUPT_FILE. Using the enumeration constant method, you simply would put these two constants anywhere in the enum definition. The compiler would generate two unique values for these constants. Using the symbolic constant method, you would have to manually assign two new numbers to these constants. Additionally, you would want to ensure that the numbers you assign to these constants are unique.
2) Another advantage of using the enumeration constant method is that your programs are more readable and thus can be understood better by others who might have to update your program later.

3) A third advantage to using enumeration constants is that some symbolic debuggers can print the value of an enumeration constant. Conversely, most symbolic debuggers cannot print the value of a symbolic constant. This can be an enormous help in debugging your program, because if your program is stopped at a line that uses an enum, you can simply inspect that constant and instantly know its value. On the other hand, because most debuggers cannot print #define values, you would most likely have to search for that value by manually looking it up in a header file.



Monday 24 September 2018

C Interview Questions Set-4


16. What are the different storage classes in C?

C has three types of storage: automatic, static and allocated. Variable having block scope and without static specifier have automatic storage duration.

Variables with block scope, and with static specifier have static scope.

Global variables (i.e, file scope) with or without the static specifier also have static scope.

Memory obtained from calls to malloc(), alloc() or realloc() belongs to allocated storage class.

17. What is the difference between strings and character arrays?

A major difference is: string will have static storage duration, whereas as a character array will not, unless it is explicity specified by using the static keyword. Actually, a string is a character array with following properties:

* the multibyte character sequence, to which we generally call string, is used to initialize an array of static storage duration. The size of this array is just sufficient to contain these characters plus the terminating NULL character.

* it not specified what happens if this array, i.e., string, is modified.

* Two strings of same value[1] may share same memory area. For example, in the following declarations:

char *s1 = “Calvin and Hobbes”;
char *s2 = “Calvin and Hobbes”;

The strings pointed by s1 and s2 may reside in the same memory location. But, it is not true for the following:

char ca1[] = “Calvin and Hobbes”;
char ca2[] = “Calvin and Hobbes”;

[1] The value of a string is the sequence of the values of the contained characters, in order.

18. What is the difference between const char* p and char const* p?

In const char* p, the character pointed by ‘p’ is constant, so u cant change the value of character pointed by p but u can make ‘p’ refer to some other location.

In char const* p, the ptr ‘p’ is constant not the character referenced by it, so u cant make ‘p’ to reference to any other location but u can change the value of the char pointed by ‘p’.

19. What is hashing?

To hash means to grind up, and that’s essentially what hashing is all about. The heart of a hashing algorithm is a hash function that takes your nice, neat data and grinds it into some random-looking integer.

The idea behind hashing is that some data either has no inherent ordering (such as images) or is expensive to compare (such as images). If the data has no inherent ordering, you can’t perform comparison searches.

If the data is expensive to compare, the number of comparisons used even by a binary search might be too many. So instead of looking at the data themselves, you’ll condense 

(hash) the data to an integer (its hash value) and keep all the data with the same hash value in the same place. This task is carried out by using the hash value as an index into an array.

To search for an item, you simply hash it and look at all the data whose hash values match that of the data you’re looking for. This technique greatly lessens the number of items you have to look at. If the parameters are set up with care and enough storage is available for the hash table, the number of comparisons needed to find an item can be made arbitrarily close to one.

One aspect that affects the efficiency of a hashing implementation is the hash function itself. It should ideally distribute data randomly throughout the entire hash table, to reduce the likelihood of collisions. Collisions occur when two different keys have the same hash value. 

There are two ways to resolve this problem. In open addressing, the collision is resolved by the choosing of another position in the hash table for the element inserted later. When the hash table is searched, if the entry is not found at its hashed position in the table, the search continues checking until either the element is found or an empty position in the table is found.

The second method of resolving a hash collision is called chaining. In this method, a bucket or linked list holds all the elements whose keys hash to the same value. When the hash table is searched, the list must be searched linearly.

20. How can you determine the size of an allocated portion of memory?

You can’t, really. free() can , but there’s no way for your program to know the trick free() uses. Even if you disassemble the library and discover the trick, there’s no guarantee the trick won’t change with the next release of the compiler.

Wednesday 1 August 2018

C Interview Questions Set-3


11. What is C standard?
The latest C standard is ISO/IEC 9899:2011, also known as C11 as the final draft was published in 2011. Before C11, there was C99. The C11 final draft is available here. See this for complete history of C standards.

12. What is the output of the following program? Why?


#include<stdio.h>
main() {
typedef union {
int a;
char b[10];
float c;
}
Union;
Union x,y = {100};
x.a = 50;
strcpy(x.b,"hello");
x.c = 21.50;
printf("Union x : %d %s %f n",x.a,x.b,x.c);
printf("Union y : %d %s %f n",y.a,y.b,y.c);
}


13. What does static variable mean?

There are 3 main uses for the static.

1. If you declare within a function:
It retains the value between function calls

2.If it is declared for a function name:
By default function is extern..so it will be visible from other files if the function declaration is as static..it is invisible for the outer files

3. Static for global variables:
By default we can use the global variables from outside files If it is static global..that variable is limited to with in the file 

14. What are the advantages of a macro over a function?

Macro gets to see the Compilation environment, so it can expand __ __TIME__ __FILE__ #defines. It is expanded by the preprocessor.

For example, you can’t do this without macros
#define PRINT(EXPR) printf( #EXPR “=%d\n”, EXPR)

PRINT( 5+6*7 ) // expands into printf(”5+6*7=%d”, 5+6*7 );

You can define your mini language with macros:
#define strequal(A,B) (!strcmp(A,B))

Macros are a necessary evils of life. The purists don’t like them, but without it no real work gets done.

15. What are the differences between malloc() and calloc()?

There are 2 differences.

First, is in the number of arguments. malloc() takes a single argument(memory required in bytes), while calloc() needs 2 arguments(number of variables to allocate memory, size in bytes of a single variable).

Secondly, malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.

Friday 27 July 2018

C Interview Questions Set-2


6. What is the output of printf("%d")?

A. When we write printf("%d",x); this means compiler will print the value of x. But as here, there is nothing after %d so compiler will show in output window garbage value.

B. When we use %d the compiler internally uses it to access the argument in the stack (argument stack). Ideally compiler determines the offset of the data variable depending on 

the format specification string. Now when we write printf("%d",a) then compiler first accesses the top most element in the argument stack of the printf which is %d and depending on the format string it calculated to offset to the actual data variable in the memory which is to be printed. Now when only %d will be present in the printf then compiler will calculate the correct offset (which will be the offset to access the integer variable) but as the actual data object is to be printed is not present at that memory location so it will print whatever will be the contents of that memory location.

C. Some compilers check the format string and will generate an error without the proper number and type of arguments for things like printf(...) and scanf(...).

7. What is the difference between "calloc(...)" and "malloc(...)"?

1. calloc(...) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0. The total number of memory allocated will be (number_of_elements * size).

malloc(...) takes in only a single argument which is the memory required in bytes. malloc(...) allocated bytes of memory and not blocks of memory like calloc(...).

2. malloc(...) allocates memory blocks and returns a void pointer to the allocated space, or NULL if there is insufficient memory available.

calloc(...) allocates an array in memory with elements initialized to 0 and returns a pointer to the allocated space. calloc(...) calls malloc(...) in order to use the C++ set_new_mode function to set the new handler mode.

8. What is the difference between "printf(...)" and "sprintf(...)"?

sprintf(...) writes data to the character array whereas printf(...) writes data to the standard output device.

9. How to reduce a final size of executable?

Size of the final executable can be reduced using dynamic linking for libraries.

10. Can you tell me how to check whether a linked list is circular?

Create two pointers, and set both to the start of the list. Update each as follows:
while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next;
if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print ("circular");
}}


If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, its either 1 or 2 jumps until they meet.

Monday 23 July 2018

C Interview Questions Set-1

1. What is the difference between declaration and definition of a variable/function

Ans: 
Most of the time, when you declare a variable, you are also providing the definition. What does it mean to define a variable, exactly? It means you are telling the compiler where to create the storage for that variable. For example, if you write:
int x;
int main()
{
    x = 3;
}

The line int x; both declares and defines the variable; it effectively says, "create a variable named x, of type int. Also, the storage for the variable is that it is a global variable defined in the object file associated with this source file." That's kind of weird, isn't it? What is going on is that someone else could actually write a second source file that has this code:

extern int x;
int func()
{
    x = 3;
}

Now the use of extern is creating a declaration of a variable but NOT defining it; it is saying that the storage for the variable is somewhere else. Technically, you could even write code like this:

extern int x;
int func()
{
    x = 3;
}

int x;
And now you have a declaration of x at the top of the program and a definition at the bottom. But usually extern is used when you want to access a global variable declared in another source file, as I showed above, and then link the two resulting object files together after compilation. Using extern to declare a global variable is pretty much the same thing as using a function declaration to declare a function in a header file. (In fact, you'd generally put extern in a header file rather than putting it in a source file.)
In fact, if you put a variable into a header file and do not use extern, you will run into the inverse problem of an undefined symbol; you will have a symbol with multiple definitions, with an error like "redefinition of 'foo'". This will happen when the linker goes to link together multiple object files.

2. What are different storage class specifiers in C?

Ans: 
There are four storage classes in C they are as follows:
  1. Automatic Storage Class
  2. Register Storage Class
  3. Static Storage Class
  4. External Storage Class
Now, let us discuss these storage classes one by one.

1. Automatic Storage Class

A variable defined within a function or block with auto specifier belongs to automatic storage class. All variables defined within a function or block by default belong to automatic storage class if no storage class is mentioned. Variables having automatic storage class are local to the block which they are defined in, and get destroyed on exit from the block.
The following C program demonstrates the visibility level of auto variables.
#include <stdio.h>
int main( )
{
  auto int i = 1;
  {
    auto int i = 2;
    {
      auto int i = 3;
      printf ( "\n%d ", i);
    }
    printf ( "%d ", i);
  }
  printf( "%d\n", i);
}
 
OUTPUT
======
3 2 1

In above example program you see three definitions for variable i. Here, you may be thinking if there could be more than one variable with the same name. Yes, there could be if these variables are defined in different blocks. So, there will be no error here and the program will compile and execute successfully. The printf in the inner most block will print 3 and the variable i defined in the inner most block gets destroyed as soon as control exits from the block. Now control comes to the second outer block and prints 2 then comes to the outer block and prints 1. Here, note that automatic variables must always be initialized properly, otherwise you are likely to get unexpected results because automatic variables are not given any initial value by the compiler.

2. Register Storage Class

The register specifier declares a variable of register storage class. Variables belonging to register storage class are local to the block which they are defined in, and get destroyed on exit from the block. A registerdeclaration is equivalent to an auto declaration, but hints that the declared variable will be accessed frequently; therefore they are placed in CPU registers, not in memory. Only a few variables are actually placed into registers, and only certain types are eligible; the restrictions are implementation-dependent. However, if a variable is declared register, the unary & (address of) operator may not be applied to it, explicitly or implicitly. Register variables are also given no initial value by the compiler.
The following piece of code is trying to get the address of variable i into pointer variable p but it won't succeed because i is declared register; therefore following piece of code won't compile and exit with error "error: address of register variable requested".
#include <stdio.h>
 
int main()
{
  register int i = 10;
  int *p = &i; //error: address of register variable requested
 
  printf("Value of i: %d", *p);
  printf("Address of i: %u", p);
 
}

3. Static Storage Class

The static specifier gives the declared variable static storage class. Static variables can be used within function or file.Unlike global variables, static variables are not visible outside their function or file, but they maintain their values between calls. The static specifier has different effects upon local and global variables. See the following flavours of static specifier.
  • When static specifier is applied to a local variable inside a function or block, the compiler creates permanent storage for it, much as it creates storage for a global variable but static local variable remains visible only to the function or block in which it is defined. In simple terms, a static local variable is a local variable that retains its value between function calls. For example, the following program code defines static variable i at two places in two blocks inside function staticDemo(). Function staticDemo() is called twice within from main function. During second call static variables retain their old values and they are not initialized again in second call of staticDemo().
  • #include <stdio.h>
     
    void staticDemo()
    {
      static int i;
      {
        static int i = 1;
        printf("%d ", i);
        i++;
      }
      printf("%d\n", i);
      i++;
    }
     
    int main()
    {
      staticDemo();
      staticDemo();
    }
    OUTPUT
    ======
    1 0
    2 1
  • When static specifier is applied to a global variable or a function then compiler makes that variable or function known only to the file in which it is defined. A static global variable has internal linkage that means even though the variable is global; routines in other files have no knowledge of it and cannot access and alter its contents directly. The following C program defines one static global variable gInt and a static function staticDemo(), for the variable and function are defined static they cannot be used outside the file (translation unit) staticdemo.c..
  • /* staticdemo.c */
    #include <stdio.h>
    static int gInt = 1;
    static void staticDemo()
    {
      static int i;
      printf("%d ", i);
      i++;
      printf("%d\n", gInt);
      gInt++;
    }
     
    int main()
    {
      staticDemo();
      staticDemo();
    }
    OUTPUT
    ======
    0 1
    1 2


Static variables have default initial value zero and initialized only once in their lifetime.

4. External Storage Class

The extern specifier gives the declared variable external storage class. The principal use of extern is to specify that a variable is declared with external linkageelsewhere in the program. To understand why this is important, it is necessary to understand the difference between a declaration and a definition. A declaration declares the name and type of a variable or function. A definition causes storage to be allocated for the variable or the body of the function to be defined. The same variable or function may have many declarations, but there can be only one definition for that variable or function.
When extern specifier is used with a variable declaration then no storage is allocated to that variable and it is assumed that the variable has already been defined elsewhere in the program. When we use extern specifier the variable cannot be initialized because with extern specifier variable is declared, not defined.
In the following sample C program if you remove extern int x; you will get an error "Undeclared identifier 'x'" because variable x is defined later than it has been used in printf. In this example, the extern specifier tells the compiler that variable x has already been defined and it is declared here for compiler's information.
#include <stdio.h>
 
extern int x;
 
int main()
{
  printf("x: %d\n", x);
}
 
int x = 10;
Also, if you change the statement extern int x; to extern int x = 50; you will again get an error "Redefinition of 'x'" because with extern specifier the variable cannot be initialized, if it is defined elsewhere. If not then extern declaration becomes a definition.
Note that extern can also be applied to a function declaration, but doing so is redundant because all function declarations are implicitly extern.

3. What is scope of a variable? How are variables are scoped in C?


A scope is a region of a program. Variable Scope is a region in a program where a variable is declared and used. So, we can have three types of scopes depending on the region where these are declared and used – 

  1. Local variables are defined inside a function or a block
  2. Global variables are outside all functions
  3. Formal parameters are defined in function parameters

Local Variables


Variables that are declared inside a function or a block are called local variables and are said to have local scope. These local variables can only be used within the function or block in which these are declared. We can use (or access) a local variable only in the block or function in which it is declared. It is invalid outside it.
Local variables are created when the control reaches the block or function containg the local variables and then they get destroyed after that.
#include <stdio.h>

void fun1()
{
    /*local variable of function fun1*/
    int x = 4;
    printf("%d\n",x);
}

int main()
{
    /*local variable of function main*/
    int x = 10;
    {
        /*local variable of this block*/
        int x = 5;
        printf("%d\n",x);
    }
    printf("%d\n",x);
    fun1();
}
Output
5
10
4
The value of the variable ‘x’ is 5 in the block of code ({ }) defined inside the function ‘main’ and the value of this variable ‘x’ in the ‘main’ function outside this block of code ({ }) is 10. The value of this variable ‘x’ is 4 in the function ‘fun1’.

Global Variables


Variables that are defined outside of all the functions and are accessible throughout the program are global variables and are said to have global scope. Once declared, these can be accessed and modified by any function in the program. We can have the same name for a local and a global variable but the local variable gets priority inside a function.
#include <stdio.h>

/*Global variable*/
int x = 10;

void fun1()
{
    /*local variable of same name*/
    int x = 5;
    printf("%d\n",x);
}

int main()
{
    printf("%d\n",x);
    fun1();
}
Output
10
5
You can see that the value of the local variable ‘x’ was given priority inside the function ‘fun1’ over the global variable have the same name ‘x’.

Formal Parameters


Formal Parameters are the parameters which are used inside the body of a function. Formal parameters are treated as local variables in that function and get a priority over the global variables.
#include <stdio.h>

/*Global variable*/
int x = 10;

void fun1(int x)
{
    /*x is a formal parameter*/
    printf("%d\n",x);
}

int main()
{
    fun1(5);
}
Output
5

4.How to print "Hello World" without semicolon?

int main(void)
{
    if (printf("Hello World")){}
}