Repository navigation
Expand file tree
/
Copy pathLEDcodeV1.py
More file actions
65 lines (52 loc) · 2.23 KB
/
Copy pathLEDcodeV1.py
File metadata and controls
65 lines (52 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import serial
import time
from gpiozero import Motor # Ensure you have a motor library that provides this class
# Set up serial communication
ser = serial.Serial('/dev/ttyACM0', 9600) # Adjust the port as needed
# Initialize motors
left_motor = Motor(17, 27) # Update pins as necessary
right_motor = Motor(12, 23) # Update pins as necessary
def send_command(command):
ser.write((command + "\n").encode()) # Send command to Micro:bit
def read_track_positions():
while True:
if ser.in_waiting:
data = ser.readline().decode().strip()
process_data(data)
def process_data(data):
if data.startswith("TR"):
right_position = int(data[3:])
print(f"Right Track Position: {right_position}")
elif data.startswith("TL"):
left_position = int(data[3:])
print(f"Left Track Position: {left_position}")
def control_motors(left_speed, right_speed):
# Set motor speeds
if left_speed > 0:
left_motor.forward(left_speed) # Replace with your method for controlling speed
elif left_speed < 0:
left_motor.backward(-left_speed) # Reverse speed
else:
left_motor.stop() # Stop the motor
if right_speed > 0:
right_motor.forward(right_speed) # Replace with your method for controlling speed
elif right_speed < 0:
right_motor.backward(-right_speed) # Reverse speed
else:
right_motor.stop() # Stop the motor
# Example usage to control motors and servos
def control_loop():
while True:
# Example speeds for left and right motors
left_speed = 0.5 # Example value; replace with actual logic
right_speed = 0.5 # Example value; replace with actual logic
control_motors(left_speed, right_speed)
# Optionally send commands to Micro:bit if needed
send_command("PS") # Send some status command
time.sleep(2) # Wait for 2 seconds before the next iteration
if __name__ == "__main__":
try:
control_loop() # Start controlling motors
read_track_positions() # Start reading track positions
except KeyboardInterrupt:
ser.close() # Close the serial connection on exit