【问题标题】:TypeError: encode() argument 'encoding' must be str, not int类型错误:encode() 参数“编码”必须是 str,而不是 int
【发布时间】:2020-11-23 23:56:49
【问题描述】:

我正在尝试使用 pyserial 在 python 中控制我的 Arduino 并收到此错误: 类型错误:encode() 参数“编码”必须是 str,而不是 int

我对编码真的很陌生,所以我有点迷茫。 我想要做的是我想首先选择“功能”nr 1 这是“滑动”,我想给它三个参数。首先,它说“命令”最多只需要两个参数,所以我尝试使用 2/3 参数来使其工作,但现在它抱怨参数必须是 str ... 任何人都可以帮助我让它工作吗??

import time
import serial
strComPort = '/dev/ttyACM0'
strComBaud = 9600

cmdSerial = serial.Serial(strComPort, strComBaud)
time.sleep(2) #sec

while True:
    command= input("Enter command number in list: \n1: Swipe \n2: tap\n3: Double tap\n4: Press\n5: Drag\n6: Flick right\n7: Flick left")

    if (command == '1'):
        x = int(input("From which deg?: "))
        y = int(input("To which deg? :"))
        spd = int(input("Speed of swipe? :"))
        cmdSerial.write(command.encode(x, y, spd))
        time.sleep(1)
    
    if (command == '2'):
        cmdSerial.write(command.encode())
        time.sleep(1)

    if (command == '3'):
        cmdSerial.write(command.encode())
        time.sleep(1)

    elif (command == '4'):
        cmdSerial.write(command.encode())
        time.sleep(1)

    elif (command == '5'):
        x = int(input("From which deg?: "))
        y = int(input("To which deg? :"))
        cmdSerial.write(command.encode(x, y))
        time.sleep(1)

    elif (command == '6'):
        cmdSerial.write(command.encode())
        time.sleep(1)

    elif (command == '7'):
        cmdSerial.write(command.encode())
        time.sleep(1)

    elif (command == 'q'):
        print("Exiting...")
        break

    else:
        print("Only number between 1-6 or 'q' (exit)")

【问题讨论】:

    标签: python arduino pyserial


    【解决方案1】:

    您收到错误是因为您尝试使用整数对字符串进行编码。

    Here 是您可以使用的所有编码的列表。

    【讨论】:

      猜你喜欢
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 2018-04-26
      • 2017-06-07
      • 1970-01-01
      相关资源
      最近更新 更多