Wednesday, June 27, 2012

AVR Tutorial - 2. Introduction to Programming in C


1.                  Into to Programming in C
C programming Language was introduced in the year of 1972 by Dennis Ritchie of AT&T Bell Laboratories. Let’s start our first program, the traditional Hello World!.. Program

/*Program to Print Hello World*/
#include<stdio.h>

void main( )
{
            printf(“Hello World!..”);

}

·      Here the things given inside /*     */ are called comments which will be ignored by the compiler during compilation time
·      When we write the pre-processor directive #include<stdio.h> our pre-processor will also include the header file stdio.h which contains the defenitions for standard input output functions. So if we include stdio.h in our program, we will be able to use those standard functions in our program. Similary there are also many standard and userdefined header files and if we include them in our program we will be able to use the functions defined int that in our program.
·      Every C program starts its execution from main( ) function and we do call other userdefined or standard library functions inside our main( ) function. We do write all our programs also inside the main( )
·      Every C Statements terminates with a semicolon ‘ ; ‘
·      printf( ) is the standard library function we use to print something into the console.


Declaring Variable
·      Variables are the programming elements which we refer to store some data in the Main Memory.
·      The basic syntax for declaring and initializing variable is:

<data type> variable_name [= <value>];
Eg:  int myVar = 5;
        char character;
       character = ‘A’;
       float x = 11.234;

Basic Data Types
·         int is used to define integer numbers.
Eg :int x =6;
·         float is used to define floating point numbers.
Eg: float y = 3.231;
·         double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes.
Eg: double z = 234.2376546;
·         char defines characters and they are usually enclosed in a single quotes and they could hold onle a single character values.
Eg: char newChar = ‘A’;
            For storing strings, we use array of characters and they are being terminated by null character ‘\0’.
Eg: char name = {‘R’, ‘a’, ‘m’, ‘\0’};
Eg:
/*Program to Print Hello World*/
#include<stdio.h>

void main( )
{
            int x, y, sum;
printf(“Enter two numbers : ”);
            scanf(“%d %d”, &x, &y);
            sum = x + y;
            printf(“Sum is %d”, sum);

}

Basic Operators in C:
i.                    Arithmetic Operators
Operator
Description
Example
+
Adds two operands
A + B will give 30
-
Subtracts second operand from the first
A - B will give -10
*
Multiply both operands
A * B will give 200
/
Divide numerator by denumerator
B / A will give 2
%
Modulus Operator and remainder of after an integer division
B % A will give 0
++
Increment operator, increases integer value by one
A++ will give 11
--
Decrement operator, decreases integer value by one
A-- will give 9

ii.                  Logical / Relational Operators:
Operator
Description
Example
==
Checks if the value of two operands is equal or not, if yes then condition becomes true.
(A == B) is not true.
!=
Checks if the value of two operands is equal or not, if values are not equal then condition becomes true.
(A != B) is true.
> 
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
< 
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.
&&
Called Logical AND operator. If both the operands are non-zero then then condition becomes true.
(A && B) is true.
||
Called Logical OR Operator. If any of the two operands is non-zero then then condition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is false.

iii.                Logical Operators
A logical operator operated between two relational or logical expressions and returns a logical value.

&& - Logical AND
||    - Logical OR
!     - Logical Negation / NOT
iv.                Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100 – Bitwise ANDing
A|B = 0011 1101 – Bitwise ORing
A^B = 0011 0001 – Bitwise XORing
~A  = 1100 0011 – Bitwise Negation operator
<<    - Left shift operator
>>    - Right Shift Operator
NB: Please make yourself very clear about bitwise operators as we use them much frequently while programming the microcontrollers.
·          sizeof( ) – operator is used to get the size (in bytes) which a variable or a data type takes in memory.



Control Structures:
a.     Sequential Control Structure
Eg: Usual programs in which we execute statements one after the other.
b.     Selection Control Structure
If statements in which a condition is being checked and if it is true certain set of statements will get executed.
i.              Simple if statement:
if(condition)
{
            --Statements--
}
ii.             If –Else Statements
if(condition)
{
            --Statements--
}
else
{
            --Statements--
}



iii.            If-Else-If Ladder
if(condition1)
{
            --Statements--
}
else if(condition2)
{
            --Statements--
}
else
{
            --Statements--
}
iv.            Switch Statements
switch(expression)
{
            case const1: --Statements—
                              break;
case const2: --Statements—
                              break;
case const3: --Statements—
                              break;

default: --Statements—
                              break;

}
c.     Iteration / Looping :
i.              For Loop

