// 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
const float gen_tics = 250; // conmutar output cada 0.25 ms = 250 microsegundos
volatile int antirebote; // variable para eliminar rebotes del pulsador
#define seg_anti_rebote 0.3 // en segundos
const int nticks_anti_rebote = 0.3/(250*1e-6); // cada 250 microseg
// 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;
if(antirebote>0) antirebote=antirebote-1; // elimina posibles rebotes hasta de duracion XX ticks
}
void IRAM_ATTR ISR_pulsador(){
if(antirebote==0){
antirebote=nticks_anti_rebote; // duración máxima de los rebotes eliminados (en ticks del timer)
// todo sth.
}
}
volatile int cuenta_flancos; // variable para eliminar rebotes del pulsador
void IRAM_ATTR ISR_entrada(){
cuenta_flancos=cuenta_flancos+1;
}
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
antirebote=0;
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");
}
void loop(){
Serial.printf("Valor frecuencia (2 kHz teoricamente): %d Hz\n", cuenta_flancos/2);
cuenta_flancos=0;
// Serial.printf("antirebote: %d \n", antirebote);
delay(1000); // cada 2 segundos indica el valor configurado
}