Saturday, June 23, 2012

Interrupt Programming in 8051 MicroController with Keil


       Concept behind Interrupt
      Interrupt vs Polling
      What is the advantage of having interrupt based system over polling system
       Interrupt Process:
Upon activation of an interrupt, the microcontroller goes through the following steps,
  1. It finishes the instruction it is executing and saves the address of the next instruction (PC) on the stack
  2. It also saves the current status of all the interrupts internally (i.e: not on the stack)
  3. It jumps to a fixed location in memory,  called the interrupt vector table, that holds the address of the ISR.
  4. The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it.
    1. It starts to execute the interrupt service subroutine until it reaches the last instruction of the subroutine which is RETI (return from interrupt)
  5. Upon executing the RETI instruction, the microcontroller returns to the place where it was interrupted and starts executing form that address.
Learn More about Interrupt, timer and Serial Programming in 8051 Micro Controller : Click here
Sample Programs for Interrup Programming in 8051 Micro Controller
/*
 Write a program to count from 0 to 256 with an interval of 100 ms and display the result on p2.
 */

#include <regx51.h>
void delay1ms(int n)
 {
  int i=0;
while(i<=n)
{
 TMOD=0x01;
 TL0=0x00;
 TH0=0x35;
 TR0=1;
 while(!TF0);
 TR0=0;
 TF0=0;
 i++;
 }
 }               
 void main()
 {
    int a=0;
  P2=0x00;
 while(a<=256)
  {
  delay1ms(20);
  P2=a;
 a++;
 }
  }

/*
Assume that there is a queue of people ready to enter inside a cinema hall whose capacity is 50 seats.
No morea than 50 people are allowed inside the hall and the gate is closed as soon as the hall is full.
There is a gate counter (sensor) to count the inflow of people and the number of people entered so far
is displayed in the display device at the gate.

                a. Write a program for the above scenario.
                b. Gate Sensor is connected to the external interupt 0 (EX0)
                c. Number can be connected using LED connected in port 1.

*/


#include<regx51.h>
int a = 0;
 
void main()
{
 P3_2=1; /* for external interrupt at port 3 bot 2*/
 P1=0x00;  //Port interrupt in input mode
 EA=1;     //For Enabling the interrupt register
 EX0=1;   //External interrupt set
 IT0=1;   //For Edge Triggered System
 P1=0x00;
 while (a<=50)
 {
 if (a<=50)
 {
 P1 = a;
 P3_2=1;               // Again the port is set for input mode
 }
 }

}
void intpt() interrupt 0  //Interrupt Service Routine
{
a++;
}

Timer Programming in 8051 Micro Controller with Keil

Learn More about Interrupt, timer and Serial Programming in 8051 Micro Controller : Click here
      The 8051 has two timers/counters, they can be used either as
     Timers to generate a time delay
     or as Event counters to count events happening outside the microcontroller
      Both Timer 0 and Timer 1 are 16 bits wide.
      Since 8051 has an 8-bit architecture, each 16-bits timer is accessed as two separate registers of low byte and high byte.
     The low byte register is called TL0/TL1 and
     The high byte register is called TH0/TH1
The 8051 has two timers/counters, they can be used either as 

     Timers to generate a time delay
     or as Event counters to count events happening outside the microcontroller.
Both Timer 0 and Timer 1 are 16 bits wide.

      Since 8051 has an 8-bit architecture, each 16-bits timer is accessed as two separate registers of low byte and high byte.
     The low byte register is called TL0/TL1 and
     The high byte register is called TH0/TH1
