← Back to Blog
manipulationrobot-armpythonprogramming

Programming Robot Control with Python: From Basics to Advanced

Python is the most popular language in robotics thanks to rich library ecosystem. Learn how to control robots from GPIO to kinematics.

Nguyen Anh Tuan1 tháng 8, 20254 min read
Programming Robot Control with Python: From Basics to Advanced

Why Python for Robotics?

Python isn't the fastest language, but it's the most efficient for robot development. Reason: enormous library ecosystem (OpenCV, NumPy, SciPy), excellent ROS 2 integration, and development time 3-5x faster than C++. In practice, most high-level control logic is written in Python, with only high-speed control loops needing C++. Python is also the primary language when deploying Edge AI on NVIDIA Jetson.

Programming Python on robot control computer

Basic Hardware Control

GPIO with Raspberry Pi

import RPi.GPIO as GPIO
import time

# Configure pins
MOTOR_PIN_1 = 17
MOTOR_PIN_2 = 27
ENABLE_PIN = 22

GPIO.setmode(GPIO.BCM)
GPIO.setup(MOTOR_PIN_1, GPIO.OUT)
GPIO.setup(MOTOR_PIN_2, GPIO.OUT)
GPIO.setup(ENABLE_PIN, GPIO.OUT)

# PWM for speed control
pwm = GPIO.PWM(ENABLE_PIN, 1000)  # 1kHz
pwm.start(0)

def set_motor(speed: float, direction: str = "forward"):
    """Control DC motor. speed: 0-100, direction: forward/backward"""
    GPIO.output(MOTOR_PIN_1, direction == "forward")
    GPIO.output(MOTOR_PIN_2, direction == "backward")
    pwm.ChangeDutyCycle(min(max(speed, 0), 100))

# Run motor at 50% speed for 3 seconds
set_motor(50, "forward")
time.sleep(3)
set_motor(0)

Serial Communication with Arduino

import serial
import struct

class RobotSerial:
    def __init__(self, port="/dev/ttyUSB0", baudrate=115200):
        self.ser = serial.Serial(port, baudrate, timeout=1)

    def send_velocity(self, linear: float, angular: float):
        """Send linear and angular velocity to robot"""
        packet = struct.pack('<ff', linear, angular)
        checksum = sum(packet) & 0xFF
        self.ser.write(b'\xAA' + packet + bytes([checksum]))

    def read_encoders(self) -> tuple:
        """Read encoder values from Arduino"""
        self.ser.write(b'\xBB\x01')
        data = self.ser.read(8)
        if len(data) == 8:
            left, right = struct.unpack('<ii', data)
            return left, right
        return None

PID Control Loop

PID controller is the most fundamental control algorithm but highly effective:

class PIDController:
    def __init__(self, kp: float, ki: float, kd: float, output_limits=(-100, 100)):
        self.kp, self.ki, self.kd = kp, ki, kd
        self.limits = output_limits
        self.integral = 0.0
        self.prev_error = 0.0

    def compute(self, setpoint: float, measurement: float, dt: float) -> float:
        error = setpoint - measurement
        self.integral += error * dt
        derivative = (error - self.prev_error) / dt if dt > 0 else 0
        self.prev_error = error

        output = self.kp * error + self.ki * self.integral + self.kd * derivative
        return max(self.limits[0], min(self.limits[1], output))

# Example: keep robot moving straight along line
pid = PIDController(kp=2.0, ki=0.1, kd=0.5)

Inverse Kinematics with NumPy

Calculate joint angles to move end-effector to desired position:

import numpy as np

def ik_2dof(x: float, y: float, l1: float, l2: float):
    """Inverse kinematics for 2-DOF robot"""
    dist = np.sqrt(x**2 + y**2)
    if dist > l1 + l2:
        raise ValueError("Position out of reach")

    cos_q2 = (x**2 + y**2 - l1**2 - l2**2) / (2 * l1 * l2)
    q2 = np.arccos(np.clip(cos_q2, -1, 1))
    q1 = np.arctan2(y, x) - np.arctan2(l2 * np.sin(q2), l1 + l2 * np.cos(q2))

    return np.degrees(q1), np.degrees(q2)

# Robot arm with 2 links, each 15cm
theta1, theta2 = ik_2dof(x=0.2, y=0.1, l1=0.15, l2=0.15)
print(f"Joint 1: {theta1:.1f}°, Joint 2: {theta2:.1f}°")

Robot arm performing inverse kinematics and motion control

Computer Vision for Robot

Combine OpenCV for object recognition, similar technique in automatic quality inspection with Computer Vision:

import cv2

def detect_colored_object(frame, lower_hsv, upper_hsv):
    """Detect object by color, return center (cx, cy)"""
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, lower_hsv, upper_hsv)
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    if contours:
        largest = max(contours, key=cv2.contourArea)
        M = cv2.moments(largest)
        if M["m00"] > 0:
            cx = int(M["m10"] / M["m00"])
            cy = int(M["m01"] / M["m00"])
            return cx, cy
    return None

Practical Advice

  1. Start with simulation: Use Gazebo or PyBullet before running on real robot
  2. Separate logic into modules: sensor, controller, planner should be separate classes
  3. Log everything: Record sensor data for offline debugging, use logging module instead of print
  4. Type hints: Always use type annotations for maintainable code

Python allows you to move from prototype to product quickly. Combined with ROS 2 and scientific libraries, you have enough tools to build complete robot systems.

Related Articles

Related Posts

ISO 10218 thực hành: Risk Assessment cho robot hàn
safetyrobot-armstandards

ISO 10218 thực hành: Risk Assessment cho robot hàn

Hướng dẫn thực hiện risk assessment theo ISO 10218 cho cell robot hàn — từ hazard identification đến safety measures.

28/3/202613 min read
ROS 2 từ A đến Z (Phần 4): ros2_control và Hardware
ros2tutorialrobot-armPart 4

ROS 2 từ A đến Z (Phần 4): ros2_control và Hardware

Kết nối ROS 2 với phần cứng thực — viết hardware interface cho motor driver và đọc encoder với ros2_control framework.

26/3/202611 min read
Multi-robot Coordination: Thuật toán phân công task
fleetamrprogramming

Multi-robot Coordination: Thuật toán phân công task

Các thuật toán phân công nhiệm vụ cho đội robot — từ Hungarian algorithm, auction-based đến RL-based task allocation.

20/3/202612 min read