0

I am executing following code for SIM 900A GSM module.

import serial

GPIO.setmode(GPIO.BOARD)    

port = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=1)

port.flush()

When I run the code Raspberry Pi freezes sometime. And due to repeated reboots without shutting down properly, it is corrupting SD card. I am using RPi 2. Please let me know what the problem could be.

  • 1
    Nothing in your code suggests the communication is taking place. Also, you're not closing the port, perhaps that's the reason it freezes after a couple of runs. – Dmitry Grigoryev Sep 26 '16 at 12:45
  • Can you please tell me the line of code which closes the serial port? – Ashwin Pajankar Sep 26 '16 at 13:03
  • 2
    port.close()! – Dmitry Grigoryev Sep 26 '16 at 13:05
3

pySerial objects close the port automatically when deleted. However, your script doesn't guarantee that port object will be deleted at the end of your script. You're at mercy of the garbage collector: if the GC runs before Python session closes, it will delete the object and the port will close. If Python interpreter terminates before the GC has a chance to run, the memory is freed by the OS, but the handle to the serial port may be left behind. This leads to those hard to reproduce errors you're seeing.

Do yourself a favour and learn with statement:

with serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=1) as port:
    port.flush()
    # send, receive at will

# port is guaranteed to be destroyed when you reach this line. No need to close

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.