You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Arduino Due与Jetson Nano串口传超255整数及循环问题求助

Arduino Due与Jetson Nano串口通信问题排查与优化

一、传输超255整数的可选方案

单字节传输仅支持0-255的数值,当需要传输更大整数时,并非只有struct.pack转字符串这一种方案,以下是几种常用实现:

  • 多字节二进制传输:利用整数的二进制结构,将数值拆分为多字节发送。比如200-1000的数值用16位整数即可覆盖,Python端用struct.pack('<HH', servo_val, dc_val)打包成4字节二进制数据,Arduino端读取4个字节后拼接为两个16位整数,这种方式传输效率最高。
  • ASCII分隔字符串传输:将两个整数用分隔符(如逗号)拼接成字符串(比如"430,180\n")发送,Arduino端按分隔符拆分字符串后转成整数,这种方式可读性强,便于调试。
  • 自定义帧格式传输:给数据添加帧头和帧尾(比如"[430,180]"),避免串口干扰导致的数据解析错误,适合复杂环境下的通信。

二、Python循环与Arduino代码的问题修复

你的代码存在多处逻辑和语法错误,导致循环无法正常运行,以下是修复后的完整代码:

修复后的Python代码

import serial
import time

# 初始化串口,添加超时防止readline无限阻塞
arduino = serial.Serial('/dev/ttyACM0', 115200, timeout=2)
time.sleep(1)

while True:
    # 发送带换行的分隔字符串,匹配Arduino的readStringUntil逻辑
    print('Sending 430,180')
    arduino.write(b'430,180\n')
    # 读取并解析反馈数据
    data = arduino.readline().decode('utf-8').strip()
    if data:
        print(f"Received: {data}")
    
    print('Sending 330,200')
    arduino.write(b'330,200\n')
    data = arduino.readline().decode('utf-8').strip()
    if data:
        print(f"Received: {data}")
    
    time.sleep(5)

修复后的Arduino代码

#include <Arduino.h>

// 声明全局控制变量,统一命名规范
int servo_position = 380; // 初始安全位置
int motor_speed = 0;

void setup() {
  Serial.begin(115200);
}

void loop() {
  if (Serial.available() > 0) {
    // 读取整行数据直到换行符,避免阻塞
    String input = Serial.readStringUntil('\n');
    input.trim(); // 去除首尾空白字符
    
    // 按逗号分割字符串,解析两个整数
    int comma_index = input.indexOf(',');
    if (comma_index != -1) {
      String servo_str = input.substring(0, comma_index);
      String dc_str = input.substring(comma_index + 1);
      
      int servo_val = servo_str.toInt();
      int dc_val = dc_str.toInt();
      
      // 限制舵机位置范围
      if (servo_val >= 300 && servo_val <= 500) {
        servo_position = servo_val;
      } else {
        servo_position = 380; // 非法数据时切换到安全位置
      }
      
      // 限制电机最小速度
      if (dc_val >= 50) {
        motor_speed = dc_val;
      } else {
        motor_speed = 0; // 低于最小速度则停止电机
      }
      
      // 发送组合反馈数据
      Serial.print("Servo Pos: ");
      Serial.print(servo_position);
      Serial.print(", Motor Speed: ");
      Serial.println(motor_speed);
    }
  }
}

关键修复点说明

  1. Python端:

    • 移除不必要的struct.pack,直接发送带换行的分隔字符串,匹配Arduino的读取逻辑
    • 添加串口超时参数,避免readline因无数据无限阻塞
    • 对读取的字节流进行解码和去空白处理,提升数据可读性
  2. Arduino端:

    • 移除错误的readString循环和死循环while(Serial.available() ==0),改用readStringUntil('\n')读取整行数据
    • 修复未声明变量、大小写不一致、缺少分号等语法错误
    • 优化数据解析逻辑,通过逗号分割字符串获取两个控制参数
    • 补充非法数据的容错处理,确保设备安全

内容的提问来源于stack exchange,提问作者Vasumathi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 14:43:38