#define timer0
const int senyal_output = 23;
const int senyal_entrada = 18;
const int sube = 32;
const int baja = 33;
const float frec_senyal = 5.8;
const float periodo_senyal_ms = 1000 * (1/frec_senyal);
int valor_prescaler=240;
volatile float nflancos=0;
volatile float valor_frec=0;
volatile unsigned long valor_cuenta=1e6;
volatile float cuenta=0;
hw_timer_t * timer = NULL;
void IRAM_ATTR ISR_senyal(){
nflancos++;
}
void IRAM_ATTR finTimer() {
cuenta=1;
}
void ISR_sube(){
noInterrupts();
timerAlarmDisable(timer);
valor_cuenta +=1e6;
timerAlarmWrite(timer, valor_cuenta, true);
timerWrite(timer, 0);
timerAlarmEnable(timer);
interrupts();
}
void ISR_baja(){
timerAlarmDisable(timer);
valor_cuenta -=1e6;
timerAlarmWrite(timer, valor_cuenta, true);
timerWrite(timer, 0);
timerAlarmEnable(timer);
}
void setup() {
pinMode(senyal_output, OUTPUT);
Serial.begin(115200);
attachInterrupt(digitalPinToInterrupt(18), ISR_senyal, FALLING);
attachInterrupt(digitalPinToInterrupt(32), ISR_sube, FALLING);
attachInterrupt(digitalPinToInterrupt(33), ISR_baja, FALLING);
timer = timerBegin(0, valor_prescaler, true);
timerAttachInterrupt(timer, &finTimer, true);
timerAlarmWrite(timer, valor_cuenta , true);
timerAlarmEnable(timer);
}
unsigned long tp1=0;
unsigned long tp2=0;
unsigned long current_time;
void loop(){
delay(1);
current_time=millis();
if( current_time-tp1 > periodo_senyal_ms/2){
digitalWrite(senyal_output, !digitalRead(senyal_output) );
tp1=millis(); // reset a tp1
}
if( cuenta==1){
cuenta=0;
valor_frec=nflancos/(valor_cuenta/1000);//esto no se
Serial.printf("Frec:%4.5f - nflancos: %.0f en %d ms \n ", valor_frec, nflancos, valor_cuenta);
nflancos=0;
tp2=millis();
}
}