Using Python I need to call the 'configSerialPort' function several times and for that I have declared serialPort as global and it is my code:
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()
but I have this error:
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'
how can I correct it
Whenever you want to access a global variable in a function, you should declare it as global
def configSerialPort(timeout):
global serialPort
...
def ping():
global serialPort
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.