import board
import busio
import time
import os
import json
import RPi.GPIO as GPIO
from random import randint
import board
import neopixel

# I2C setup
from adafruit_cap1188.i2c import CAP1188_I2C
i2c = busio.I2C(board.SCL, board.SDA)
cap = CAP1188_I2C(i2c)

# Setup servo
servoPIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(servoPIN, GPIO.OUT)

p = GPIO.PWM(servoPIN, 50)  # GPIO 17 for PWM with 50Hz
p.start(2.5)  # Initialization

# On a Raspberry pi, use this instead, not all pins are supported
pixel_pin = board.D12

# The number of NeoPixels
num_pixels = 4

# The order of the pixel colors - RGB or GRB. Some NeoPixels have red and green reversed!
# For RGBW NeoPixels, simply change the ORDER to RGBW or GRBW.
ORDER = neopixel.RGB

pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER)



# Recalibrate the capacitive touch sensors 
for i in range(1, 9):
    cap[i].recalibrate()
    time.sleep(1)
    print(i)



while True:
    pixels.fill((0, 0, 255))
    pixels.show()
   
    p.ChangeDutyCycle(0)
    for i in range(1, 9):
        if cap[i].value:
            print("Pin {} touched!".format(i))

        # Green planet that launches rocket           
        if cap[1].value:
            print('Cap 1 Touched, moving servo')
            ##            os.system('mpg123 /home/pi/Desktop/music/rocket.mp3')
            pixels.fill((255, 0, 0))
            pixels.show()
            p.ChangeDutyCycle(12.5)
            time.sleep(3)
            p.ChangeDutyCycle(2.5)
            time.sleep(3)

        # Hairy monster on the left        
        if cap[3].value:
            print('Cap 3 Touched')
            ## os.system('mpg123 /home/pi/Desktop/music/monster.mp3')
            pixels.fill((66, 239, 245))
            pixels.show()
            time.sleep(3)

        # Blobby monster on the right       
        if cap[5].value:
            print('Cap 5 Touched')
            ##            os.system('mpg123 /home/pi/Desktop/music/robot.mp3')
            pixels.fill((242, 66, 245))
            pixels.show()
            time.sleep(3)

        # Orange planet        
        if cap[8].value:
            print('Cap 8 Touched')
            ##os.system('mpg123 /home/pi/Desktop/music/space.mp3')
            pixels.fill((128,255, 0))
            pixels.show()
            time.sleep(3)
            

