How to Integrate USB-to-Serial (FTDI, CH340, CP2102) with ASI Biont: A Step-by-Step Guide to AI-Powered COM Port Automation

Introduction

In industrial automation, scientific research, and IoT prototyping, USB-to-Serial adapters like FTDI FT232, CH340, and CP2102 are the workhorses that connect legacy serial devices—sensors, PLCs, GPS modules, and microcontrollers—to modern computers. Yet, despite their ubiquity, extracting meaningful data from these adapters typically requires writing custom scripts, handling parsing logic, and building alert systems from scratch. ASI Biont, an AI agent designed for device integration, eliminates that drudgery. By pairing a simple USB-to-Serial adapter with ASI Biont’s Hardware Bridge and execute_python capabilities, you can transform a raw COM port into an intelligent, conversational interface that reads sensor data, controls actuators, and sends alerts—all without writing a single line of glue code yourself.

This article is a practical guide for engineers, hobbyists, and system integrators who want to connect CH340, FTDI, or CP2102 adapters to ASI Biont. We’ll cover the exact connection mechanism (COM port via Hardware Bridge), show real Python code for four concrete use cases, and explain how ASI Biont’s AI converts your verbal description into a working integration in seconds. No dashboards, no drag-and-drop editors—just you, the AI, and a chat window.

Why Use an AI Agent with a USB-to-Serial Adapter?

A USB-to-Serial adapter alone is passive—it merely converts USB packets to RS-232 signals. To make it useful, you need software that:
- Opens the COM port with the correct baud rate, parity, and stop bits.
- Sends commands and parses responses (e.g., AT commands, Modbus RTU frames, NMEA sentences).
- Logs data, detects anomalies, and triggers actions (email, Telegram, database write).

Traditionally, you’d write a Python script using pyserial, test it, debug edge cases, and then deploy it on a Raspberry Pi or a server. ASI Biont collapses this workflow: you describe your task in natural language, and the AI generates, tests, and runs the integration code on the fly. It handles error handling, timeout management, and even suggests optimizations based on your hardware.

How ASI Biont Connects to USB-to-Serial Adapters

ASI Biont does not have direct access to your computer’s COM ports—it runs in the cloud. To bridge the gap, it uses a lightweight companion application called Hardware Bridge (bridge.py). Here’s the architecture:

  1. You download bridge.py from the ASI Biont dashboard (Devices → Create API Key → Download bridge). This is a Python script that runs on your local machine (Windows, Linux, macOS).
  2. Bridge.py connects to ASI Biont via a secure WebSocket connection (the only communication channel). It authenticates using a token you generate in the dashboard.
  3. You specify the COM port (e.g., COM3 on Windows, /dev/ttyUSB0 on Linux) and the baud rate (e.g., 9600, 115200) when launching bridge.py or later through the chat.
  4. You chat with the AI agent and describe your task: “Read temperature from a DS18B20 sensor on COM4 at 115200 baud every 10 seconds, and alert me if it exceeds 30°C.”
  5. The AI uses the industrial_command tool with the serial_write_and_read command. This is an atomic operation: bridge.py sends a hex string to the COM port and immediately reads the response. Data is passed in hex format (e.g., data="48454c500a" for HELP+\n) or as escape sequences (BLUE_ON\n).
  6. Bridge.py handles low-level details: On Windows, if pyserial overlapped I/O fails, bridge.py automatically falls back to CancelIoEx, PurgeComm, and synchronous WriteFile to ensure reliable writes.
  7. Result: The AI receives the parsed data, analyzes it (e.g., compares temperature to thresholds), and can send commands back (e.g., turn on a relay via RELAY_ON\n).
Component Role
Hardware Bridge (bridge.py) Local proxy; runs on user’s PC; opens COM port; relays commands/responses via WebSocket
ASI Biont Cloud AI agent; runs your Python logic; sends industrial_command; stores logs; triggers alerts
Your Chat Interface You describe tasks in natural language; AI interprets and executes

Alternative Connection Methods for Related Devices

While USB-to-Serial adapters use the COM port path, ASI Biont supports many other protocols. For devices that communicate over TCP/IP or have an HTTP API, you can use execute_python directly—no bridge needed. For example:
- Modbus/TCPindustrial_command(protocol='modbus', command='read_registers', ...)
- MQTT → AI writes a Python script using paho-mqtt that runs in the sandbox.
- SSH → AI connects to a Raspberry Pi via paramiko and runs GPIO commands.

