所以我使用树莓派使用来自笔记本电脑的 xbox 控制器的输入命令对机器人进行编程。使用 python 2.7 编程
我在尝试使用控制器轴的幅度来控制电机的速度时遇到错误。
但如果我为它的工作速度声明一个确定的数字。但是如果我使用大小它会给出一个错误,即使我打印变量也很好。
这是我得到的错误
executing forward...
max speed is
23
Traceback (most recent call last):
File "driverMain.py", line 103, in <module>
main()
File "driverMain.py", line 69, in main
frontCon.allForward(maxSpeed)
File "/home/pi/xbox/sabretooth.py", line 11, in allForward
self.leftMotor.drive('forward', speed)
File "/home/pi/xbox/sabretooth.py", line 32, in drive
self.port.write(chr(speed))
TypeError: an integer is required
*部分代码在电脑上
def joyStickMovement(magnitude, command, joyStickNum):
host = '192.168.1.112'
port = 12345
sock = socket.socket()
sock.connect((host,port))
prefix = ""
if joyStickNum == 1:
prefix = "bucket"
sock.send(str(prefix + command) + '|' + str(magnitude))
*覆盆子上的部分代码
frontCon = controller(serialPort, baudRate, 130)
rearCon = controller(serialPort, baudRate, 129)
#set up socket
host = ''
port = 12345
sock = socket.socket()
sock.bind((host,port))
sock.listen(5)
while True:
c, addr = sock.accept()
command,maxSpeed = c.recv(1024).split('|')
print(command)
print(maxSpeed)
#### this print shows the speed value correctly
#### if i insert this maxspeed code
## maxSpeed = 120
## here for example, the program works correctly, otherwise i get an error
## even tho without it, the print work fine
#### later in the code
elif command == 'forward':
print('executing forward...')
print('max speed is')
print(maxSpeed)
frontCon.allBack(maxSpeed)
rearCon.allBack(maxSpeed)
*剑齿虎
import serial
class controller(object):
def __init__(self, port, baudRate, address):
self.port = serial.Serial(port, baudRate, timeout=1)
self.address = address
self.leftMotor = motor(self.port, address, 1)
self.rightMotor = motor(self.port, address, 2)
def allForward(self, speed):
self.leftMotor.drive('forward', speed)
self.rightMotor.drive('forward', speed)
def allBack(self, speed):
self.leftMotor.drive('back', speed)
self.rightMotor.drive('back', speed)
class motor(object):
#motorNum is 1 or 2, depending on which motor you wish to control
def __init__(self, serial, controllerAddress, motorNum):
self.port = serial
self.address = controllerAddress
self.motorNum = motorNum
if motorNum == 1:
self.commands = {'forward': 0, 'back': 1}
elif motorNum == 2:
self.commands = {'forward': 4, 'back': 5}
def drive(self, direction, speed):
self.port.write(chr(self.address))
self.port.write(chr(self.commands[direction]))
self.port.write(chr(speed))
self.port.write(chr(int(bin((self.address + self.commands[direction] + speed) & 0b01111111), 2)))
我还尝试在脚本的开头添加一个 maxSpeed = 50,希望它可能会看到该变量并将其更改为它接收到的任何内容并将其发送到电机,但它仍然给出相同的错误。我真的不知道还能做什么,如果有任何帮助,我将不胜感激
感谢您的时间