VnRobo
AboutPricingBlogContact
🇻🇳VISign InStart Free Trial
🇻🇳VI
VnRobo logo

AI infrastructure for next-generation industrial robots.

Product

  • Features
  • Pricing
  • Knowledge Base
  • Services

Company

  • About Us
  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 VnRobo. All rights reserved.

Made with♥in Vietnam
VnRobo
AboutPricingBlogContact
🇻🇳VISign InStart Free Trial
🇻🇳VI
  1. Home
  2. Blog
  3. Programming Robot Control with Python: From Basics to Advanced
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 TuanAugust 1, 20254 min readUpdated: Jun 16, 2026

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
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
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

  • Introduction to ROS 2: Next-Generation Robot Programming Framework
  • Edge AI with NVIDIA Jetson: Deploying AI on Embedded Devices
  • SLAM and Navigation: How Robots Localize and Move
NT

Nguyễn Anh Tuấn

Robotics & AI Engineer. Building VnRobo — sharing knowledge about robot learning, VLA models, and automation.

Khám phá VnRobo

Fleet MonitoringROS 2 IntegrationAMR Solutions

Related Posts

Manipulation
robot-armpythonprogramming
manipulation

Inverse Kinematics robot arm 6 bậc: Lý thuyết + Python

Giải bài toán IK cho robot arm 6-DOF — từ DH parameters, forward kinematics đến numerical IK solver với Python và NumPy.

1/26/202610 min read
NT
Tutorial
Classical Robot Arm Control: Roadmap & Controller Stack
robot-armclassical-controlmotion-planningPart 1
manipulation

Classical Robot Arm Control: Roadmap & Controller Stack

Bản đồ nhập môn controller robot arm cổ điển: MoveJ/MoveL, planner, trajectory, servo loop, C++/Python và thư viện 2026.

6/13/202616 min read
NT
Tutorial
Dựng project C++ cho robot controller: CMake & Eigen
robot-armcmakeeigenPart 2
manipulation

Dựng project C++ cho robot controller: CMake & Eigen

Setup C++/CMake/Eigen, GoogleTest và Python env để làm nền cho robot arm controller trong toàn bộ series.

6/13/202614 min read
NT
VnRobo logo

AI infrastructure for next-generation industrial robots.

Product

  • Features
  • Pricing
  • Knowledge Base
  • Services

Company

  • About Us
  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 VnRobo. All rights reserved.

Made with♥in Vietnam