简体   繁体   中英

How to keep the value of a variable despite function being called multiple times?

I have a python function that will turn the servo to the left or right everytime a button on the web interface is clicked. Currently it is working like this:

@cherrypy.expose
def turnCamera (self, **data):

    import pigpio
    import time

    servos=[4,7] #GPIO number
    pigpio.start()
    key = data['direction']
    if key=="left":
            servostatus = "left"
            print servostatus
            m=1500

    elif key=="right":
            servostatus = "right"
            print servostatus
            m=1000

    #to dispense pill
    if key=="dispense":
        m=900
        pigpio.set_servo_pulsewidth(servos[0], m) 
        servostat= "Position of servo: %s"%m
        print servostat
        time.sleep(1)
        m=1500
        pigpio.set_servo_pulsewidth(servos[0], m) 
        servostat= "Position of servo: %s"%m
        print servostat
        time.sleep(1)


    pigpio.stop()

    return servostat

The data is posted from jQuery:

$('#left_button').click(function(){
                        $.post('/turnCamera', {direction:"left"}).done(function (reply) {
                            $('#camerapos').empty().append(reply);
                            alert("left button clicked");});

                    });
                    $('#right_button').click(function(){
                        $.post('/turnCamera', {direction:"right"}).done(function (reply) {
                            $('#camerapos').empty().append(reply);
                            alert("right button clicked");});
                    });

However I would like the servo to turn such that each click will make it turns by 100. When the script is first run, it goes to initial position m=1500 . Then user can control the camera position by clicking left or right. Something like this:

m=1500
while (m >= 500 and m <= 2500):
        if (key =="left"):
            m=m+100
        elif (key =="right"):
            m=m-100

However i do understand that this will not work because m will get reset to 1500 everytime the function is triggered (button is clicked). How can i store the value of m?

You can make the method

return [servostat, m]

and then change the method so that it has a parameter where you pass in the m from the previous call like def turnCamera(self, **data, m):

As follows:

$('#left_button').click(function(){
                $.post('/turnCamera', {direction:"left",m_value:m}).done(function (reply) {
                    $('#camerapos').empty().append(reply);
                    alert("left button clicked");});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM