使用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'
我怎样才能改正呢
每当您想要访问函数中的全局变量时,都应该将其声明为全局变量
相关问题 更多 >
编程相关推荐