ESTE: GPIO and External Interrupts - part 2
This experiment is part of this project.
Here we are going to build another experiment with an led and a push button, using the GPIO to consolidate concepts of interrupts. The exercise here proposed is to turn on a led always when a push button is pressed and off when the button is no longer pressed. To complete this experiment it is recommended to see at first the GPIO and External Interrupts - part 1 scripts.
Pseudo code
Let's begin with a solution. The pseudo code (actual coding is up to you) is below:
int main(void) {
type_interrupt = 0; //you can select two types of interrupt: 0 (pin 2) and 1 (pin 3);
led_state = 0; //state = 0, led is off; state =1, led is on
limit_time = 100; //limit time in ms to stabilize the calls of interruption
moment = CHANGE;
/*here we specify when or wich moment of the signal calls the interruption. We can have the values: HIGH, LOW, CHANGE, RISING, FALLING*/
button_state = 0; //to check exactly if it is happenig a RISING or a FALLING
while(1) {
if (moment)
led_change();
else
set_led(led, led_state);
}
return 0;
}
void led_change(){
if (debounce()){
if (button_state == HIGH)
state = HIGH; //if the button is pressed, the led is on
else
state = LOW; //if the button isn’t pressed anymore, the led is off
last_button_time = button_time;
}
}
int debounce(){
//debounce is the function responsable for stabilizing the call to interruption
debounce_time = time_passed(); //It performs a delay
if(debounce_time > limit_time)
stabilazed = 1;
else
stabilazed = 0;
return stabilazed;
}
This pseudo-code always send a led_state to the led so that it atualizes his brightness acording to the states on and off. When the microcontroller detects a special “moment”, it will call the function specified to a certain type_interrupt (each type of interruption can call only one function or perform one determinated action). To truly perform the led_change() it is necessary to check if the debounce() was done correctly, because the debounce will treat all the calling signals to the interruption - commonly more then thousands calls for each second in a push button - so that they stay regular. After the treatment of the interrupt signals, it will be checked if the button is still pressed or not. If yes we turn the led on, if not the led will be turned off.
Schematic
Part List
- 1 LED
- 1 push button
- 2 220 ohm resistors
- 1 Protoboard
- 5 copper wires (tinned) or jumpers
Assembly
Solutions
Tools
- AVR GCC and tools
- Arduino IDE