Both timers 0 and 1 use the same register, called TMOD (timer mode), to set the   various timer operation modes.

                             8051 Micro Controller Timer mode 1 programming

      The following are the characteristics and operations of mode1:
     It is a 16-bit timer; therefore, it allows value of 0000 to FFFFH to be loaded into the timer’s register TL and TH
     After TH and TL are loaded with a 16-bit initial value, the timer must be started
     This is done by setting high TR0 for timer0 and  TR1 for timer1
     After the timer is started, it starts to count up
     It counts up until it reaches its limit of FFFFH
     When it rolls over from FFFFH to 0000, it sets high a flag bit called TF (timer flag).Each timer has its own timer flag: TF0 for timer 0, and TF1 for timer 1.
     When this timer flag is raised, one option would be to stop the timer.
     After the timer reaches its limit and rolls over, in order to repeat the process TH and TL must be reloaded with the original value, and TF must be reloaded to 0.


                             8051 Micro Controller Delay generation process

1.      Load the TMOD value register indicating which timer (timer 0 or timer 1) is to be used and which timer mode (0 or 1) is selected.
2.      Load registers TL and TH with initial count value.
3.      Start the timer.
4.      Keep monitoring the timer flag (TF). if it is raised,
5.      ƒStop the timer.
6.      Clear the TF flag for the next round
7.      Go back to Step 2 to load TH and TL again.

How to calculate values to be loaded into TH and TL 

Assume XTAL = 11.0592 MHz, we can use the following steps for finding the TH and TL registers’ values,
1.      Divide the desired time delay by 1.085 us.
2.      Calculate 65536 – n, where n is the decimal value we got in Step1.
3.      Convert the result of Step2 to hex, where yyxx is the initial hex value to be loaded into the timer’s register
4.      Set TL = xx and TH = yy.

Some Examples of 8051 Micro Controller Programming in Keil Micro Vision 4

To create a program in keil follow the following steps:

a.      Get the Keil MicroVision 4 from keil.com and install it on your computer.
b.      Click the project tab and create a new project.
c.      Select the microcontroller.
d.      Microcontroller here I will be using is AT 89C51
e.      Then Click create.
f.       From the Flash tab select Configure Flash Tools.
g.      Inside the new window, inside the Target Tab Check the Use the onchip Rom Option.
h.      Select Code Rom Size: less than 2k memory for Small programs.
i.        Give the Crystal Frequency 11.0592 mhz.
j.        Inside the Output Tab Check the Create a hex file to create a hex file.
k.      Add a C code file (.c file ) to your project by Rt Clicking the project.


/*
Write a program to Toggle (on/Off) bits of Port 2(P2) continuously forever with delay.
*/

# include <regx51.h>
 void main()
 {
            int i;
            P2=0x00;
            while(1)
            {
                        P2= 0x00;
                        for(i=0;i<15000;i++);
                        P2=0xFF;
                        for(i=0;i<15000;i++);
            }         
 }


/*
Write a program to on/off leds connected in port1 using Push Switches Sw1 (used as on switch) connected to p2.0 pin  and SW2 used as off switch connected to p2.1
 */
 # include <regx51.h>
 void main()
 {
            int i;
            P1=0x00;
            P2=0x00;
            while(1)
            {
                        if (P2_1==1 && P2_0==0)
                                    P1=0xFF;
                        else
                                    P1=0x00;
                        for(i=0;i<10000;i++);
            }
 }



/*
Write a program to display count 0 to 9 in 7-Segment display with the timing interval of 1 sec. Use Timer 0, 16 bit mode to generate the delay. 7 Segment display is connected to P1.
*/

#include <regx51.h>
void delay1ms(unsigned int i)
{                        int c=0;
            while(c<i)
            {
                          TMOD=0x01;
                          TH0=0xFC;
                          TL0=0x66;
                          TR0= 1;
                          while(!TF0);
                                    TR0=0;
                                    TF0=0;
                                     c++;
            }
}
void main()
{
            P1=0x00;
            while(1)
            {
                        P1=0xC0;
                        delay1ms(1000);
                        P1=0xF9;
                        delay1ms(1000);
                        P1=0xA4;
                        delay1ms(1000);
                        P1=0xB0;
                        delay1ms(1000);
                        P1=0x99;
                        delay1ms(1000);
                        P1=0x92;
                        delay1ms(1000);
                        P1=0x82;
                        delay1ms(1000);
                        P1=0xF8;
                        delay1ms(1000);
                        P1=0x80;
                        delay1ms(1000);
                        P1=0x98;
                        delay1ms(1000);
            }
}