But for serial devices, the Hardware Bridge is the only way, because the cloud sandbox has no access to your local USB ports.

Concrete Use Cases with Code Examples

Below are four real-world scenarios showing how to integrate CH340/FTDI/CP2102 with ASI Biont. Each includes the chat prompt you’d give to the AI, the Python code it generates (which runs in the sandbox or on bridge.py), and the outcome.

Use Case 1: Temperature Logging with DS18B20

Scenario: You have a DS18B20 temperature sensor connected to an Arduino that outputs the temperature over serial at 9600 baud. You want to log the temperature to a CSV file and receive a Telegram alert if it exceeds 35°C.

Chat Prompt:

Connect to COM3 at 9600 baud via bridge. Every 5 seconds, read a line from the serial port. The Arduino sends a temperature value like "Temp: 23.5". Parse it, save it to a CSV file, and if temperature > 35°C, send me a Telegram message with the value.

AI-Generated Python Code (runs in sandbox via execute_python):

import asyncio
import csv
import io
from datetime import datetime

# Assume bridge.py is already connected and we have a function to read
# The AI uses industrial_command to do the actual serial read.
# Here we simulate the logic that runs after each serial read.

async def process_temperature():
    # This part runs when AI calls serial_write_and_read
    # The bridge returns raw data, e.g., b"Temp: 27.3\r\n"
    raw_data = "Temp: 27.3"  # placeholder
    if raw_data.startswith("Temp:"):
        temp_str = raw_data.split(":")[1].strip()
        try:
            temp = float(temp_str)
        except ValueError:
            print("Invalid temperature")
            return
        timestamp = datetime.now().isoformat()
        # Save to CSV (using sandbox file I/O)
        with open("/tmp/temperature_log.csv", "a", newline="") as f:
            writer = csv.writer(f)
            writer.writerow([timestamp, temp])
        # Alert if threshold exceeded
        if temp > 35.0:
            # Send Telegram via requests
            import requests
            bot_token = "YOUR_BOT_TOKEN"
            chat_id = "YOUR_CHAT_ID"
            msg = f"⚠️ Temperature alert: {temp}°C at {timestamp}"
            url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
            requests.post(url, json={"chat_id": chat_id, "text": msg})
            print("Alert sent")
        else:
            print(f"Logged {temp}°C")

asyncio.run(process_temperature())

How It Runs: The AI sets up a periodic loop using industrial_command every 5 seconds. Each iteration sends an empty write (or a polling command if your Arduino requires it), reads the response, and passes it to this Python logic. The CSV is saved temporarily in the sandbox; you can download it or have the AI upload it to cloud storage.

Use Case 2: Relay Control via Serial Command

Scenario: You have a relay module connected to an Arduino/ESP32 that listens for commands like RELAY_ON\n and RELAY_OFF\n. You want to control the relay from a chat message: “Turn on the pump.”

Chat Prompt:

Connect to COM5 at 115200 baud. When I say “turn on pump”, send the string "PUMP_ON\n" to the serial port. When I say “turn off pump”, send "PUMP_OFF\n". Wait 2 seconds for a response and tell me what the device replied.

AI-Generated Command (sent via industrial_command):

industrial_command(
    protocol='serial',
    command='serial_write_and_read',
    params={
        'port': 'COM5',
        'baud': 115200,
        'data': '50554d505f4f4e0a'  # hex for "PUMP_ON\n"
    }
)

Outcome: The bridge sends the hex bytes to the COM port, the Arduino toggles the relay, and the bridge reads back an acknowledgment (e.g., OK\n). The AI parses “OK” and replies in chat: “✅ Pump turned on. Device responded: OK.” You never see the hex—the AI handles conversion.

Use Case 3: Liquid Level Monitoring with Ultrasonic Sensor

Scenario: An HC-SR04 ultrasonic sensor connected to an Arduino sends distance in centimeters every 2 seconds over serial at 9600 baud. You want to monitor the level of a water tank and trigger a pump when level drops below 20 cm.

Chat Prompt:

Read from COM7 at 9600 baud. Data format: "Distance: 45.2 cm". If distance > 30 cm, send a command "FILL_ON\n" to the same port to start filling. If distance < 10 cm, send "FILL_OFF\n". Log all readings to a file.

