I'm wondering how often should we open and close a serial port. Should we open it in the beginning of the program and keep it open then close it in the end of the program? Or should we open it every time we need access to it then close it soon after the access. I know open and close a serial port doesn't take much time. Please someone give some advice.
I assume you are using VISA to commuicate with your device. I would recommend that you open once and leave it open. This is especially true for serial connections since there is very little gained by opening and closing all the time. In a network environment you need to look at your use case to see which approach should be used.
Open it once and close it once.
Open it at the beginning, and close it when you're done.
Simple example :
Thank you both for help. I'd like to know if I do it multiple times, what is bad about it except the little bit performance sacrifice.
you never want to do things you don't have to do. That's the way to do it... And you say it yourself, performance sacrifice, why would you do that?
Actually open and close it once is what I did, but my coleague thinks it's better to keep it closed after the access to the port is done, this way, we can used hyperterminal or other programs to check things, I know this is the advantage of keeping it closed. If the lttle performance sacrifice is ok, then is there anything else bad about keep it open and close every time we need the port?
Nope, I don't think so. If you want to use hyperterminal in the mean while in a test environment, it's ok by me. As long as you know it's not the "good" way to go.
If you are sharing the resource then you would be a "good neighbor" if you release the resource after using it. In this case it may be best to open and close whenever you access it. If you do this though you will need to decide if you want to allow for retries to when opening the connection if you fail to open it.
In general, if you are the only application that will be using the resource open and close once. If you are in a shared environment then you should only grab the resource when you are actually using it. Other than performance there is no down side to open and closing it everytime.
This last piece of information was important to know though for us to give you good advice.