使用Raspberry Pi控制伺服电机时Python代码错误 3 B+

Error in Python code in controlling servo motor using Raspberry Pi 3 B+

我目前正在使用 Raspberry Pi 3 B+ 和 Android 应用程序支持构建一个自动垃圾桶,我将使用伺服电机作为盖子和 Android 应用程序的执行器作为无线遥控器的一种形式。一切都进行得很顺利,直到我遇到了一个问题,每当我试图按下 Android 应用程序上的按钮时,Python shell 程序在测试期间就会出错。我使用了参考视频 (https://www.youtube.com/watch?v=t8THp3mhbdA&t=1s) 并彻底遵循了所有内容,直到我遇到了这个障碍。

对我来说不断出现的结果是:

Waiting for connection 
...connected from : 

根据参考视频,假设的结果是:

Waiting for connection 
...connected from : ('192.168.1.70', 11937)
Increase: 2.5

如您所见,IP 地址、端口和 'Increase' 文本没有出现,这意味着代码有问题。

根据观看视频的人的一些评论,此代码已过时,使用 Python 2,我们现在的最新版本是 Python 3,并且我们需要在条件中使用“.encode()”行。但是,作为 Python 的新手,恐怕我还没有将其应用到代码中的知识。

这是视频中使用的代码:

import Servomotor
from socket import *
from time import ctime
import RPi.GPIO as GPIO

Servomotor.setup()

ctrCmd = ['Up','Down']

HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

while True:
        print 'Waiting for connection'
        tcpCliSock,addr = tcpSerSock.accept()
        print '...connected from :', addr
        try:
                while True:
                        data = ''
                        data = tcpCliSock.recv(BUFSIZE)
                        if not data:
                                break
                        if data == ctrCmd[0]:
                                Servomotor.ServoUp()
                                print 'Increase: ',Servomotor.cur_X
                        if data == ctrCmd[1]:
                                Servomotor.ServoDown()
                                print 'Decrease: ',Servomotor.cur_X
        except KeyboardInterrupt:
                Servomotor.close()
                GPIO.cleanup()
tcpSerSock.close();

我已经将使用 ' ' 格式的文本字符串更改为 (" ") 格式,因为它也在代码中产生了一些错误,我立即更正了这些错误。

如有任何帮助,我们将不胜感激,并提前致谢!

这是一个 Python3 版本,为了更好的清晰度和更好的实践,进行了一点点编辑:

import Servomotor
import RPi.GPIO as GPIO
import socket

# Setup the motor
Servomotor.setup()

# Declare the host address constant - this will be used to connect to Raspberry Pi
# First values is IP - here localhost, second value is the port
HOST_ADDRESS = ('0.0.0.0', 21567)

# Declare the buffer constant to control receiving the data
BUFFER_SIZE = 4096

# Declare possible commands
commands = 'Up', 'Down'

# Create a socket (pair of IP and port) object and bind it to the Raspberry Pi address
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(HOST_ADDRESS)

# Set the socket to listen to an incoming connection (1 at a time)
server_socket.listen(1)

# Never stop the server once it's running
while True:

    # Inform that the server is waiting for a connection
    print("Waiting for connection to the following address: {}...".format(HOST_ADDRESS))

    # Perform a blocking accept operation to wait for a client connection
    client_socket, client_address = server_socket.accept()

    # Inform that the client is connected
    print("Client with an address {} connected".format(client_address))

    # Keep exchanging data
    while True:

        try:

            # Receive the data (blocking receive)
            data = client_socket.recv(BUFFER_SIZE)

            # If 0-byte was received, close the connection
            if not data:
                break

            # Attempt to decode the data received (decode bytes into utf-8 formatted string)
            try:
                data = data.decode("utf-8").strip()
            except UnicodeDecodeError:
                # Ignore data that is not unicode-encoded
                data = None

            # At this stage data is correctly received and formatted, so check if a command was received
            if data == commands[0]:
                Servomotor.ServoUp()
                print("Increase: {}".format(Servomotor.cur_X))
            elif data == commands[1]:
                Servomotor.ServoDown()
                print("Decrease: {}".format(Servomotor.cur_X))
            elif data:
                print("Received invalid data: {}".format(data))

        # Handle possible errors
        except ConnectionResetError:
            break
        except ConnectionAbortedError:
            break
        except KeyboardInterrupt:
            break

    # Cleanup
    Servomotor.close()
    GPIO.cleanup()
    client_socket.close()

    # Inform that the connection is closed
    print("Client with an address {} disconnected.".format(client_address))

为了向您展示运行中的代码,我在我的机器上托管了一个本地服务器并使用 Putty 连接到它。以下是我输入的命令:

这里是服务器的输出(我把Servo相关的函数换成了打印语句):

Waiting for connection to the following address: ('0.0.0.0', 21567)...
Client with an address ('127.0.0.1', 61563) connected.
Received invalid data: Hello
Received invalid data: Let's try a command next
Running ServoUp
Increase: 2.5
Running ServoDown
Decrease: 2.5
Received invalid data: Nice!
Client with an address ('127.0.0.1', 61563) disconnected.
Waiting for connection to the following address: ('0.0.0.0', 21567)...