tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/makeybutton/buffer.go (about) 1 package makeybutton 2 3 const ( 4 bufferSize = 3 5 maxSumAllowed = 4 6 ) 7 8 // Buffer is a buffer to keep track of the most recent readings for a button. 9 // in bit form. 10 type Buffer struct { 11 data [bufferSize]byte 12 byteCounter int 13 bitCounter int 14 sum int 15 } 16 17 // NewBuffer returns a new buffer. 18 func NewBuffer() *Buffer { 19 return &Buffer{} 20 } 21 22 // Sum returns the sum of all measurements 23 func (b *Buffer) Sum() int { 24 return b.sum 25 } 26 27 // Put stores a boolean button state into the buffer. 28 func (b *Buffer) Put(val bool) { 29 currentMeasurement, oldestMeasurement := b.updateData(val) 30 b.updateCounters() 31 32 if currentMeasurement != 0 && b.sum < maxSumAllowed { 33 b.sum++ 34 } 35 36 if oldestMeasurement != 0 && b.sum > 0 { 37 b.sum-- 38 } 39 } 40 41 func (b *Buffer) updateData(val bool) (byte, byte) { 42 currentByte := b.data[b.byteCounter] 43 oldestMeasurement := (currentByte >> b.bitCounter) & 0x01 44 45 if val { 46 currentByte |= (1 << b.bitCounter) 47 } else { 48 currentByte &= ^(1 << b.bitCounter) 49 } 50 51 b.data[b.byteCounter] = currentByte 52 53 return (currentByte >> b.bitCounter) & 0x01, oldestMeasurement 54 } 55 56 func (b *Buffer) updateCounters() { 57 b.bitCounter++ 58 if b.bitCounter == 8 { 59 b.bitCounter = 0 60 b.byteCounter++ 61 if b.byteCounter == bufferSize { 62 b.byteCounter = 0 63 } 64 } 65 }