AI-Generated Logic (pseudocode run in sandbox):

# After each serial read, this function is called:
def check_level(distance_cm):
    if distance_cm > 30.0:
        # Send FILL_ON via industrial_command
        # (AI calls serial_write_and_read with hex for "FILL_ON\n")
        print("Level low, starting fill")
    elif distance_cm < 10.0:
        # Send FILL_OFF
        print("Level high, stopping fill")
    # Log to file
    with open("/tmp/level_log.txt", "a") as f:
        f.write(f"{datetime.now()}, {distance_cm}\n")

Result: The AI runs this loop, reads the sensor every 2 seconds, and automatically controls the pump relay. If the water level reaches critical low, it also sends you a Telegram notification: “⚠️ Water level critically low (8 cm). Pump activated.”

Use Case 4: Parsing NMEA GPS Data from a Serial GPS Module

Scenario: A u-blox NEO-6M GPS module is connected via a CP2102 adapter to your PC, outputting NMEA sentences at 9600 baud. You want to extract latitude, longitude, and speed, and plot the route on a map.

Chat Prompt:

Connect to /dev/ttyUSB0 at 9600 baud. Continuously read NMEA sentences. Parse the $GPGGA and $GPRMC sentences to extract latitude, longitude, and speed. Save the coordinates to a CSV file every minute. Also, if the GPS signal is lost (no fix), alert me via email.

AI-Generated Python (uses pynmea2 in sandbox):

import pynmea2
import csv
import io
from datetime import datetime

# This function is called for each line read from serial
def parse_nmea(line):
    if line.startswith("$GPGGA") or line.startswith("$GPRMC"):
        try:
            msg = pynmea2.parse(line)
            if isinstance(msg, pynmea2.GGA):
                lat = msg.latitude
                lon = msg.longitude
                fix = msg.gps_qual
                if fix == 0:
                    # No fix — send email alert
                    # (AI uses requests to SendGrid API or smtplib)
                    print("No GPS fix!")
                else:
                    # Save to CSV
                    with open("/tmp/gps_log.csv", "a", newline="") as f:
                        writer = csv.writer(f)
                        writer.writerow([datetime.now(), lat, lon, msg.spd_over_grnd])
            return lat, lon
        except pynmea2.ParseError:
            pass

Outcome: The AI continuously feeds lines from the serial port into this parser. You get a live GPS log and can later ask the AI to generate a KML file or a Folium map from the saved coordinates.

Why This Approach Beats Traditional Coding

Aspect Traditional Method ASI Biont Method
Setup time 2–4 hours (write, test, debug) 2 minutes (describe in chat)
Error handling Manual try/except, timeout logic AI auto-adds retries, fallbacks
Alerting Integrate separate Telegram/email API AI uses sandbox libraries (requests)
Scalability Requires refactoring for new sensors Just describe new task in chat
Maintenance Update scripts when hardware changes AI adapts dynamically

Getting Started: Step-by-Step

  1. Download bridge.py from the ASI Biont dashboard (Devices → Create API Key → Download bridge).
  2. Install dependencies on your local machine: pip install pyserial requests websockets.
  3. Run bridge.py with your token and COM port:
    bash python bridge.py --token=YOUR_TOKEN --ports=COM3 --baud=115200
  4. Open the ASI Biont chat and describe your task, e.g., “Read temperature from COM3 at 115200 baud. The device sends a line like ‘T:23.5’. If temperature > 30, send me a Telegram alert.”
  5. The AI does the rest: it writes the Python code, sends periodic serial_write_and_read commands via the bridge, and executes the analysis logic in the sandbox.

Conclusion

USB-to-Serial adapters like FTDI, CH340, and CP2102 unlock a world of legacy and custom serial devices. By connecting them to ASI Biont via the Hardware Bridge, you gain an AI agent that can read, parse, log, and act on serial data—all through a simple chat conversation. No more writing boilerplate pyserial scripts, no more manual alert setups. Whether you’re logging temperatures, controlling relays, monitoring liquid levels, or tracking GPS positions, ASI Biont turns your COM port into an intelligent interface in seconds.

Ready to try it? Visit asibiont.com, create an account, download bridge.py, and connect your first USB-to-Serial adapter. Describe your sensor in the chat, and watch the AI bring your serial data to life.

← All posts

Comments