// Ejemplo de generación de una señal cuadrada de 2 +xx kHz
//https://wokwi.com/projects/411646978791034881
// the number of the LED pin
#define LED_PIN 23 // GPIO23
#define PULS_PIN 22 // GPIO pulsador - pin interrupcion
#define ENTRADA_PIN 21 // GPIO signal input
// setting Timer y PWM properties
hw_timer_t * timer = NULL; // estructura de datos del timer
const int timer_tics = 1e6; // tics/seg valor del contador del timer - cada 1 microsegundos
float gen_tics = 250; // conmutar output cada 0.25 ms = 250 microsegundos
// ISR finTimer
void IRAM_ATTR finTimer() { // no incluir delay o while(condicion)
static int valor=0;
valor=!valor;
if(valor) digitalWrite(LED_PIN, LOW); //OFF;
else digitalWrite(LED_PIN, HIGH); //ON;
}
volatile unsigned long tic; // variable para almacenar el tiempo de la última pulsación
#define seg_anti_rebote 0.3 // en segundos
void IRAM_ATTR ISR_pulsador(){
if(tic+seg_anti_rebote < millis()){ // si ya se ha pasado esos seg_anti_rebote
tic=millis();
gen_tics = gen_tics -5; // generacion onda mayor frecuencia
if(gen_tics<10) gen_tics=10; // valor mínimo
timerAlarm(timer, gen_tics, true, 0); // se solicita ISR cada 150 microseg
}
}
volatile int cuenta_flancos; // variable para eliminar rebotes del pulsador
void IRAM_ATTR ISR_entrada(){
cuenta_flancos=cuenta_flancos+1; // ascendentes y descendentes - CHANGE
}
void setup(){
Serial.begin(115200);
Serial.printf("\n\n // Ejemplo de generación de una señal cuadrada de 2 +xx kHz \n");
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH); //encendido;
delay(1000);
digitalWrite(LED_PIN, LOW); //apagado;
delay(1000);
pinMode(PULS_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PULS_PIN), ISR_pulsador, FALLING);
// mode: LOW / HIGH / CHANGE / FALLING / RISING
pinMode(ENTRADA_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ENTRADA_PIN), ISR_entrada, CHANGE);
// mode: LOW / HIGH / CHANGE / FALLING / RISING
cuenta_flancos=0;
// configurar timer a esta frecuencia => p.e. a 10 MHz
timer = timerBegin(timer_tics); // how quickly the timer counter is “ticking”.
timerAttachInterrupt(timer, &finTimer);
// Set alarm to call finTimer function - each XX ticks
// Repeat the alarm (third parameter) with unlimited count = 0 (fourth parameter).
timerAlarm(timer, gen_tics, true, 0); // se solicita ISR cada 150 microseg
timerRestart(timer);
Serial.printf("\nTimer configurado para generar 2 kHz \n");
tic=millis();
}
void loop(){
float freq_teorica= (timer_tics / gen_tics) /2.0;
Serial.printf("Valor frecuencia (%.2f Hz teoricamente): %d Hz\n", freq_teorica, cuenta_flancos/2);
cuenta_flancos=0;
// Serial.printf("antirebote: %d \n", antirebote);
delay(1000); // cada 2 segundos indica el valor configurado
}