Python端感觉没什么好说的,学过一点Python基础的应该都能看得懂,至于加Try……except的原因是处理服务端掉线后反馈在Python端的异常,让脚本重新尝试连接服务器,else:那一句运行的时候直接写Pass就行。

#coding=UTF-8
try:
    while True:
        import socket
        import RPi.GPIO as GPIO
        import time
        from DRV8825 import DRV8825
        time.sleep(60)
        phone = socket.socket()
        phone.connect(('61.132.225.70',21265))   
        phone.send(bytes('ssdk'))         
        while True:                  
            data = phone.recv(10240)
            data = data.decode('GBK')
            if str(data)=='open':
                Motor1 = DRV8825(dir_pin=13, step_pin=19, enable_pin=12, mode_pins=(16, 17, 20))
                Motor1.SetMicroStep('softward','fullstep')
                Motor1.TurnStep(Dir='backward', steps=39, stepdelay = 0.005)
                #time.sleep(0.8)
                Motor1.Stop()
            elif str(data)=='close':
                Motor1 = DRV8825(dir_pin=13, step_pin=19, enable_pin=12, mode_pins=(16, 17, 20))
                Motor1.SetMicroStep('softward','fullstep')
                Motor1.TurnStep(Dir='forward', steps=31, stepdelay = 0.005)
                #time.sleep(0.8)
                Motor1.Stop()
            else:   
                phone.send(bytes('heart'))
                print(str(data))
        time.Sleep(10)
except Exception as e:
    print(e)

PS:其中steps是旋转角度,可自行测试调节大小

注:需要把保存的x.py文件加入到树莓派的开机自启里,以保证宿舍晚间断电,第二天早晨来电启动时能够正常连接服务器,代码开头的time.sleep(60)是因为树莓派自启后需要有一段时间来连接wifi,为确保连接成功所以加了60秒延迟


You got to put the past behind you before you can move on.