Chapter 5
Chapter 5
INTERRUPTS STRUCTURE
What is Interrupt
It is an internal or external events that inform the CPU something needs to be serviced
• interrupt:interrupt number
• ISR: The name of the
function to be called when
an interrupt event is
generated.
• Mode: LOW; HIGH;RISING;
FALLING; CHANGE
•RISING: To trigger an interrupt when the pin transits from LOW to HIGH.
•FALLING: To trigger an interrupt when the pin transits from HIGH to LOW.
•CHANGE: To trigger an interrupt when the pin transits from LOW to HIGH
or HIGH to LOW (i.e., when the pin state changes ).
Experiment with Arduino
Example
void setup() {
pinMode(interruptPin, INPUT_PULLUP); // cấu hình chân ngắt
attachInterrupt(digitalPinToInterrupt(interruptPin), ISR, CHANGE); // đăng ký ngắt
Serial.begin(9600); // cấu hình Serial monitor
}
void loop() {
// thực hiện các hoạt động khác trong vòng lặp chính
}
void ISR() {
state = !state; // cập nhật trạng thái biến
Serial.println(state); // hiển thị giá trị trạng thái mới
}
#include <TimerOne.h>
const int led = LED_BUILTIN; // the pin with a LED
int ledState = LOW;
volatile unsigned long blinkCount = 0; // use volatile for shared variables
void setup(void)
{
pinMode(led, OUTPUT);
Timer1.initialize(150000);
Timer1.attachInterrupt(blinkLED); // blinkLED to run every 0.15 seconds
Serial.begin(9600);
}
//Interrupt Programming
void blinkLED(void)
{
if (ledState == LOW) {
ledState = HIGH;
blinkCount = blinkCount + 1; // increase when LED turns on
} else {
ledState = LOW;
}
digitalWrite(led, ledState);
}
// The main program will print the blink count
void loop(void)
{
unsigned long blinkCopy; // holds a copy of the blinkCount
noInterrupts();
blinkCopy = blinkCount;
interrupts();
Serial.print("blinkCount = ");
Serial.println(blinkCopy);
delay(100);
}
BÀI TOÁN ĐO TỐC ĐỘ CAO (HIGH SPEED MEASUREMENTS)