Arduino+树莓派双电机控制及编码器测距编译报错求助
问题分析与修复方案
编译错误逐一修复
- TB67H420FTG对象未声明:原代码中
TB67H420FTG (2,3,11,4,5,10);缺少对象名称,后续代码使用driver调用方法,需改为TB67H420FTG driver(2,3,11,4,5,10);。 - 右编码器变量名拼写错误:原代码中
Encoders ridriverghtEncoder(15,14);存在拼写错误,变量名应为rightEncoder,否则后续无法识别该对象。 - 变量名大小写不匹配:原代码中
Serial.println(CurrentRightEncoderCount);的变量名首字母大写,与实际定义的currentRightEncoderCount不符,需统一为小写开头。 - encoderTest函数未调用:虽非编译错误,但原代码定义了
encoderTest()却未在loop()中调用,导致编码器计数无法输出,需添加调用逻辑。
修正后的Arduino代码
#include "TB67H420FTG.h" #include <QuadratureEncoder.h> // 修复:添加driver对象名称 TB67H420FTG driver(2,3,11,4,5,10); Encoders leftEncoder(7,6); // 修复:修正右编码器变量名拼写 Encoders rightEncoder(15,14); unsigned long lastMilli = 0; void encoderTest(){ // 每50毫秒打印一次编码器计数 if(millis()-lastMilli > 50){ long currentLeftEncoderCount = leftEncoder.getEncoderCount(); long currentRightEncoderCount = rightEncoder.getEncoderCount(); Serial.print(currentLeftEncoderCount); Serial.print(" , "); Serial.println(currentRightEncoderCount); lastMilli = millis(); } } void setup() { driver.init(); Serial.begin(9600); } void loop() { // 修复:调用encoderTest函数 encoderTest(); if (Serial.available() > 0) { long currentLeftEncoderCount = leftEncoder.getEncoderCount(); long currentRightEncoderCount = rightEncoder.getEncoderCount(); Serial.println(currentLeftEncoderCount); // 修复:修正变量名大小写 Serial.println(currentRightEncoderCount); String data = Serial.readStringUntil('\n'); Serial.print("Command Received: " + data); if (data == "turn A right") driver.setMotorAPower(50); else if (data == "turn A left") driver.setMotorAPower(-50); if (data == "turn B right") driver.setMotorBPower(50); else if (data == "turn B left") driver.setMotorBPower(-50); else if (data == "stop A") driver.motorABrake(); else if (data == "stop B") driver.motorBBrake(); else if (data == "stop All") driver.brakeAll(); else Serial.print("Invalid Command Received"); } }
树莓派控制代码(无需修改)
import serial import time ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1) ser.reset_input_buffer() while True: ser.write(b"turn A left\n") line = ser.readline().decode('utf-8').rstrip() print("Data Received from Arduino: ",line) time.sleep(3) ser.write(b"turn A right\n") line = ser.readline().decode('utf-8').rstrip() print("Data Received from Arduino: ",line) time.sleep(3) ser.write(b"turn B left\n") line = ser.readline().decode('utf-8').rstrip() print("Data Received from Arduino: ",line) time.sleep(3) ser.write(b"turn B right\n") line = ser.readline().decode('utf-8').rstrip() print("Data Received from Arduino: ",line) time.sleep(3) ser.write(b"stop A\n") line = ser.readline().decode('utf-8').rstrip() print("Data Received from Arduino: ",line) time.sleep(3) ser.write(b"stop B\n") line = ser.readline().decode('utf-8').rstrip() print("Data Received from Arduino: ",line) time.sleep(3) ser.write(b"stop All\n") line = ser.readline().decode('utf-8').rstrip() print("Data Received from Arduino: ",line) time.sleep(5)
内容的提问来源于stack exchange,提问作者Garberchov
相关产品推荐
相关产品推荐

