STM32L0: Fast processing of an analog sinusoidal signal
There is an analog watchdog in the ADC just for this purpose.

From the Reference Manual:


  Analog window watchdog (AWDEN, AWDSGL, AWDCH, AWD_HTR/LTR, AWD)
  
  The AWD analog watchdog feature is enabled by setting the AWDEN bit in the
  ADC_CFGR1 register. It is used to monitor that either one selected channel or all enabled
  channels (see Table 62: Analog watchdog channel selection) remain within a configured
  voltage range (window) as shown in Figure 46.
  
  The AWD analog watchdog status bit is set if the analog voltage converted by the ADC is
  below a lower threshold or above a higher threshold. These thresholds are programmed in
  the 12 least significant bits of the ADC_HTR and ADC_LTR 16-bit registers. An interrupt can
  be enabled by setting the AWDIE bit in the ADC_IER register.


So it can generate an interrupt. The interrupt handler should


read the last converted value
compare it with a threshold value
set the output pin accordingly
and do the rest afterwards


It would take perhaps 10 to 20 clock cycles. With the interrupt entry latency (15-20 cycles) it should take maybe 10 microseconds at 4 MHz, way less than your goal.

Give the ADC interrupt handler higher priority than any other handler (note that value 0 is the highest priority), and avoid HAL like a plague for time-critical tasks. There are detailed descriptions for every step in the Reference Manual, even some code examples without HAL.

You can store the converted values in memory using DMA, and evaluate them in the background to adjust the thresholds. The problem is that the ADC must be stopped to update the threshold register, and restarted afterwards. You can syncronise that with the interrupt, i.e. doing it in the interrupt handler just after the analog watchdog event.



Using the on-chip comparators with some external circuitry

Based on @ScottSeidman's idea in the comments above. There are two comparators in the MCU, they can be used to detect the lower and upper thresholds. Set the compare levels with two PWMs and RC filters, and connect their output to an RS flip-flop to have a single digital output, which can be fed back to a counter input pin.







simulate this circuit &ndash; Schematic created using CircuitLab