I'm new in embedded programming in C, just getting to understand coding. Is there a fundamental difference between an interrupt function and a delay function?
I would greatly appreciate answers with example code.
Electrical Engineering Stack Exchange is a question and answer site for electronics and electrical engineering professionals, students, and enthusiasts. It only takes a minute to sign up.Sign up to join this community
Those are two conceptually totally different things.
This is more commonly called an interrupt handler or Interrupt Service Routine (ISR). The execution is triggered by the reception of an hardware interrupt. What actions are taken in the ISR normally depends on the reason the interrupt was generated (the kind of interrupt source that caused it).
This is typically a function accepting 1 parameter which specifies the delay that the code execution should be blocked for.
Maybe you are confused here, because a delay can also be implemented using a interrupt driven approach. You can implement a delay using a (timer) interrupt. This is often preferred to calling a delay function like
delay(1000); /// delay for 1000ms
because this would block the main loop for 1 second.
Using an interrupt based approach, you can set some kind of flag in the interrupt service routine (which fires after a specific delay using a hardware timer/counter). That flag can just be checked in the main loop to determine if the delay expired, effectively not blocking other code from execution.
During a "delay", the programs sits and waits at a particular point in a program, and does nothing else. An interrupt, though, can occur anytime. It yanks the program pointer away from whatever line of execution it happened to be at, does some processing in an interrupt routine, and then restores the program pointer to where it was before the interrupt.
You can achieve an effective delay using one kind of interrupt that is triggered by a timer (i.e., a timer interrupt). You preload the timer to some value, start the timer, and trigger an interrupt when the timer register rolls over.
An Interrupt is agenerated in response to a certain event. For example if you generate an interrupt on a switch, that part of code will only be called when that switch is pressed. In case of a delay function, you constantly check every few microseconds if the key has been pressed.
Think of this as mail on your phone vs Webmail. In the first case, whenever you receive an email, you get a notification on your smartphone saying you have a mail. In case of webmail, you check every few minutes(or hours) whether you have a mail.