首页 > 解决方案 > Python3 RSPI3 串行对象编程

问题描述

我今天在一个项目中使用GSM/GPRS RSPI 模块。我的工作是使用 AT 命令将文件发送到 FTP 服务器(它通过 Python 中的简单程序或通过 putty 逐个发送所有 AT 命令来工作)。

今天,为了简化我的代码,我选择在 object 中翻译代码。另外,我用我所有的方法创建了我的类,比如发送 SMS、connectGPRS、sendFTP ......(这些方法似乎没有简化代码)

但是当我启动我的程序时,我没有收到来自模块的确认回复。

启动时isReady(),程序发送串口命令对模块进行测试。但我没有任何答复。我的串口配置似乎正确(debug()返回 ttyAMA0),我可以使用 Putty 控制我的模块。但是当我用 Tx 和 Rx 做短路时,我看不到 Putty 上程序的请求。

sys.exit(0)然后我的程序停止ser.isReady()返回false。

所以我的问题是:在对象编程中是否可以像我使用的那样使用串行端口?还是我的代码出错了?

问候。(顺便说一句,我的法语)

import serial

print("Reset du module")
resetModem()
time.sleep(5)

ser = ConnexionModule(SERIAL_PORT, 9600, 5)

if not ser.isReady():
    print("Failed reboot, maybe a another program connected on serial, or the device isn't lauched")
    sys.exit(0)

#debug() is a print function
def debug(text):
    if VERBOSE:
        print("Debug:---", text)

# This class is in reality in a another file imported in main
class ConnexionModule():
    def __init__(self,serial_port,baudrate,timeout):
        self.ser = serial.Serial(serial_port, baudrate, timeout)

    # Testing if the module is ready to be used
    def isReady(self):
        # Resetting to defaults
        cmd = 'ATZ\r'
        # When i send 'ATZ' the module return 'OK'
        debug("Cmd: " + cmd)
        self.serialwrite(cmd,2)
        reply = self.ser.read(self.ser.inWaiting())
        reply = reply.decode("utf-8")
        time.sleep(8) # Waiting for a reply
        debug("Reply: " + reply)
        return ("OK" in reply)

    def serialwrite(self,cmd,slp):
        debug("Sending:")
        debug(self.ser.port)
        debug(cmd)
        self.ser.write(cmd.encode())
        time.sleep(slp)

此代码有效:

import serial

print("Reset du module")
resetModem()
ser = serial.Serial(SERIAL_PORT, baudrate = 9600, timeout = 5)
if not isReady(ser):
    print("Fail reboot")
    sys.exit(0)

def isReady(pserial):
    # Resetting to defaults
    cmd = 'ATZ\r'
    debug("Cmd: " + cmd)
    serialwrite(pserial,cmd,2)
    reply = pserial.read(pserial.inWaiting())
    reply = reply.decode("utf-8")
    time.sleep(8)
    debug("Reply: " + reply)
    return ("OK" in reply)

def debug(text):
    if VERBOSE:
        print("Debug:---", text)

def resetModem():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(P_RESET, GPIO.OUT)
    GPIO.output(P_RESET, GPIO.LOW)
    time.sleep(0.5)
    GPIO.output(P_RESET, GPIO.HIGH)
    time.sleep(0.5)
    GPIO.output(P_RESET, GPIO.LOW)
    time.sleep(3)

标签: pythonobjectserial-portraspberry-pi3at-command

解决方案


推荐阅读