cannot access local variable

Typically: "How do I... ", "How can I... " questions
Post Reply
jetixmen
Posts: 14
Joined: 03 Oct 2023, 08:45

cannot access local variable

Post by jetixmen »

In my code even though I have defined a variable "guctutforD1" it says "UnboundLocalError: cannot access local variable 'guctutforD1' where it is not associated with a value".
the part where the code give error:

Code: Select all

#python

import numpy as np

T_end = 10
r = 0.5
guctutforD1=5
guctutforD2=5
P=5
D=3
I=0.25
guctoplaforI1=0;
guctoplaforI2=0;

def PID(a,b):
    derivative1= guctutforD1 - a     #here it gives error
    derivative2= guctutforD2 - b
    guctutforD1= a
    guctutforD2= b
    guctoplaforI1 += a
    guctoplaforI2 += b
    f1= (P*a + I*guctoplaforI1 + D*derivative1)
    f2= (P*b + I*guctoplaforI2 + D*derivative2)

coppelia
Site Admin
Posts: 10375
Joined: 14 Dec 2012, 00:25

Re: cannot access local variable

Post by coppelia »

Hello,

when writing code within CoppeliaSim, you need to follow the suggested script structure when attaching a new script to an object. For Python, this is typically:

non-threaded:

Code: Select all

#python

def sysCall_init():
    sim = require('sim')

    # do some initialization here
    #
    # Instead of using globals, you can do e.g.:
    # self.myVariable = 21000000

def sysCall_actuation():
    # put your actuation code here
    pass

def sysCall_sensing():
    # put your sensing code here
    pass

def sysCall_cleanup():
    # do some clean-up here
    pass

# See the user manual or the available code snippets for additional callback functions and details
threaded:

Code: Select all

#python

def sysCall_init():
    sim = require('sim')

    # Put some initialization code here
    # sim.setStepping(True) # enabling stepping mode
    #
    # Instead of using globals, you can do e.g.:
    # self.myVariable = 21000000

def sysCall_thread():
    # Put your main code here, e.g.:
    #
    # while not sim.getSimulationStopping():
    #     p = sim.getObjectPosition(objHandle, -1)
    #     p[0] += 0.001
    #     sim.setObjectPosition(objHandle, -1, p)
    #     sim.step() # resume in next simulation step
    pass

# See the user manual or the available code snippets for additional callback functions and details
Cheers

Post Reply