tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/examples/touch/resistive/fourwire/main.go (about)

     1  // demo of 4-wire touchscreen as described in app note:
     2  // http://ww1.microchip.com/downloads/en/Appnotes/doc8091.pdf
     3  package main
     4  
     5  import (
     6  	"machine"
     7  	"math"
     8  
     9  	"tinygo.org/x/drivers/touch"
    10  	"tinygo.org/x/drivers/touch/resistive"
    11  )
    12  
    13  var (
    14  	resistiveTouch = new(resistive.FourWire)
    15  )
    16  
    17  const (
    18  	Xmin = 750
    19  	Xmax = 325
    20  	Ymin = 840
    21  	Ymax = 240
    22  )
    23  
    24  func main() {
    25  
    26  	// configure touchscreen
    27  	machine.InitADC()
    28  	resistiveTouch.Configure(&resistive.FourWireConfig{
    29  		YP: machine.TOUCH_YD, // y+
    30  		YM: machine.TOUCH_YU, // y-
    31  		XP: machine.TOUCH_XR, // x+
    32  		XM: machine.TOUCH_XL, // x-
    33  	})
    34  
    35  	last := touch.Point{}
    36  
    37  	// loop and poll for touches, including performing debouncing
    38  	debounce := 0
    39  	for {
    40  
    41  		point := resistiveTouch.ReadTouchPoint()
    42  		touch := touch.Point{}
    43  		if point.Z>>6 > 100 {
    44  			touch.X = mapval(point.X>>6, Xmin, Xmax, 0, 240)
    45  			touch.Y = mapval(point.Y>>6, Ymin, Ymax, 0, 320)
    46  			touch.Z = point.Z >> 6 / 100
    47  		} else {
    48  			touch.X = 0
    49  			touch.Y = 0
    50  			touch.Z = 0
    51  		}
    52  
    53  		if last.Z != touch.Z {
    54  			debounce = 0
    55  			last = touch
    56  		} else if math.Abs(float64(touch.X-last.X)) > 4 ||
    57  			math.Abs(float64(touch.Y-last.Y)) > 4 {
    58  			debounce = 0
    59  			last = touch
    60  		} else if debounce > 1 {
    61  			debounce = 0
    62  			HandleTouch(last)
    63  		} else if touch.Z > 0 {
    64  			debounce++
    65  		} else {
    66  			last = touch
    67  			debounce = 0
    68  		}
    69  
    70  	}
    71  }
    72  
    73  // based on Arduino's "map" function
    74  func mapval(x int, inMin int, inMax int, outMin int, outMax int) int {
    75  	return (x-inMin)*(outMax-outMin)/(inMax-inMin) + outMin
    76  }
    77  
    78  func HandleTouch(touch touch.Point) {
    79  	println("touch point:", touch.X, touch.Y, touch.Z)
    80  }