Interrupts
Interrupts
Objective:
Timer Configuration
1. Write a C program that continuously gets a single bit of data from P1.7 and sends it to P1.0,
while simultaneously creating a square wave of 200 μs period on pin P2.5. Use Timer 0 to
create the square wave. Assume that XTAL = 11.0592 MHz.
#include <reg51.h>
sbitSW =P1^7;
sbitIND =P1^0;
sbitWAVE =P2^5;
void timer0(void) interrupt 1 {
WAVE=~WAVE; //toggle pin
}
void main() {
SW=1; //make switch input
TMOD=0x02;
TH0=0xA4; //TH0=-92
IE=0x82; //enable interrupt for timer 0
while (1) {
IND=SW; //send switch to LED
}
}
2. Write a C program using interrupts to do the following:
(a) Generate a 10 KHz frequency on P2.1 using T0 8-bit auto-reload
(b) Use timer 1 as an event counter to count up a 1-Hz pulse and display it on P0. The pulse is
connected to EX1. Assume that XTAL = 11.0592 MHz. Set the baud rate at 9600.
Solution:
#include <reg51.h>
Sbit WAVE =P2^1;
Unsigned char cnt;
void timer0() interrupt 1 {
WAVE=~WAVE; //toggle pin
}
void timer1() interrupt 3 {
cnt++; //increment counter
P0=cnt; //display value on pins
}
void main () {
cnt=0; //set counter to 0
TMOD=0x42;
TH0=0x-46; //10 KHz
IE=0x86; //enable interrupts
TR0=1; //start timer 0
while (1); //wait until interrupted
}
3. Write a C program using interrupts to do the following: (a) Receive data serially and send it to P0
(b) Read port P1, transmit data serially, and give a copy to P2 (c) Make timer 0 generate a square
wave of 5 kHz frequency on P0.1 Assume that XTAL = 11.0592 MHz. Set the baud rate at 4800.
#include <reg51.h>
sbit WAVE =P0^1;
void timer0() interrupt 1 {
WAVE=~WAVE; //toggle pin
}
void serial0() interrupt 4 {
if (TI==1) {
TI=0; //clear interrupt
}
else {
P0=SBUF; //put value on pins
RI=0; //clear interrupt
}
}
void main () {
unsigned char x;
P1=0xFF; //make P1 an input
TMOD=0x22;
TH1=0xF6; //4800 baud rate
SCON=0x50;
TH0=0xA4; //5 kHz has T=200us
IE=0x92; //enable interrupts
TR1=1; //start timer 1
TR0=1; //start timer 0
while (1) {
x=P1; //read value from pins
SBUF=x; //put value in buffer
P2=x; //write value to pins
}
}