Python3 RSPI3串行对象编程

2024-04-20 07:54:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我今天用的是一个项目aGSM/GPRS RSPI module。我的工作是用AT命令将文件发送到FTP服务器(它通过Python中的一个简单程序工作,或者通过逐个发送所有AT命令来使用putty)。你知道吗

今天,为了简化代码,我选择在object中翻译代码。 此外,我创建我的类与我的所有方法,如发送短信,连接GPRS,发送FTP。。。(这些方法似乎不能简化代码)

但是当我启动程序时,我没有收到模块的确认回复。你知道吗

isReady()启动时,程序发送串行命令来测试模块。但我没有任何答复。我的串行端口配置似乎是正确的(debug()return 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)

Tags: 代码debugself程序cmdgpiotimedef