for(initialisation;  condition ; updation)
{
            --Loop Body--
}
Eg:
for(int i = i; i<=10 ; i++)
{    /*Printing Multiplication Table of 5 */
            printf(“%d x 5 = %d”, i, i*5);
}
ii.             While Loop – Loop Body will get executed till the condition goes false
while(condition)
{
            --Loop Body --
}
iii.            Do-While Loop : It is an exit controlled loop, ie. The loop body is executed at least once even if the condition is always being false.
do
{
            --Loop Body --
} while (condition);
Break statement:
            If we place a break statement inside a loop after checking a condition and if it goes right, the control will come out of the loop.
Eg:
for(int i = i; i<=10 ; i++)
{    /*Printing Multiplication Table of 5 */
            printf(“%d x 5 = %d”, i, i*5);
            if(i == 5)
                break;
}
/*Here the loop will print only till 25 and later on i becomes 5 and it breaks the loop*/
Continue Statement:
If we place a continue statement inside a loop after checking a condition and if it goes right, the control leave rest of the loop body, update the loop variable and then continue the loop
for(int i = i; i<=10 ; i++)
{    /*Printing Multiplication Table of 5 */
            printf(“%d x 5 = %d”, i, i*5);
            if(i == 5)
                break;
}/*Here the loop will not print 5*5 */

Functions
            Functions are one of the most commonly used features in the C Programming language. It helps users to separate blocks of codes which could be reused again and again.
A program using functions may look something like this:
#include<stdio.h>
int myFunction(int , int);
void main( )
{
            ---------
            ---------
}

int myFunction(int x, int y)
{
            int z;
            z = (x+y)*x;
            return z;
}

·         Here the line  int myFunction(int , int); is called function prototyping or declaration where we do tells the compiler that a function with a name myFunction exists and it takes two integer arguments. We need to add this if we define the function just after the main( )
·         After the main we have defined the function myFunction and we have given the function body.
·         The general syntax of defining a function is:
<return-type> <function-name>(<parameter-list>)
{
            --Function Body--
}
·         Return-type is the data type of value returned by a function to the called program.
·         If a function does not return a value, we do give its return type as void.

Example for functions:
int factorial(int  x)
{
            if(x == 1 || x ==0)
                        return 1;
            else
                        return (x * factorial(x -1) );
}
·         This is an example of a recursive function which does call itself. This is a powerful programming technique but it is least preferred in the embedded programming as it takes a lot of space in the system stack and memory is a main constraint in the Embedded Systems.
Arrays:
·         Arrays are continuous storage locations in memory which could be refered under a common name and could be used to store a collection of data of same data types.
·         The syntax for declaration of array is:
<data-type> <array-name>[<number-of elements>];
Eg:       int nos[20];
            char name[30];  
·         The indexing of array starts from 0, so if we want to access the first element, we give                    array[0];
·         There is no basic data type in C for storing strings, so we use array of characters for storing string. The end of the string should have a null character .ie ‘\0’.
Structures:
·         Structures are user defined data types which could be used to group different data-types under a common name.
Eg:
struct student
{
            int roll_no;
            char name[20];
            char place[20];
            int age;
};
·         We create the elements of an array as follows:
struct  student  s;
·         We use dot( . ) operator to access each element in a structure.
Eg:       s.age = 15;
            n = s.roll_no;
·         We could also create array of structures : struct  student  s[40];
Pointers:
·         Pointers are special variables which do hold the address of another variable.
Eg:
            int num = 25;
            int * ptr ; /* Declaring a pointer variable ptr */
ptr = &num; /* Assigning the address of variable num to ptr */
print(“%d”, *ptr); /* Printing the value at the address in ptr through dereferencing*/
·         Here we have created an integer num and a pointer variable ptr which could hold an address of a integer variable.
·         We have assigned the address of num to ptr using the address of operator( & ).
·         Using the dereferencing or vaule at operator ( * ) we have printed the value contained at the in ptr, which is equivalent as the value of num as ptr now has the address of variable num.



AVR Tutorial - 1.Basics


