I want to improve efficiency with Python even in an experimental system (4) Use ser.close () when an error is thrown using try syntax

Synopsis up to the last time

Up to the last time, measurement can be automated. This time, when the measuring device is in a bad mood, it will throw an error, so we will deal with it.

Windows COM port double digit or more unacceptable issue

-Microsoft Support Page --As mentioned on the above site, on Windows ** COM ports may continue to grow as the number of connected devices increases, but problems may occur when the number exceeds 10. In my environment, when ADVANTEST's R6441 is connected using a USB hub etc., measurement may fail if the COM port is 10 or more.

Resolve using try syntax

If you write the name of the exception (printed when an error occurs) after ʻexcept, you can determine the behavior when it fails. This time, I will do ser.close ()`.

try:
    while 1:
        if pulse >= MAX:
            ##End the while statement when the position reaches MAX
            break
        ##Record current location information
        pulse_list.append(pulse/2)
        ##Measure the current(Take 5 times and average it as the value at that position)
        for i in range(5):
            ser = serial.Serial(COMampere,bitRate,timeout=0.1)
            ser.write(b"F5, R0,PR2\r\n")
            time.sleep(1)
            ser.write(b"MD?\r\n")
            time.sleep(1)
            tmp = ser.read_all()
            #Skip if no current is available
            if len(tmp)== 0:
                ser.close()
                continue
            ampere = float(tmp.split()[2])
            ampere_average_list.append(ampere)
            time.sleep(1)
            ser.close()
        ##Current and pulse(position)To list
        ampere_list.append(sum(ampere_average_list)/len(ampere_average_list))
        ampere_average_list = []

        ##Move the optical table
        pulse += 1000
        position = "A:2+P"+str(pulse)+"\r\n"
        ser = serial.Serial(COMpulse,bitRate,timeout=0.1)
        ser.write(bytes(position, 'UTF-8'))
        time.sleep(1)
        ser.write(b"G:\r\n")
        ser.close()

    ##Turn the list into a dataframe
    print(ampere_list)
    print(pulse_list)
    df = pd.DataFrame({'ampere(A)':ampere_list,'pulse':pulse_list})
    def pulseToMilliMeter(pulse):
        return pulse*0.006
    df["position(mm)"] = df["pulse"].map(pulseToMilliMeter)
    df.to_csv('./csv/result.csv',index=False)
    plt.figure()
    df.plot(x='position(mm)',y='ampere(A)',marker='o')
    plt.savefig('./img/sample.png')
    plt.close('all')
except IndexError:
    ser.close()

Recommended Posts

I want to improve efficiency with Python even in an experimental system (4) Use ser.close () when an error is thrown using try syntax
I want to improve efficiency with Python even in an experimental system (2) RS232C and pySerial
I want to improve efficiency with Python even in an experimental system (1) Install Anaconda with Chocolatey
I want to improve efficiency with Python even in an experimental system (3) I want to do something like Excel with Pandas
I want to improve efficiency with Python even in the experimental system (5) I want to send a notification at the end of the experiment with the slack API
[Python] I want to know the variables in the function when an error occurs!
I get an error when I try to raise Python to 3 series using pyenv on Catalina
I know? Data analysis using Python or things you want to use when you want with numpy
When you want to use it as it is when using it with lambda memo
I want to use Temporary Directory with Python2
I got an error when I put opencv in python3 with Raspberry Pi [Remedy]
[Python] I want to use only index when looping a list with a for statement
Even in JavaScript, I want to see Python `range ()`!
I want to work with a robot in python.
I want to get an error message in Japanese with django Password Change Form
I got an error when using Tensorboard with Pytorch
I want to use the R dataset in python
I want to do something in Python when I finish
When I try to update the data on DynamoDB with Python (boto3), I get "ExpressionAttributeNames contains invalid key: Syntax error; key: <key name>"
[Solution] When I try to connect to CloudSQL with GAE, I get an ImportError only when using dev_appserver.
If you want to use field names with hyphens when updating firestore data in python
Solution when you want to use cv_bridge with python3 (virtualenv)
[Python] I want to use the -h option with argparse
Things to keep in mind when using Python with AtCoder
Things to keep in mind when using cgi with python.
I want to use a wildcard that I want to shell with Python remove
I want to solve APG4b with Python (only 4.01 and 4.04 in Chapter 4)
I want to run Rails with rails s even in vagrant environment
When I get an error with Pylint in Atom on Windows
I get an error when trying to install maec 4.0.1.0 with pip
[Python] When you want to use all variables in another file
I want to use an external library with IBM Cloud Functions
When I try to use pip, SSL module is not available.
When you want to send an object with requests using flask
I tried to improve the efficiency of daily work with Python
When I try to execute the make command of Makefile with os / exec of golang, the second and subsequent executions result in an error.
I want to debug with Python
Let's use the NAOqi OS VM. I want to resolve dependencies with pip even in Pepper development
How to write what to do when an application is first displayed in Qt for Python with Designer
Gist repository to use when you want to try a little with ansible
How to deal with OAuth2 error when using Google APIs from Python
[Python] What to do when an error related to SSL authentication is returned
Environment maintenance made with Docker (I want to post-process GrADS in Python
I want to color a part of an Excel string in Python
Try to poke DB on IBM i with python + JDBC using JayDeBeApi
I'm an amateur on the 14th day of python, but I want to try machine learning with scikit-learn
Try logging in to qiita with Python
I want to use jar from python
When I get an error with PyInstaller
I want to analyze logs with Python
How to use is and == in Python
How to build an environment when you want to use python2.7 after installing Anaconda3
I want to use Python in the environment of pyenv + pipenv on Windows 10
[python] What to do when an error occurs in send_keys of headless chrome
Three things I was addicted to when using Python and MySQL with Docker
Output timing is incorrect when standard (error) output is converted to a file in Python
Things to keep in mind when using Python for those who use MATLAB
What to do if you get an error when installing python with pyenv
When I try to use Jupiter notebook on Mac, I can only select python2
Python program is slow! I want to speed up! In such a case ...
To automatically send an email with an attachment using the Gmail API in Python