DE6417 Microcontrollers 2 - Week 2 Practical Session
Explain how an external event can interrupt the normal program flow.
Use attachInterrupt() on pin 2 or pin 3 at Arduino API level.
Use the oscilloscope to prove that the output is the inverse of the input.
A polling loop samples the pin at particular moments. A fast input can change between those moments, so the program reacts late or not at all.
The program can do other work. It does not need to keep checking pin 2.
The signal generator creates an edge on pin 2.
The callback reads pin 2 and writes the opposite value to pin 8.
On the scope, CH2 should be opposite to CH1.
digitalPinToInterrupt(2)digitalPinToInterrupt(3)CHANGE, because an inverter must respond to both rising and falling transitions.const byte INPUT_PIN = 2;
attachInterrupt(
digitalPinToInterrupt(INPUT_PIN),
inputChanged,
CHANGE
);
pin 2GNDpin 8 is the inverted outputloop() is intentionally empty.const byte INPUT_PIN = 2;
const byte OUTPUT_PIN = 8;
void inputChanged() {
int inputState = digitalRead(INPUT_PIN);
digitalWrite(OUTPUT_PIN, !inputState);
}
void setup() {
pinMode(INPUT_PIN, INPUT);
pinMode(OUTPUT_PIN, OUTPUT);
int startState = digitalRead(INPUT_PIN);
digitalWrite(OUTPUT_PIN, !startState);
attachInterrupt(
digitalPinToInterrupt(INPUT_PIN),
inputChanged,
CHANGE
);
}
void loop() {
// The signal is handled by the callback.
}
loop() is not reading the signal.CHANGE is used.Once the inverter works at low frequency, increase the signal generator gradually.
| Question | Your answer |
|---|---|
Which Arduino Uno pins can use attachInterrupt() today? |
|
Why did we use CHANGE? |
|
| What should CH2 show when CH1 is HIGH? |
Use this only after attempting the practical.
const byte INPUT_PIN = 2;
const byte OUTPUT_PIN = 8;
void inputChanged() {
int inputState = digitalRead(INPUT_PIN);
digitalWrite(OUTPUT_PIN, !inputState);
}
void setup() {
pinMode(INPUT_PIN, INPUT);
pinMode(OUTPUT_PIN, OUTPUT);
int startState = digitalRead(INPUT_PIN);
digitalWrite(OUTPUT_PIN, !startState);
attachInterrupt(
digitalPinToInterrupt(INPUT_PIN),
inputChanged,
CHANGE
);
}
void loop() {
}
Interrupts let code react when an input changes, instead of constantly checking it.
An inverter must update on both edges, so CHANGE is the right trigger mode.
This is a learning inverter. For high-speed inversion, use hardware logic.