使用pyserial从GSM模块写入和读取AT命令数据

时间:2016-11-09 00:29:41

标签: python raspberry-pi gsm pyserial

我正在玩Raspberry Pi,Breakout BoardGSM模块。我有串行读数据的问题。它看起来非常流行,有很多空白行和各种奇怪的条目,它们看起来都是来自终端(ssh登录字段提示)。我只是试图读取AT命令的输入响应。阅读我的GSM的AT Command manual,回复非常具体,所以我希望只阅读我正在寻找的回复。我是这样的串口接口的新手,所以任何关于最佳实践的建议也将受到赞赏。

#!/usr/bin/python

import time
import serial
import traceback
import netifaces as ni
import RPi.GPIO as GPIO


def resetModule(resetModulePin):
    GPIO.output(resetModulePin, GPIO.HIGH)
    time.sleep(0.5)
    GPIO.output(resetModulePin, GPIO.LOW)
    time.sleep(0.1)


def switch(onModulePin):
    GPIO.output(onModulePin, GPIO.HIGH)
    time.sleep(2)
    GPIO.output(onModulePin, GPIO.LOW)


def writeAT():
    i = 0
    while True:
        ser.flushInput()
        ser.flush()
        out = ''
        ser.write('AT\r')
        time.sleep(1)
        if ser.inWaiting() > 0:
            out += ser.read(12)
            print 'GSM Is Up'
            return out
        else:
            i += 1
        if i > 3:
            print 'GSM Down'
            print 'Resetting Module'
            resetModule(resetModulePin)
            time.sleep(5)
            print 'Turning On GSM'
            switch(onModulePin)
            time.sleep(5)
            i = 0



try:
    resetModulePin = 15
    onModulePin = 13

    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(onModulePin , GPIO.OUT)
    GPIO.setup(resetModulePin, GPIO.OUT)

    ser = serial.Serial(port='/dev/ttyAMA0', baudrate=115200)

    ser.isOpen()
    answers = ['yes', 'y']
    while True:
        out = writeAT()
        if out != '':
            print out
            break
    question = raw_input('Do you want to powerdown GSM?:').lower()
    if question in answers:
        print 'Powering Off GSM'
        switch(onModulePin)
        ser.close()
    GPIO.cleanup()
except KeyboardInterrupt, e:
    GPIO.cleanup()
except Exception,e :
    traceback.print_exc()
    GPIO.cleanup()

输出(注意空白行)#Debugging

pi@raspberrypi:~/Desktop $ sudo python Newpy
GSM Down
Resetting Module
Turning On GSM
GSM Is Up



Do you want to powerdown GSM?:

1 个答案:

答案 0 :(得分:0)

根据this尝试ser.write('AAAAAAAT')。显然,GSM分线板上的SIM908会尝试自动检测波特率,为了做到这一点,你必须给它一些额外的数据。

修改或尝试this (post of Tue Nov 25, 2014 11:41 pm) - 检查"充电"的设置在SIM908上跳线。