Home
Blog
Go Back
TECHNOLOGY
|
8
Min
Updated On
October 23, 2024

Controlling Robots Built with SMD Using Flask API

Introduction: Controlling Robots Built with SMD Using Flask API

This project focuses on the development and control of a robot built with ACROME’s Smart Motion Devices (SMD) using a Flask API. The objective is to establish a robust and flexible control interface that leverages the simplicity and power of Flask, a lightweight Python web framework, to manage the robot's movements and operations effectively.

Smart Motion Devices (SMD) are known for their precision and reliability in motion control applications. These devices are designed to handle the complex requirements of robotic systems, providing high torque and accurate positioning capabilities. By integrating these devices with a Raspberry Pi, the project creates a compact yet powerful platform for robotics experimentation and deployment.

Flask, a micro web framework written in Python, serves as the control interface in this setup. Its lightweight nature makes it an ideal choice for embedded systems like the Raspberry Pi, where resource efficiency is paramount. Flask’s simplicity and ease of use allow for rapid development and deployment of RESTful APIs, which are crucial for controlling the robot in real-time.

In this project, the Flask API handles incoming HTTP requests, processes them, and translates them into specific motor control commands that are sent to the SMD modules. This setup enables remote control of the robot over a network, allowing users to send commands from a web interface, mobile app, or even another machine.

What is an API?

An Application Programming Interface (API) is a set of protocols, tools, and definitions that allow different software components to communicate with each other. In the context of web development and software engineering, an API serves as an intermediary that enables the interaction between different systems, applications, or devices.

At its core, an API defines the methods and data structures that developers can use to interact with a software component, whether it be a web service, a library, or a framework. APIs abstract the underlying complexity of a system and expose only the necessary functions that other applications need to access.

Key Concepts of APIs:

  • Endpoints: An API typically consists of multiple endpoints, each representing a specific function or resource that can be interacted with. For instance, in a web-based API, an endpoint might correspond to a URL that performs a particular action, such as retrieving data or triggering a process.
  • HTTP Methods: In the context of web APIs, the HTTP protocol is commonly used to facilitate communication. The most common HTTP methods include:some text
    • GET: Retrieves data from the server.
    • POST: Submits data to the server to create or update a resource.
    • PUT: Updates an existing resource on the server.
    • DELETE: Removes a resource from the server.
  • Request and Response: When an API is called, a request is sent from the client to the server, often including parameters or data necessary for the operation. The server processes this request and returns a response, which typically includes a status code (such as 200 for success or 404 for not found) and the requested data or a confirmation of the operation.
  • Authentication and Authorization: APIs often require authentication to ensure that the requests are made by legitimate users or systems. This can be handled through various methods such as API keys, OAuth tokens, or JWT (JSON Web Tokens). Authorization determines what actions a user is allowed to perform via the API.

 

  • RESTful APIs: Representational State Transfer (REST) is a popular architecture for designing networked applications, particularly web services. RESTful APIs are stateless, meaning each request from a client to a server must contain all the information needed to understand and process the request. RESTful APIs are designed to be scalable and to use standard HTTP methods.
  • JSON and XML: APIs typically use data formats like JSON (JavaScript Object Notation) or XML (eXtensible Markup Language) to structure the data exchanged between the client and server. JSON is particularly popular due to its lightweight and easy-to-read format.

What Are the Use Cases of APIs and Why Are They Used?

APIs (Application Programming Interfaces) are vital in modern software development, enabling communication between different software systems, applications, and devices through a standardized interface. They are extensively used across various industries for integrating disparate systems, enhancing functionality, and automating processes.

In web services and cloud computing, APIs allow different applications to interact, enabling tasks like user authentication and data sharing. Mobile applications rely on APIs to communicate with backend services, ensuring that apps remain lightweight while accessing powerful server-side resources. Similarly, in IoT (Internet of Things), APIs enable devices to send data to cloud services or receive commands, creating interconnected networks of smart devices.

Robotics and automation also benefit from APIs, which provide standardized methods for remote control and monitoring. For instance, in a project involving a robot built with Smart Motion Devices (SMD) and controlled via a Flask API, the API facilitates real-time control and precise execution of tasks.

The Role of APIs in Robotics:

In the context of robotics, APIs are crucial for controlling and managing robotic systems. They provide a standardized interface through which software can send commands to the robot, receive sensor data, and monitor the robot’s status. By using APIs, developers can create modular and extensible control systems, enabling different components of a robot to be managed independently or integrated into larger systems.

For instance, in this project, the Flask API serves as the control interface for a robot built with SMD. The API allows external applications to interact with the robot by sending movement commands, initializing the robot’s position, and performing other control operations. This abstraction simplifies the interaction with the robot, making it possible to control the robot remotely or integrate it with other software systems seamlessly.

Example Application Details: Controlling Robots Built with SMD Using Flask API

This project utilizes ACROME’s Smart Motion Devices (SMD) along with a Raspberry Pi to create a simple, yet effective, mobile robot. The hardware setup is designed for precision control and flexibility in movement. Below are the key components used:

  • SMD RED Brushed DC Motor Driver Modules: These modules provide precise control over the robot’s motors, allowing for accurate movement and positioning. They are essential for managing the robot’s low-level motor functions.
  • DC Motors: The robot is equipped with two DC motors, driven by the SMD modules. These motors deliver the necessary torque and speed for the robot’s mobility.
  • Raspberry Pi: The Raspberry Pi serves as the central controller, running the Flask API that handles motor control commands. It interfaces directly with the SMD modules via GPIO and manages communication with external control interfaces over the network.
  • Power Supply: The robot is powered by a battery pack that supplies consistent voltage to both the Raspberry Pi and the motors, ensuring reliable operation during movement.

