# Made by ChatGPT, modified by Claire Chaikin-Bryan April 2023 

import serial
import time
import random
import RPi.GPIO as GPIO
import time

# Set up GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

# Set up PWM
pwm = GPIO.PWM(18, 50) # pin 18, frequency 50Hz
pwm.start(0) # start with duty cycle of 0

# Define a function to set the angle of the servo
def set_angle(angle):
    duty = angle / 18 + 2 # calculate duty cycle from angle
    GPIO.output(18, True) # turn on the servo
    pwm.ChangeDutyCycle(duty) # set duty cycle
    time.sleep(1) # wait for servo to move
    GPIO.output(18, False) # turn off the servo
    pwm.ChangeDutyCycle(0) # set duty cycle to 0


ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1) # Replace ttyACM0 with the appropriate port for your Arduino Uno

def send_gcode(gcode):
    ser.write(str.encode(gcode + '\n'))
    grbl_out = ser.readline().decode('utf-8').strip()
    print('sent: ' + gcode)
    print('received: ' + grbl_out)

send_gcode('$X') # send the kill alarm command to reset the Arduino Uno

send_gcode('G21') # set units to millimeters

# set the starting position of the machine
start_x = 0
start_y = 0

# set the movement speed of the machine
speed = 3000

#create counter for servo
a = 0

set_angle(90)

while True:
    for a in range (0, 5):
        # Move servo to 0 degrees
        set_angle(0)

        # loop to draw a continuous line
        x = random.randint(-50, 50)
        x = round(x / 10) * 10
        y = random.randint(-100, 80)
        y = round(x / 10) * 10

        send_gcode('G1 X{} Y{} F{}'.format(x, y, speed))

        # wait for the machine to finish moving
        time.sleep(3)
        a = a + 1
    for a in range (5, 10):
        # Move servo to 0 degrees
        set_angle(120)
        
    # loop to draw a continuous line
        x = random.randint(-50, 50)
        x = round(x / 10) * 10
        y = random.randint(-100, 80)
        y = round(x / 10) * 10

        send_gcode('G1 X{} Y{} F{}'.format(x, y, speed))

        # wait for the machine to finish moving
        time.sleep(3)
        a = a - 1

# Clean up GPIO
pwm.stop()
GPIO.cleanup()