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

时间:2019-02-23 14:31:40

标签: python raspberry-pi servo

我目前正在使用具有Android应用程序支持的Raspberry Pi 3 B +构建自动垃圾桶,其中我将使用伺服电机作为盖子的致动器,并使用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地址,端口和“增加”文本没有出现,这意味着代码有问题。

根据观看视频的人的评论,使用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();

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

任何帮助将不胜感激,并在此先感谢您!

1 个答案:

答案 0 :(得分:2)

这里是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将其连接到该服务器。这是我输入的命令:

Putty commands

这是服务器的输出(我将与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)...