-assign dbg = ssp_frame;
-
-assign adc_clk = ~pck_divclk;
-
-// Toggle the output with hysteresis
-// Set to high if the ADC value is above 200
-// Set to low if the ADC value is below 64
-reg is_high;
-reg is_low;
-reg output_state;
-
-always @(posedge pck0)
-begin
- if((pck_cnt == 8'd7) && !pck_divclk) begin
- is_high = (adc_d >= 8'd190);
- is_low = (adc_d <= 8'd70);
- end
-end
-
-always @(posedge is_high or posedge is_low)
-begin
- if(is_high)
- output_state <= 1'd1;
- else if(is_low)
- output_state <= 1'd0;
-end
-
-assign ssp_frame = output_state;
+
+// filter the ADC values
+wire data_rdy;
+wire [7:0] adc_filtered;
+assign adc_clk = pck0;
+lp20khz_1MSa_iir_filter adc_filter(pck0, adc_d, data_rdy, adc_filtered);
+
+// detect edges
+wire [7:0] high_threshold, highz_threshold, lowz_threshold, low_threshold;
+wire [7:0] max, min;
+wire edge_state, edge_toggle;
+lf_edge_detect lf_ed(pck0, adc_filtered, lf_ed_threshold,
+ max, min,
+ high_threshold, highz_threshold, lowz_threshold, low_threshold,
+ edge_state, edge_toggle);
+
+assign dbg = lf_ed_toggle_mode ? edge_toggle : edge_state;
+
+assign ssp_frame = lf_ed_toggle_mode ? edge_toggle : edge_state;