如何用Python声明pySerial的全局变量

2024-04-28 20:32:15 发布

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

使用Python,我需要多次调用'configSerialPort'函数,为此,我已将serialPort声明为全局,这是我的代码:

import serial

comPort = 'COM5'
serialPort = None

def configSerialPort(timeout):
   serialPort = serial.Serial(port = comPort, baudrate = 9600, timeout = timeout)

def ping():
   #serialPort = serial.Serial(port = comPort, baudrate = 9600, timeout = 1)
   command = "AT\n"
   serialPort.write(command.encode('ASCII'))
   bufferRxSerial = serialPort.readline().decode('ASCII')
   if( bufferRxSerial.strip() == "OK" ):
       return True
   else:
       return False


def main():
   global serialPort
   configSerialPort(3)
   flagConexion = ping()
   if flagConexion == True:
       print('The Modem is connected!')
   else:
       print('ERROR, no connection to modem!')

main()

但我有一个错误:

File "C:/Users/WSR/AppData/Local/Programs/Python/Python39/TestSerialPort.py", line 12, in ping
serialPort.write(command.encode('ASCII'))
AttributeError: 'NoneType' object has no attribute 'write'

我怎样才能改正呢


Tags: portdefasciitimeoutserialpingcommandencode