Python is excellent for robotics programming due to its simplicity and powerful libraries.
Here's a simple Python script to control a robot:
import time
import math
class Robot:
def __init__(self, name):
self.name = name
self.x = 0
self.y = 0
self.angle = 0
self.battery = 100
def move_forward(self, distance):
"""Move the robot forward by a given distance"""
if self.battery > 0:
self.x += distance * math.cos(self.angle)
self.y += distance * math.sin(self.angle)
self.battery -= 5
print(f"{self.name} moved to ({self.x:.2f}, {self.y:.2f})")
else:
print(f"{self.name} needs charging!")
def turn(self, angle_degrees):
"""Turn the robot by a given angle in degrees"""
self.angle += math.radians(angle_degrees)
print(f"{self.name} turned {angle_degrees} degrees")
def get_position(self):
return (self.x, self.y, math.degrees(self.angle))
# Create and control a robot
my_robot = Robot("R2D2")
my_robot.move_forward(10)
my_robot.turn(90)
my_robot.move_forward(5)
Here's how you might work with sensor data:
import numpy as np
import matplotlib.pyplot as plt
def process_sensor_data(sensor_readings):
"""Process an array of sensor readings"""
# Convert to numpy array for easier manipulation
data = np.array(sensor_readings)
# Calculate statistics
mean_value = np.mean(data)
std_dev = np.std(data)
max_value = np.max(data)
min_value = np.min(data)
# Filter out noise (values beyond 2 standard deviations)
filtered_data = data[np.abs(data - mean_value) <= 2 * std_dev]
return {
'raw_data': data,
'filtered_data': filtered_data,
'stats': {
'mean': mean_value,
'std_dev': std_dev,
'max': max_value,
'min': min_value
}
}
# Example usage
sensor_readings = [23.1, 24.5, 22.8, 25.2, 23.9, 24.1, 23.7, 100.0, 24.3]
result = process_sensor_data(sensor_readings)
print(f"Mean: {result['stats']['mean']:.2f}")
print(f"Filtered readings: {len(result['filtered_data'])} out of {len(result['raw_data'])}")
A typical robot control loop in Python:
import asyncio
from typing import List, Tuple
class RobotController:
def __init__(self):
self.running = False
self.sensors = {}
self.actuators = {}
async def read_sensors(self) -> dict:
"""Read all sensor values asynchronously"""
# Simulate sensor reading
await asyncio.sleep(0.01)
return {
'distance': 15.5,
'temperature': 22.3,
'battery': 85
}
async def control_loop(self):
"""Main robot control loop"""
self.running = True
while self.running:
try:
# Read sensors
sensor_data = await self.read_sensors()
# Make decisions based on sensor data
if sensor_data['distance'] < 10:
print("Obstacle detected! Stopping.")
break
elif sensor_data['battery'] < 20:
print("Low battery! Returning to base.")
break
else:
print(f"All systems normal. Distance: {sensor_data['distance']}")
# Wait before next iteration
await asyncio.sleep(0.1)
except KeyboardInterrupt:
print("Control loop interrupted")
break
self.running = False
# Run the control loop
if __name__ == "__main__":
controller = RobotController()
asyncio.run(controller.control_loop())
Python makes robotics programming accessible and powerful!