This hardware configuration provides a solid foundation for controlling the robot via the Flask API, offering a straightforward approach to managing robotic movements with precision.

Software Details

The software for controlling the robot built with Smart Motion Devices (SMD) is structured around a Flask-based RESTful API that runs on a Raspberry Pi. This API enables remote control of the robot's movements via HTTP requests, allowing for a straightforward and flexible interface to manage the robot's behavior.

Flask API Structure

The Flask API serves as the communication layer between the user and the robot's hardware. It handles incoming HTTP requests, processes them, and invokes the appropriate control functions for the robot. The API is structured with a main endpoint /execute, which interprets commands based on the id provided in the JSON payload.

  • /execute Endpoint: This endpoint receives commands such as initializing the robot, linear movement, rotation, and radial movement. The API parses the incoming JSON data, determines the command type, and then calls the corresponding function to execute the command on the robot.

@app.route('/execute', methods=['POST']) def execute(): 
    data = request.json     if data.get('id') == "0": 
        return jsonify(init_robot())     elif data.get('id') == "1": 
        return jsonify(linear_movement(data['cm']))     elif data.get('id') == "2": 
        return jsonify(turn(data['degree']))     elif data.get('id') == "3": 
        return jsonify(radial_movement(data['radius'], data['degree'])) 

Control Functions

The core functionality of the robot is implemented through a set of control functions that directly interact with the SMD motor drivers. These functions are responsible for the precise control of the robot’s movement based on the commands received from the API.

  • linear_movement(cm) Function: Moves the robot forward or backward by a specified distance in centimeters. The function calculates the required changes in x and y coordinates based on the current angle and updates the motor positions accordingly.

  def
 linear_movement(cm): 
    global x_coordinate, y_coordinate, angle     x_coordinate += cm * np_cos(angle * np_pi / 180)     y_coordinate += cm * np_sin(angle * np_pi / 180) 
 
    # Motor position adjustment logic follows... 
 
    return {"x": x_coordinate, "y": y_coordinate, "angle": angle}

We used linear_movement(cm), turn(degree), and radial_movement(radius, degree) functions for this example application. These functions control the robot's movement by enabling it to travel in a straight line, rotate in place, or follow a circular path, respectively. The linear_movementfunction moves the robot forward when given a positive distance and backward when given a negative distance, all in centimeters. The turn function rotates the robot left with positive degree values and right with negative values. Finally, the radial_movement function guides the robot along a curved path: a positive radius moves the robot in a rightward arc, while a negative radius creates a leftward arc; the angle of rotation determines the extent of the curve, with positive values moving the robot forward along the arc and negative values moving it backward. Each function returns the robot's updated position and orientation, ensuring precise control during movement.

Accessing and Using the Flask API

The Flask API created in this project serves as the control interface for the robot. It allows users to send commands to the robot over a network, enabling remote operation and control. The API is hosted on a Raspberry Pi, and users can interact with it by sending HTTP requests to specific endpoints defined in the Flask application. Below is a step-by-step explanation of how to access the API, what happens when you access it, and what you can expect as a response.

API Endpoint Overview

The Flask API defines a primary endpoint /execute, which handles various robot control commands based on the data sent in the HTTP request. The API can be accessed using tools like curl, Postman, or any HTTP client in programming languages such as Python, JavaScript, or Java.

  • If your Raspberry Pi is connected to a local network, you can access the API using the Raspberry Pi’s IP address and the designated port (in this case, port 5000). The base URL would look like this:
http://<raspberry-pi-ip>:5000/execute

Sending a Request to the API

To control the robot, you send a POST request to the /execute endpoint. The request must include a JSON payload that specifies the command you want the robot to execute. Below are examples of different commands you can send, along with the expected actions and responses.

To test the API using the command line, you can use curl, a command-line tool for sending HTTP requests.

 curl -X POST http://<raspberry-pi-ip>:5000/execute -H "Content-
Type: application/json" -d '{"id": "1", "cm": 50}' 

Or we can write a simple Python script to access the API we created in Python enviroment

 import requests 
 
# Set the base URL for the API 
url = 'http://<raspberry-pi-ip>:5000/execute' 
 
# Example JSON payload for initializing the robot 
 payload = {"id": "1", "cm": 50} 
 
# Send the POST request 
response = requests.post(url, json=payload) 
 
# Print the response from the API print(response.json()) 

Application Areas of the Project and Future Developments

The method employed in this project, which integrates SMD hardware with a Flask API for robotic control, is highly adaptable and can be applied across various domains. Its core strength lies in the flexibility of the Flask API, enabling seamless integration with different systems and technologies.

In industrial automation, this method can be utilized to enhance precision in tasks such as material handling and assembly, where remote control and real-time adjustments are crucial. The approach also fits well into the robotics research field, where quick iterations and modifications are needed to test new control algorithms or hardware configurations.

For smart home applications, the method allows for the easy addition of custom functionalities, making it suitable for developing personalized automation solutions. In healthcare, it can be adapted for assistive devices, providing straightforward control mechanisms that are essential for patient safety and ease of use.

Looking ahead, future developments could focus on integrating advanced AI algorithms to enable more autonomous operations, expanding the range of sensors and actuators to improve environmental interaction, and enhancing the security of the communication protocols to ensure robust and safe operation in critical applications. These improvements will further broaden the applicability of this method, making it relevant for more complex and demanding use cases.

Author

Discover Acrome

Acrome was founded in 2013. Our name stands for ACcessible RObotics MEchatronics. Acrome is a worldwide provider of robotic experience with software & hardware for academia, research and industry.