Tutorial - Code

From RoboWiki
Revision as of 12:03, 6 June 2024 by Robot (talk | contribs) (Created page with "Return back to project page: Line Following Car - Jakub Vojtek Python code for the Line Following Car project: <syntaxhig...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Return back to project page: Line Following Car - Jakub Vojtek

Python code for the Line Following Car project:

 

# All of buildhat documentation (source): https://buildhat.readthedocs.io/en/latest/hub_index.html

from buildhat import Motor, MotorPair, DistanceSensor, ColorSensor, ForceSensor
import time
import cv2
import pygame
from pynput import keyboard as kb


# Comment out motor or motorPair you cant run both because we don't have enough ports (add arguments from your ports)
motor = Motor('A')
motorPair = MotorPair('A', 'B')
distanceSensor = DistanceSensor('B')
colorSensor = ColorSensor('C')
forceSensor = ForceSensor('D')

# camera setup
cam_width = 480
cam_height = 360
camera = cv2.VideoCapture(0)
camera.set(cv2.CAP_PROP_FRAME_WIDTH, cam_width)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, cam_height)


# Motor starts and runs until turned off
def run_infinite_motor():
    motor.start(30)
    time.sleep(2)
    motor.start(-30)
    time.sleep(2)
    motor.stop()


# Run motor for specific time or angle
def run_motor():
    motor.run_for_degrees(180, blocking=True)  # blocking= True/False determines if rest of the code should wait until motor movement stopped
    time.sleep(1)
    motor.run_for_degrees(-180)
    time.sleep(1)
    motor.run_for_seconds(1)
    time.sleep(1)
    motor.run_to_position(0)
    time.sleep(1)
    motor.run_for_rotations(1)  # == motor.run_for_degrees(360)


# MotorPair starts and runs until turned off
def run_infinite_motorPair():
    motorPair.start(30, 30)
    time.sleep(2)
    motorPair.stop()
    time.sleep(2)
    motorPair.start(-30, 30)
    time.sleep(2)
    motorPair.stop()


# Run motorPair for specific time or angle
def run_motorPair():
    motorPair.run_for_degrees(180)
    time.sleep(1)
    motorPair.run_for_degrees(-180)
    time.sleep(1)
    motorPair.run_for_seconds(1)
    time.sleep(1)
    motorPair.run_to_position(0, 0)
    time.sleep(1)
    motorPair.run_for_rotations(1)  # == motorPair.run_for_degrees(360)


def distance_functions():
    distanceSensor.wait_for_in_range(50)
    motor.run_for_rotations(1)

    distanceSensor.wait_for_out_of_range(100)
    motor.run_for_rotations(2)


def handle_in(distance):
    motor.run_for_rotations(1)
    print("in range", distance)


def handle_out(distance):
    motor.run_for_rotations(-1)
    print("out of range", distance)


distanceSensor.when_in_range = handle_in
distanceSensor.when_out_of_range = handle_out


def color_functions():
    print(colorSensor.get_color())
    time.sleep(2)
    colorSensor.wait_until_color("Red")
    print("Red color detected. Continue...")
    colorSensor.wait_for_new_color()
    print("New color detected. Continue...")
    print("Value of reflected light: ", colorSensor.get_reflected_light())
    print("Value of ambient light: ", colorSensor.get_ambient_light())


def force_functions():
    print(forceSensor.get_force())   # use in while loop to see how the force changes
    print(forceSensor.get_peak_force())  # highest force detected
    time.sleep(2)
    print(forceSensor.is_pressed())  # True/False
    time.sleep(2)
    forceSensor.wait_until_pressed()
    print("Force detected. Continue...")
    forceSensor.wait_until_released()
    print("Force released. Continue...")


def handle_pressed(force):
    motor.run_for_rotations(1)
    print("pressed: ", force)


def handle_released(force):
    motor.run_for_rotations(-1)
    print("released: ", force)


forceSensor.when_pressed = handle_pressed
forceSensor.when_released = handle_released


# Show camera feed
def generate_feed():
    while True:
        ret, frame = camera.read()
        if not ret:
            break
        cv2.imshow('frame', frame)

        # Exit if 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    camera.release()
    cv2.destroyAllWindows()


# Show pygame window
def pygame_window():
    pygame.init()
    pygame.display.set_caption('PyGame Window')
    screen = pygame.display.set_mode((800, 600))
    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:  # close the window [X]
                running = False
                print("Closing pygame window")

    pygame.quit()

# keyboard controls
def on_press(key):
    if key == kb.Key.left:
        print("left")
    elif key == kb.Key.right:
        print("right")
    elif key == kb.Key.up:
        print("up")
    elif key == kb.Key.down:
        print("down")


listener = kb.Listener(on_press=on_press)
listener.start()


if __name__ == '__main__':
    pygame_window()
    generate_feed()