1.                  Basics
A microcontroller (sometimes abbreviated µC, uC or MCU) is a small computer on a single integrated circuit containing a processor core, memory, and programmable input/output peripherals. Program memory in the form of NOR flash or OTP ROM is also often included on chip, as well as a typically small amount of RAM. Microcontrollers are designed for embedded applications, in contrast to the microprocessors used in personal computers or other general purpose applications.
Microcontrollers are used in automatically controlled products and devices, such as automobile engine control systems, implantable medical devices, remote controls, office machines, appliances, power tools, toys and other embedded systems. By reducing the size and cost compared to a design that uses a separate microprocessor, memory, and input/output devices, microcontrollers make it economical to digitally control even more devices and processes. Mixed signal microcontrollers are common, integrating analog components needed to control non-digital electronic systems.
Some microcontrollers may use four-bit words and operate at clock rate frequencies as low as 4 kHz, for low power consumption (milliwatts or microwatts). They will generally have the ability to retain functionality while waiting for an event such as a button press or other interrupt; power consumption while sleeping (CPU clock and most peripherals off) may be just nanowatts, making many of them well suited for long lasting battery applications. Other microcontrollers may serve performance-critical roles, where they may need to act more like a digital signal processor (DSP), with higher clock speeds and power consumption.

Here in this tutorial we will be dealing with ATMEL’s AVR microcontrollers, more specifically ATMEGA-32. For futher reference about any further details about this MCU, you could refer to the manual for this MCU. We will be using WinAVR as our programming platform and avrdude as the programming application.   

Basic Electronics Tutorial





1.                  Resistor
         Resistor is the electronic component use to reduce the flow of current.
         Resistors are available at ¼, ½, 1, 2, 4 Watts and we need to select the appropriate one we need depending upon the voltage drop and current flowing through that.
         In our usual circuits working under 5 to 25 volts we use ¼ W resistors and its size will be small.
         The value of resistor is being calculated using the color codes given in that.







         Variable resistors are the resistors whose value could be changed
         They are of mainly two types: Preset type and Potentiometer Type
         They are being characterized by the maximum resistance it could offer.
        

It is mainly used for making potential divider arrangements.



 



Testing With A Multimeter
         Select the resistance range in the multimeter
         Check the resistor with that and get the resistence reading value from that.
         Compare that value with the one given in the color code. If both the vales remains same within the tolerance range, then it is working fine.

2.                  Capacitor
         Capacitor is the component which could store electric charge in it for a short time.
         The value of Capacitor is being measured in Farads, but as it is a large unit we mainly use micro Farads / nano Farads / pico Farads.
         They are of two types :
i.                    Electrolytic
Electrolytic capacitors have polarity and it has got higher capacitance compared to the other. We need to connect it with the correct polarity else Di-electric breakdown could happen. There is a working voltage given in the capacitor and it is the maximum voltage under which we could use that capacitor safely.

ii.                  Disk Type:
They have comparatively lower capacitance(in pF range). They usually don't have any polarity. Values are given in a number code somewhat similar to the resistor color codes.





  
         Variable Capacitors like Trimmers / Gang Condensers etc are used in circuits like radio tuning (for changing the Natural frequency of the LC circuit)





            Testing With A Multimeter(Works only with electrolytic capacitor with large capacitance and should be tested with an analogue multimeter)
         Select the resistance range in the multimeter
         First short circuit the two leads of the capacitor to avoid any charges residing in it.
         Connect the probes of the multimeter into the terminals and at that moment you could see a deflection and the pointer coming back. This is because at the instant when we connect the  probes to the terminal of capacitor there will be a difference in potential and a charging current will flow. Afterwords the capacitor gets into steady state and no current will be flowing.

3.                  Inductor
         An inductor (also choke, coil or reactor) is a passive two-terminal electrical component that stores energy in its magnetic field. For comparison, a capacitor stores energy in an electric field, and a resistor does not store energy but rather dissipates energy as heat.
         Any conductor has inductance. An inductor is typically made of a wire or other conductor wound into a coil, to increase the magnetic field.
         Unit of Inductance is Henry but we usually use milli Henry as unit.
         When an intuctor is connected to a circuit the moment when we switch on the circuit, the current will be zero and when we switch off the circuit, at that moment it will have the same current as before. It is the elctrical analouge of inertia in mechanical systems.




4.                  Transistor
         A transistor is a semiconductor device used to amplify and switch electronic signals and power. It is composed of a semiconductor material with at least three terminals for connection to an external circuit.
         A voltage or current applied to one pair of the transistor's terminals changes the current flowing through another pair of terminals. Because the controlled (output) power can be higher than the controlling (input) power, a transistor can amplify a signal.
         The transistor is the fundamental building block of modern electronic devices, and is ubiquitous in modern electronic systems.

  







Transistor Pin-Configuration



