Timer program in 8051

Program to produce a square wave of 1KHz frequency ( Timer program in 8051 ):

Refer timer section>>>
Here we will consider T0 , which has an internal clock ( 1MHz ). And the square wave signal will be produced at P1.6, which would be connected to CRO for display. So providing continuous HIGH and LOW signals would produce continuous square wave.

Time period = 1/1K = 1m sec ( 1 x 10-3 seconds )

The timer period of the total cycle ( high and low ) is 1 millisecond.

Clock frequency is 1MHz

Time period = 1/1M = 1μ sec

Sample square wave
Sample square wave

After every HIGH signal we need 0.5msec delay, and similarly to LOW signal. So for 0.5msec ( 500μ secs ), Timer should count 500 counts ( 1 count = 1μ sec ). Below is the explanataion of timer program in 8051 microcontroller.

Put 500 to T0 .

Count required = 65,535 – required count + 1

=65,536 – 500 + 1

= ( 65,036 )D

= ( FE0C )H

MOV TL0 , #0CH 

MOV Th0 , #0FEH ( whenever numerical starts with character, we must put zero before it , to let know assembler it is an numerical )

Main: CLR P1.6 ( clear the bit ) {{{{{ timer program in 8051 microcontroller }}}}}}

ACALL delay ( call the delay, delay would be declared later )

SETB P1.6 ( put 1 )

ACALL delay ( call the same delay, 500 msec as it is a square wave)

SJMP Main ( go back to Main label, for infinite loop )

delay: MOV TMOD , #01H

We select the TMOD register requirements ( we use mode 1 ( 16bit counter )). To understand timer programs in 8051, timer modes of 8051 are needed first, click here to learn about timer modes in 8051

tmod register for timer program in 8051
tmod register for timer program in 8051

TMOD register is mainly used for timer program in 8051 microcontroller. In this 4 bits are for timer ( we dont require ), here gate = 0 ( no external control ). C/T = 0 ( it’s a timer ).

MOV TL0 , #0CH

MOV TH0 , #0FEH

Giving timer count to the T0.

MOV TCON , #10H

Timer Register in 8051 Microcontroller
Timer Register in 8051 Microcontroller

Here TR0 = 1, which means run the timer.

wait: JNB TF0 , wait

Keep jumping in the same instruction until , when TF0 = 1, then next line will be executed

CLR TR0 

Clear the TR0, however already the timer is overflown. This instruction is to set the timer as it was previous. 

CLR TF0

Clears the TF0 flag.

RET

Returns to the main program.

Total program for timer in 8051

Main: 	CLR P1.6		
	ACALL delay 			
        SETB P1.6		
        ACALL delay 	
        SJMP Main 	
	
delay: 	MOV TMOD , #01H
	MOV TL0 , #0CH
	MOV TH0 , #0FEH
	MOV TCON , #10H
	
wait: 	JNB TF0 , wait
	CLR TR0 
	CLR TF0
	RET

Try simulating edsim51 to understand these programs.

Spread knowledge

Leave a Comment

Your email address will not be published. Required fields are marked *