150 likes | 281 Views
Interrupts. Microprocessor and Interfacing 261214. Example: Writing a Game. Need to Check Keyboard Input. Method 1: Using a Loop Program keeps checking for keyboard input. While (1) [ If Key = Right Then moveRight ElseIf Key = Left Then moveLeft End If ].
E N D
Interrupts Microprocessor and Interfacing261214
Example: Writing a Game Need to Check Keyboard Input
Method 1: Using a LoopProgram keeps checking for keyboard input While (1) [ If Key = Right Then moveRight ElseIf Key = Left Then moveLeft End If ]
Mothod II: Use KeyPress EventRuns only when there is a keyboard interrupt KeyPressEvent(Key) If Key = Left Then MoveLeft ElseIf Key = Right Then MoveRight End If End Subroutine
Method I : Software Polling Method II : Event or Interrupt Driven
I/O Handling Techniques • Software Polling • Interrupts • Direct Memory Access (DMA)
Benefits of Using Interrupts • Consumes much less CPU • Especially when interrupt generated by hardware • Cleaner & Simpler Code • Allows Basic Parallel Processing
Exercise: Program a PIC Microcontroller • Blink an LED every 0.5 sec • Also receives serial data from the computer What’s wrong with this program? While (1) { output_toggle(LED); delay_ms(500); data = getchar(); }
A better program, but not best While (1) { output_toggle(LED); delay_ms(500); if (kbhit()) { data = getchar(); } }
How do we fix the problem? Available Commands • Getchar() – wait and return serial data • Output_toggle(LED) • Time() – returns current time (in ms) • Kbhit() – returns true if serial data is available
Solution Software Polling IntcurrentTime; Char data; startTime = time(); While (1) { if (time() – startTime > 500) { output_toggle(LED); startTime = time(); } if (kbhit()) { data = getchar(); } }
Same Program with Timer Interrupt timerISR() { output_toggle(LED); } Main() { setupTimer(); while (1) { data = getchar(); } }