diff --git a/autotune.go b/autotune.go index b18e8a29..e037580b 100644 --- a/autotune.go +++ b/autotune.go @@ -37,7 +37,10 @@ type autoTune struct { // Sample adds a signal sample to the pulse buffer func (tune *autoTune) Sample(bit bool, seq uint32) { - tune.pulses[seq%maxAutoTuneSamples] = pulse{bit, seq} + // ensure seq is in range [pulses[0].seq, pulses[0].seq + maxAutoTuneSamples] + if seq >= tune.pulses[0].seq && seq <= tune.pulses[0].seq+maxAutoTuneSamples { + tune.pulses[seq%maxAutoTuneSamples] = pulse{bit, seq} + } } // Find a period for a given signal diff --git a/autotune_test.go b/autotune_test.go index 75e61696..2c933c27 100644 --- a/autotune_test.go +++ b/autotune_test.go @@ -66,4 +66,20 @@ func TestAutoTune(t *testing.T) { } assert.Equal(t, -1, tune.FindPeriod(true)) assert.Equal(t, 4, tune.FindPeriod(false)) + + // minimal test + tune = autoTune{} + for i := 0; i < 1024; i++ { + if i%maxAutoTuneSamples == 0 { + tune.Sample(false, uint32(i)) + } else { + tune.Sample(true, uint32(i)) + } + } + assert.NotEqual(t, 0, tune.pulses[0].seq) + minSeq := tune.pulses[0].seq + t.Log("minimal seq", tune.pulses[0].seq) + + tune.Sample(false, minSeq-1) + assert.Equal(t, minSeq, tune.pulses[0].seq) }