TCP连接控制伺服电机

时间:2017-01-17 10:31:13

标签: raspberry-pi

我正在使用android客户端和python服务器编写套接字网络应用程序。客户端几乎完美地发送两个值" 1"和" 2" 。在服务器端,服务器将接收该值以检查该值是否等于" 1",电机伺服将从右向左移动,或者如果值等于2,则电机将从左侧移动对。请查看代码:

# server.py 
import socket                                         
import RPi.GPIO as IO
import time
IO.setmode(IO.BOARD)
IO.setup(12,IO.OUT)
pwm2=IO.PWM(12,50)
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = "192.168.1.10"                             
# bind to the port
s.bind((host, 18050))                                  
# queue up to 5 requests
s.listen(1)
while True:
    print("Listenng  to the client" )
    # establish a connection
    clientsocket,addr = s.accept()      
    print("Got a connection from %s" % str(addr))
    d=int(clientsocket.recv(1024))
    if d==1:
       print(d, "right to left")
       pwm2.start(12)
       time.sleep(3)
       pwm2.stop()
    elif d==2:
       print(d, "left to right") 
       pwm2.start(2)
       time.sleep(3)
       pwm2.stop()
IO.cleanup()     
s.close() 

在实施过程中,总会发生奇怪的行为。有时电机会移动,而有时则电机不移动。而且,它们只会从右到左,从左到右移动一次。结果如下:

>>
Listenng  to the client
Got a connection from ('192.168.1.9', 1313)
(1, 'right to left')                  # Movement occurs 
Listenng  to the client
Got a connection from ('192.168.1.9', 1337)
(2, 'left to right')                 # Movement occurs 
Listenng  to the client
Got a connection from ('192.168.1.9', 1383)
(1, 'right to left')                  # No Movement occurs 
Listenng  to the client
Got a connection from ('192.168.1.9', 1416)
(2, 'left to right')                    # No Movement occurs 
Listenng  to the client
Got a connection from ('192.168.1.9', 1445)
(1, 'right to left')                       # No Movement occurs 
Listenng  to the client
Got a connection from ('192.168.1.9', 1528)
(2, 'left to right')                      # No Movement occurs 
Listenng  to the client
Got a connection from ('192.168.1.9', 1574)
(1, 'right to left')             # No Movement occurs 
Listenng  to the client

请问有什么建议吗?......整个想法是通过从android活动中发送1或2来控制伺服。提前感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

3条建议:

  • 您不应该接受循环中的连接。你最好只接受一次,然后只要你需要它就可以使用这个连接。
  • 如果您不介意伺服在两次拨打服务之间打开,也许您可​​以避免启动/停止PWM引脚并只更改占空比(功能ChangeDutyCycle(xx))
  • 如果您可以使用GPIO18(引脚12),因为它是硬件PWM。软件运行良好,但他们使用DMA传输实现这可能是资源消耗(我也经历了一些延迟)