// Variável externa (simulando uso de extern)
extern int contadorGlobal;
// Definições de pinos e constantes
const int botao = 2;
const int led = 13;
const unsigned long intervaloDebounce = 500;
// Variável volátil modificada por interrupção
volatile bool estadoBotao = false;
volatile unsigned long ultimoTempoInterrupcao = 0; // Para debounce
// Declaração de variável de registrador
register int contadorRapido = 0;
// Variável compartilhada usada na função não reentrante
int variavelCompartilhada = 0;
// Função de interrupção
void interrupcao() {
unsigned long tempoAtual = millis();
// Se o tempo decorrido for menor que o intervalo de debounce, ignore
if (tempoAtual - ultimoTempoInterrupcao < intervaloDebounce) {
return;
}
// Sinaliza que o botão foi pressionado e armazena o tempo
estadoBotao = true;
ultimoTempoInterrupcao = tempoAtual;
// estadoBotao = !estadoBotao;
}
// Função reentrante (não usa variáveis globais)
int funcaoReentrante(int x) {
return x * 2;
}
// Função não reentrante (usa variável estática)
int funcaoNaoReentrante(int x) {
static int acumulador = 0;
acumulador += x;
return acumulador;
}
// Função segura (evita reentrada)
void funcaoSegura() {
static bool emExecucao = false;
if (emExecucao) return;
emExecucao = true;
// Modifica variável compartilhada de forma protegida
variavelCompartilhada++;
emExecucao = false;
}
void setup() {
pinMode(botao, INPUT_PULLUP);
pinMode(led, OUTPUT);
// Configura interrupção no botão
attachInterrupt(digitalPinToInterrupt(botao), interrupcao, FALLING);
Serial.begin(9600);
}
void loop() {
funcaoSegura();
static int estadoLed = LOW;
if (estadoBotao) {
estadoLed = !estadoLed;
digitalWrite(led, estadoLed);
Serial.println("Botão pressionado! Novo estado do LED: ");
Serial.println(estadoLed ? "ON" : "OFF");
estadoBotao = false;
}
// Exemplo de função reentrante
int resultado = funcaoReentrante(5);
Serial.print("Função reentrante (5 * 2): ");
Serial.println(resultado);
// Exemplo de função não reentrante
int soma = funcaoNaoReentrante(3);
Serial.print("Função não reentrante (acumulado +3): ");
Serial.println(soma);
delay(500);
}