5.                  Diode
         In electronics, a diode is a two-terminal electronic component with asymmetric transfer characteristic, with low (ideally zero) resistance to current flow in one direction, and high (ideally infinite) resistance in the other. A semiconductor diode, the most common type today, is a crystalline piece of semiconductor material with a p-n junction connected to two electrical terminals

         The most common function of a diode is to allow an electric current to pass in one direction (called the diode's forward direction), while blocking current in the opposite direction (the reverse direction). Thus, the diode can be viewed as an electronic version of a check valve.
         In a diode the terminal near which a line is there will be catode and the other one will be anode.
        
Diode is commenly used for Rectification(Converting AC to DC)

Testing
        
Connect the diode terminals to a multimeter probe as given in the figure.
         When it is being forward biased, it should show very low resistance and in the other case, it should show high resistance.

Zener Diode:
         A zener diode is a special kind of diode which allows current to flow in the forward direction in the same manner as an ideal diode, but will also permit it to flow in the reverse direction when the voltage is above a certain value known as the breakdown voltage, "zener knee voltage" or "zener voltage."
         Common applications include providing a reference voltage for voltage regulators, or to protect other semiconductor devices from momentary voltage pulses.







LED – Light Emitting Diode





Photo Diode:
         A photodiode is a type of photodetector capable of converting light into either current or voltage, depending upon the mode of operation. The common, traditional solar cell used to generate electric solar power is a large area photodiode.
         Photodiodes are similar to regular semiconductor diodes except that they may be either exposed (to detect vacuum UV or X-rays) or packaged with a window or optical fiber connection to allow light to reach the sensitive part of the device.
         Many diodes designed for use specifically as a photodiode use a PIN junction rather than a p-n junction, to increase the speed of response. A photodiode is designed to operate in reverse bias.


6.                  IC

         IC or integrated circuit is a silicon chip in which millions of other components like resistor, capacitor, transistor were embedded into.
          The first integrated circuit was developed in the 1950s by Jack Kilby of Texas Instruments and Robert Noyce of Fairchild Semiconductor.
         Integrated circuits are used for a variety of devices, including microprocessors, audio and video equipment, and automobiles.
         Integrated circuits are often classified by the number of transistors and other electronic components they contain as SSI, LSI, MSI, VLSI, ULSI.
         You should be very careful while using and soldering ICs and should recheck that you are providing the correct working voltage for the IC as there are much chances for the IC's to burn off. Even for small surface mount ICs the static charge residing in your body could destroy them.
         Usually people use extra base for soldering and then put the IC into that after soldering the base.
         Inductor is a component that cannot be integrated into an IC.
IC Pin-numbering
            The pins are numbered anti-clockwise around the IC (chip) starting near the notch or dot.








7.                  Transformer
         A transformer is a device that transfers electrical energy from one circuit to another through inductively coupled conductors—the transformer's coils. A varying current in the first or primary winding creates a varying magnetic flux in the transformer's core and thus a varying magnetic field through the secondary winding. This varying magnetic field induces a varying electromotive force (EMF), or "voltage", in the secondary winding. This effect is called inductive coupling.
         If a load is connected to the secondary, current will flow in the secondary winding, and electrical energy will be transferred from the primary circuit through the transformer to the load. In an ideal transformer, the induced voltage in the secondary winding (Vs) is in proportion to the primary voltage (Vp) and is given by the ratio of the number of turns in the secondary (Ns) to the number of turns in the primary (Np) as follows:

         By appropriate selection of the ratio of turns, a transformer thus enables an alternating current (AC) voltage to be "stepped up" by making Ns greater than Np, or "stepped down" by making Ns less than Np. The windings are coils wound around a ferromagnetic core, air-core transformers being a notable exception.
         We usally charecterise the transformer by the primary and secondary voltages and also the current flowing through the secondary.
         Usally there are two types of transformers: Single tapped and central tapped transformer.
         In power eliminators with multiple voltage outputs, we use multi-tapped transformers.



Rectifiers:





8.                  Voltage Regulators
         Regulators are used to give a particular voltage out put if we give a voltage input above that voltage, within a range.


NB: This is a 5V regulator.

9.                  LDR
         LDR or Light Dependent Resistor is a component whose resistance changes with the intensity of light falling into it. So this component is being used as light sensors / detectors.



10.     Soldering Basics
Soldering is a process in which two or more metal items are joined together by melting and flowing a filler metal (solder) into the joint, the filler metal having a lower melting point than the workpiece. Soldering differs from welding in that soldering does not involve melting the work pieces

         Soldering Iron
Soldering Iron is the main equipment required for soldering.It is characterised in Watts.Irons of the 15W to 30W range are good for most electronics/printed circuit board work.
         Solder and Flux
Solder is a metal or metallic alloy used, when melted, to join metallic surfaces together. The most common alloy is some combination of tin and lead.Flux cleans oxides of the surfaces to be soldered.
Steps:
         Before use, a new soldering tip, or one that is very dirty, must be tinned. "Tinning" is the process of coating a soldering tip with a thin coat of solder. This aids in heat transfer between the tip and the component you are soldering.
         Warm up the soldering iron or gun thoroughly. Make sure that it has fully come to temperature because you are about to melt a lot of solder on it. This is especially important if the iron is new because it may have been packed with some kind of coating to prevent corrosion.
         Thoroughly coat the soldering tip in solder. It is very important to cover the entire tip. You will use a considerable amount of solder during this process and it will drip, so be ready. If you leave any part of the tip uncovered it will tend to collect flux residue and will not conduct heat very well, so run the solder up and down the tip and completely around it to totally cover it in molten solder






11.                        Multimeter and Testing Components
         A multimeter or a multitester, also known as a VOM (Volt-Ohm meter), is an electronic measuring instrument that combines several measurement functions in one unit. A typical multimeter may include features such as the ability to measure voltage, current and resistance,continuity,capacitance and also for identifying teminals of transistor.
         Multimeters are of two types:digital and analog


         All digital meters contain a battery to power the display so they use virtually no power from the circuit under test. This means that on their DC voltage ranges they have a very high resistance and  they are very unlikely to affect the circuit under test.
         Analogue meters take a little power from the circuit under test to operate their pointer. They must have a high sensitivity of at least 20k/V or they may upset the circuit under test and give an incorrect reading.
         A digital multimeter is the best choice for your first multimeter, even the cheapest will be suitable for testing simple projects.

Testing Transistor With Multimeter:
         Set the meter to its ohms range - any range should do, but the middle ohms range if several are available is probably best.
         Connect the base terminal of the transistor to the terminal marked positive (usually coloured red) on the multimeter
         Connect the terminal marked negative or common (usually coloured black) to the collector and measure the resistance. It should read open circuit (there should be a deflection for a PNP transistor).
         With the terminal marked positive still connected to the base, repeat the measurement with the positive terminal connected to the emitter. The reading should again read open circuit (the multimeter should deflect for a PNP transistor).
         Now reverse the connection to the base of the transistor, this time connecting the negative or common (black) terminal of the analogue test meter to the base of the transistor.
         Connect the terminal marked positive, first to the collector and measure the resistance. Then take it to the emitter. In both cases the meter should deflect (indicate open circuit for a PNP transistor).
         It is next necessary to connect the meter negative or common to the collector and meter positive to the emitter. Check that the meter reads open circuit. (The meter should read open circuit for both NPN and PNP types.
         Now reverse the connections so that the meter negative or common is connected to the emitter and meter positive to the collector. Check again that the meter reads open circuit.
         If the transistor passes all the tests then it is basically functional and all the junctions are intact.


12. Relays
         Relays are switching components which could be turned on / off by giving a voltage across that.
         There are two types of relays:
i. Industrial Relay : Used to drive High current devices / circuits.
ii. Sugar Cube Relays: Small Circuit Relays which could be placed in circuits and used for switching low power devices / circuits.

  

Tower of Hanoi Problem(Solution in C++)


//Solving the tower of Hanoi Problem....----Feel the power of Recursion -----

#include<iostream>

using namespace std;

void solveTowerofHanoi(int n,char frompeg,char topeg, char auxpeg);

int main()
{
    int n;
    char frompeg, topeg, auxpeg;
    cout<<"Eneter the number of rings :";
    cin>>n;
    cout<<"Enter a character reprsentation for source peg :";
    cin>>frompeg;
    cout<<"Enter a character reprsentation for destination peg :";
    cin>>topeg;
    cout<<"Enter a character reprsentation for auxilliary peg :";
    cin>>auxpeg;

    cout<<"Let the 1 be the smallest ring and "<<n<<" be the largest ring, the solution is:\n";
    solveTowerofHanoi(n,frompeg,topeg,auxpeg);
    return (0);



}

void solveTowerofHanoi(int n,char frompeg,char topeg, char auxpeg)
{
    if(n == 1)
    {
        //If there is only one ring, move it directly from source peg to destination peg
        cout<<"Move ring 1 from "<<frompeg<<" to "<<topeg<<"\n";
    }
    else
    {
        //Mov n-1 pegs from source peg to auxilliary peg
        solveTowerofHanoi(n-1,frompeg,auxpeg,topeg);

        //Move the nth ring to destination peg
        cout<<"Move ring "<<n<<" from "<<frompeg<<" to "<<topeg<<"\n";

        //Now transfer the n-1 rings from auxilliary peg to the destination peg
        solveTowerofHanoi(n-1,auxpeg, topeg, frompeg);

    }


}