-2

I am trying to read data from a senor using my PI and in order to calculate the magnitude to determine acceleration but but I always get the following error when I run a test program

Time elasped: 0
Traceback (most recent call last):
  File "MMA7455.py", line 47, in <module>
    print("X = ", x2)
NameError: name 'x2' is not defined

This is the the code that ive been using

def calculateMag():
   x = MMA7455.getValueX()
   x2 = ((x + 128) % 256) -128

   y = MMA7455.getValueY()
   y2 = ((y - 240 + 128) % 256) -128

   z = MMA7455.getValueZ()
   z2 = ((z - 64 + 128) % 256) -128

   magnitude = int(math.sqrt((x2*x2) + (y2*y2) + (z2*z2)))

return x2, y2, z2, magnitude

for i in range (1000):
   timeGo()
   calculateMag()
   print("X = ", x2)
   print("Y = ", y2)
   print("Z = ", z2)

Ive tried passing x, y, z into the function but this didnt seem to work.Thanks for the help it would be much appreciated.

1 Answers1

0

When you return values from a function, the variable names that you gave to them within the function don't necessarily still exist outside of that function. In your case, when you call calculateMag(), the return values aren't going anywhere. Try this:

x2,y2,z2,magnitude = calculateMag()

print("X = ", x2)
print("Y = ", y2)
print("Z = ", z2)
mypetlion
  • 2,415
  • 5
  • 18
  • 22