# Adafruit QT Py touch demo

# To run, this file should be copied to the CIRCUITPY drive as code.py

# related docs:

# https://docs.circuitpython.org/en/latest/shared-bindings/touchio/index.html
# https://learn.adafruit.com/adafruit-qt-py/pinouts#capacitive-touch-pins-3073279
# https://learn.adafruit.com/adafruit-qt-py/circuitpython-internal-rgb-led
# https://www.adafruit.com/product/4600

import time
import board
import digitalio
import touchio
import neopixel_write

#------------------------------------------------------------------
# A0, A1, A2, A3, A6 (TX), A7 (RX) can be capacitive touch pins without the need for a separate driver pin.
touch_inputs = [touchio.TouchIn(pin) for pin in [board.A0, board.A1, board.A2, board.A3, board.A6, board.A7]]

# Each touch sensor emits a different color.
colors = ((255,   0,   0), # red
          (255, 255,   0), # yellow
          (  0, 255,   0), # green
          (  0, 255, 255), # cyan          
          (  0,   0, 255), # blue
          (255,   0, 255), # magenta
          )

black = (0,0,0)

#------------------------------------------------------------------
# The NeoPixel uses one GPIO output for sending color data.
pixels = digitalio.DigitalInOut(board.NEOPIXEL)
pixels.direction = digitalio.Direction.OUTPUT

# The NeoPixel API needs a data object implementing the buffer protocol.
frame_buffer = bytearray(3)

# Helper function to accept a color tuple.  The NeoPixel has GRB color ordering.
def set_color(color):
    frame_buffer[0] = color[1]
    frame_buffer[1] = color[0]
    frame_buffer[2] = color[2]
    neopixel_write.neopixel_write(pixels, frame_buffer)
        
# Turn on the NeoPixel.
power = digitalio.DigitalInOut(board.NEOPIXEL_POWER)
power.direction = digitalio.Direction.OUTPUT
power.value = True
        
#------------------------------------------------------------------
# Constantly read the touch sensors and emit color.

last_touch = None

while True:

    # read all the touch sensors; this will produce a list of Boolean values
    active = [sensor.value for sensor in touch_inputs]

    # if any are active, set the Neopixel color based on the first
    if any(active):
        idx = active.index(True)
        set_color(colors[idx])

        if last_touch != idx:
            print("Touch on", idx)
            last_touch = idx

    else:
        set_color(black)
        last_touch = None
