software 原文存档
树莓派运行python操作串口发送AT命令程序
ATZ是恢复出厂设置
AT&W 是保存设置
`#!/usr/bin/python # -*- coding:utf-8 -*- import RPi.GPIO as GPIO import serial import time ser = serial.Serial('/dev/ttyS0',115200) ser.flushInput() def send_at(command,back,timeout): rec_buff = '' ser.write((command+'\r\n').encode()) time.sleep(timeout) if ser.inWaiting(): time.sleep(0.5)#目测是这里之前太快了,导致没来得及读取返回命令 rec_buff = ser.read(ser.inWaiting()) if rec_buff != '': if back not in rec_buff.decode(): print(command + ' ERROR') print(command + ' back:\t' + rec_buff.decode()) return 0 else: str_4g=rec_buff.decode() print(rec_buff.decode()) # if len(str_4g)>50: # print(float(str_4g[25:27])+float(str_4g[27:36])/60) # print(float(str_4g[39:42])+float(str_4g[42:51])/60) return 1 else: print('4G is not ready') return 0 def get_call(): # AT$QCRMCALL=1,1 send_at('AT$QCRMCALL=1,1','OK',1) # 执行程序 try: # 进行拨号 get_call() except: if ser != None: ser.close() if ser != None: ser.close()`
下面的比上面的效果好
`import serial class AtCommand: def __init__(self): self.ser = None def open(self, port, rd_timeout=1): # Open searil port self.ser = serial.Serial(port,115200, timeout=rd_timeout) def close(self): # Close searil port self.ser.close() def send_at(self, cmd): cmd_ex = cmd + '\r\n' print 'Sending ' + cmd + ' ...' self.ser.write(cmd_ex) def check_at_resp(self, exp_str, max_size=200): ''' It reads AT response and checks if there is any error. All AT response string will be returned if no error, otherwise None will be returned. ''' ret = self.ser.read_until(exp_str + '\r\n', max_size) if not exp_str in ret: print "Actual AT response is: ", ret, "\nBut expected response is: ", exp_str ret = None return ret def parse_at_resp(self, targ_str, at_resp): ''' It extracts the line including target string, then return the string after target string at the same line. None will be returned in case of any error ''' for cur_line in at_resp.split('\r\n'): if targ_str in cur_line: # Remove leading and trailing whitespace chars and target string return cur_line.replace(targ_str, '').strip() else: return None if __name__ == "__main__": test_at = AtCommand() test_at.open('/dev/ttyS0') test_at.send_at('AT') print test_at.check_at_resp('OK')`