Saturday, June 16, 2012

Backtracking , Structures,Non Deterministic Finite State Automata [Artificial Intelligence Programming in Visual Prologue] --Part II


Backtracking
As has already been seen prolog has built in backtracking mechanism. It tries to prove a goal with all possible instantiations. Automatic backtracking is a useful programming concept because it reveals the programmer of the burden of backtracking explicitly. However in some cases this feature degrades the efficiency of the program.

For example in cases where one solution is sufficient, backtracking to find all the solutions is not a good idea. Similarly, in case of mutually exclusive rules(clauses) when one rule has been proved then it is known in advance that no other rules can succeed. So this backtracking can be controlled by the use of ‘cut’, (“!”).

The disadvantage of using cut is that we tend to move away from the declarative nature of the prolog because when we have used the cut the order of the clauses may make difference in the result we get.
                
Consider the function. The relation between X and Y can be specified by the following three rules.
Rule 1: if X<3 then Y=0
Rule 2: if 3=<X <6 then Y=2
Rule 3: if 6<X then Y=4

This can be programmed as
PREDICATES
f(integer,integer)

CLAUSES
f(X,0):-
                X<3.
f(X,2):-
                3<=X,X<6.
               
f(X,4):-
                6<X.
               
GOAL
f(2,X).

Now modify the program using cut and observe the difference between the two modules. Comment on the difference.

Solution:

Backtracking happens here after the cut operator is added and due to this cut operator the goal returns only one value. Backtracking is like a Tree.

PREDICATES
f(integer,integer)

CLAUSES
f(X,0):-
            X<3.
f(X,2):-
            3<=X,X<6,!.
f(X,4):-
            6>X.
           
GOAL
f(4,X).


Define the relation min(X,Y,Z) where Z returns the smaller of the two given numbers X and Y. Do it with and without the use of cut and comment on the result.

Ans: Here in this Question the cut operator is used which makes the backtracking stop if solution is found. If 2,3 are passed to the predicate then the compiler tries to find the solution. Backtracking is only effective after a solution is found.

PREDICATES
min (Integer, Integer , Integer)
Clauses
min(X,Y,Y):-X>Y,!.
min (X,Y,X):-Y>X.
Goal
min(2,3,Z).
/**/


Structure revisited
            In prolog we can use structures to define data types of our requirement. For example if we want to use date as an structure we can define date as a structure in the domains section as follows

date=d(integer,symbol,integer)

We can then on use date as a data type to contain the date.
DOMAINS
date=d(integer,symbol,integer)

PREDICATES
inquire
display(symbol)
date_of_birth(symbol,date)

CLAUSES
date_of_birth(ram,d(12,july,1983)).
date_of_birth(shyam,d(15,august,1976)).
date_of_birth(hari,d(26,may,1994)).
date_of_birth(sita,d(29,september,1991)).

display(X):-
                date_of_birth(X,Y),
                write(X),nl,
                write(Y).
inquire:-
                write("Enter the name"),
                readln(X),
                display(X).          
GOAL
inquire.




Here the goal so proceeds as to ask a name from the user and to display the date of birth of the person with that name. With a little modification we can write goals which can find out persons with age below or above certain value, persons born in a month etc as in a relational database.

So the facts of the prolog can be thought of as a database. In fact we use structures to define certain relations and for all purposes of integrity this can be used similar to a table in a relational database. We call it the prolog’s internal database. We can update this database during the execution of the program by using the following keywords.

assert(C)   – this keyword can be used to assert a data in the facts base as
asserta(C) and assertz( C) can be used to control the position of insertion, the two asserts at the beginning and the end respectively.
retract( C) –deletes a clause that matches C.


An example

DOMAINS
date=d(integer,symbol,integer)
works=w(symbol,integer)

FACTS
person(symbol,symbol,date,works).

PREDICATES

