Ошибка в коде Python при управлении серводвигателем с помощью Raspberry Pi 3 B+
В настоящее время я создаю автоматизированный контейнер для мусора с использованием Raspberry Pi 3 B+ с поддержкой приложений Android, где я буду использовать серводвигатель в качестве привода для крышки, а приложение Android - в качестве формы беспроводного дистанционного управления. Все шло гладко, пока я не столкнулся с проблемой, что всякий раз, когда я пытаюсь нажать кнопку в моем приложении Android, во время тестирования в программе оболочки Python возникают ошибки. Я использовал эталонное видео ( 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 ответ
Вот версия 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. Вот команды, которые я ввел:
Вот выходные данные сервера (я поменял функции, связанные с сервоприводом, для печати операторов):
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)...