Newbie - floating point

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
StotfoldSteve
Posts: 1
Joined: Wed Jul 26, 2017 10:12 am

Newbie - floating point

Post by StotfoldSteve » Wed Jul 26, 2017 10:17 am

Silly newbie question...

When I use math.sqrt() function I seem to get a type error. What I'm trying to do is take the XYZ accelerometer, square the values and then square root it. Further down the app will be an "if total acc>2 then" type call.

I feel stupid. Where am I going wrong. TIA

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Newbie - floating point

Post by pythoncoder » Thu Jul 27, 2017 5:02 am

Code: Select all

import pyb
import math
a = pyb.Accel()
print(math.sqrt(a.x()**2 + a.y()**2 + a.z()**2))
Note that the scaling of the accelerometer isn't evident from the docs http://docs.micropython.org/en/latest/p ... Accel.html. As far as I can see it's intended for simple tasks like basic orientation checks rather than accurate measurement.

For serious measurement it's best to use an external module such as the InvenSys MPU9150/MPU9250. Drivers are available.
Peter Hinch
Index to my micropython libraries.

User avatar
deshipu
Posts: 1388
Joined: Thu May 28, 2015 5:54 pm

Re: Newbie - floating point

Post by deshipu » Thu Jul 27, 2017 11:47 am

By the way, it's much faster to compare the squared values with squared distance, rather than take the square root and compare it with normal distance. Just a small trick.

Post Reply