from machine import Pin, SoftI2C

# A4988 work based on https://wokwi.com/projects/397750005824230401
from a4988 import A4988  # Importing the A4988 class from a4988.py

# LCD work based on https://wokwi.com/projects/390084353519159297
from i2c_lcd import I2cLcd

# Create motors from A4988 class
stepper0 = A4988(0,1)
stepper1 = A4988(20,21)
print("Starting stepper motor test.")
speed = 200

# Set up buttons
button0 = Pin(2, Pin.IN, Pin.PULL_UP)
button1 = Pin(12, Pin.IN, Pin.PULL_UP)

# Starting buttons state
# Buttons go to 0 when pushed
lastState0 = 1
lastState1 = 1

# Starting counts
count0 = 0
count1 = 0

# Pins for LCD display
sdaPIN = 18
sclPIN = 19

# Set up i2c LCD
i2c = SoftI2C(sda=sdaPIN, scl=sclPIN, freq=10000)

# Scan for display devices
devices = i2c.scan()

# Only one display, set up 2x16 display
lcd = I2cLcd(i2c, devices[0], 2, 16)
lcd.putstr("Start dealing!")



while True:
    
    # Read buttons
    # Pushing button makes value 0
    state0 = button0.value()
    state1 = button1.value()

    # Test for changed state button 1
    if(state0 != lastState0):
      # Test if button pushed
      if state0 == 0:
        # Increment count for player 1 cards
        count0 += 1
        # Print state to terminal
        print(f"Player 1: {count0}\nPlayer 2: {count1}\n")
        # Print motor to deal card
        stepper0.move_sync(100, speed)
        # Clear LCD
        lcd.clear()
        # Put count on LCD
        lcd.putstr(f"Player 1: {count0}\nPlayer 2: {count1}")
      # Set tracked state to current state
      lastState0 = state0

    # Test for changed state button 2
    if(state1 != lastState1):
      # Test if button pushed
      if state1 == 0:
        # Increment count for player 2 cards
        count1 += 1
        # Print state to terminal
        print(f"Player 1: {count0}\nPlayer 2: {count1}\n")
        # Print motor to deal card
        # Player 2 motor moves opposite direction to P1
        stepper1.move_sync(-100, speed)
        # Clear LCD
        lcd.clear()
        # Put count on LCD
        lcd.putstr(f"Player 1: {count0}\nPlayer 2: {count1}")
      lastState1 = state1
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
A4988
Player 2
Player 1
Push buttons to deal a card
Number of cards dealt
Motors to deal cards
A4988
Player 1
Player 2