start
load_name
evalans(integer)
display
search
dispname(symbol)
delete

CLAUSES

person(shyam,sharma,d(12,august,1976),w(ntv,18000)).
person(ram,sharma,d(12,august,1976),w(ntv,18000)).
person(ram,singh,d(13,may,2001),w(utl,12000)).



start:-
                write("*************MENU**************"),nl,
                write("Press 1 to add new data"),nl,
                write("Press 2 to show existing data"),nl,
                write("Press 3 to search"),nl,
                write("Press 4 to delete"),nl,
                write("Press 0 to exit"),nl,
                write("*************MENU**************"),nl,
                readint(X),
                evalans(X).

evalans(1):-
                load_name,
                start.
               
evalans(2):-
                display,
                evalans(2).

evalans(3):-
                search,
                evalans(3).
               
evalans(4):-
                delete,
                evalans(4).
               

evalans(0):-
                write("Thank You").
               
delete.
/* write clauses delete a fact from the facts base */

search.
/*write  clauses to search a fact from the facts base */

               
dispname(N):-
                person(N,C,d(D,M,Y),w(O,S)),
                write("Name:",N," ",C),nl,
                write("Date of Birth:",D,"th"," ",M," ",Y),nl,
                write("Organisation:",O),nl,
                write("Salary:",S),nl,nl.

               

display:-
                retract(person(N,X,d(D,M,Y),w(O,S))),
                write("Name:",N," ",X),nl,
                write("Date of Birth:",D,"th"," ",M," ",Y),nl,
                write("Organisation:",O),nl,
                write("Salary:",S),nl,nl.
               

load_name:-
                write("Enter the name \n"),
                readln(N),
                write("Enter the surname \n"),
                readln(S),
                write("Date of Birth \n Day:"),
                readint(D),nl,
                write("Month:"),
                readln(M),nl,
                write("Year:"),
                readint(Y),nl,
                write("Enter the organisation:"),
                readln(O),
                write("Enter the salary:"),
                readint(Sl),nl,nl,
                asserta(person(N,S,d(D,M,Y),w(O,Sl))).
               
               
GOAL
start.


We may not use prolog to handle databases but the use of prologs internal database makes problem solving with prolog lot more easy.  

Assignment: Observe the above program. Add clauses for search and delete and extend your module as much as you like 3.


Simple application

Let us now see how the features of prolog can be used to simulate a non-deterministic automata which would have been a cumbersome task using other programming languages.

A nondeterministic finite automaton is an abstract machine that reads a string of symbols as input and decides whether to accept or to reject the input string. An automaton has a number of states and it is always in one of the states. The automata can change from one state to another upon encountering some input symbols. In a non deterministic automata the transitions can be non deterministic meaning that the transition may take place with a NULL character or the same character may result in different sitions

A non deterministic automaton decides which of the possible moves to execute, and it chooses a move that leads to the acceptance of the string if such a move is available.

Let us simulate the given automata.


 

DOMAINS
Symb_list=symbol*

PREDICATES
Trans(symbol,symbol,symbol)
Silent(symbol,symbol)
Final(symbol)

CLAUSES
final(s3).

trans(s1,a,s1).
trans(s1,a,s2).
trans(s1,b,s1).
trans(s2,b,s3).
trans(s3,b,s4).

silent(s2,s4).
silent(s3,s1).


accepts(S,[]):-
                final(S).

accepts(S,[H|T]):-
                trans(S,H,S1),
                accepts(S1,T).

accepts(S,X):-
                silent(S,S1),
                accepts(S1,X).

GOAL
Accepts(S,[a,b]).



Check the automaton with various input strings and with various initial states. ( The initial state  need not necessarily be s1.) Observe the result and comment on how the simulation works.
            Use the following goals
  • accepts(s1,[a,a,b]).
  • accepts(s1,[a,b,b]).
  • accepts(S,[b,a,b]).
  • accepts(s1,[X,Y,Z]).
  • accepts(s2,[b]).
  • accepts(s1,[_,_,_,_|[a,b]]).