How to know if Android device is Flat on table - java

I'm using accelometer sensor to detect whether my device is flat on a table or not. The weird thing is even when I put my phone flat or rotate it on it's side the value is always between 90 and 100! This shouldn't be correct! am I missing something? Here is my code:
float[] values = event.values;
// Movement
float x = values[0];
float y = values[1];
float z = values[2];
float norm_Of_g =(float) Math.sqrt(x * x + y * y + z * z);
// Normalize the accelerometer vector
x = (x / norm_Of_g);
y = (y / norm_Of_g);
z = (z / norm_Of_g);
int inclination = (int) Math.round(Math.toDegrees(Math.acos(y)));
Log.i("tag","incline is:"+inclination);
if (inclination < 25 || inclination > 155)
{
// device is flat
Toast.makeText(this,"device flat - beep!",Toast.LENGTH_SHORT);
}
Edit: I'm using this code : How to measure the tilt of the phone in XY plane using accelerometer in Android

You're using the y-axis instead of the z-axis as used in the answer you linked.
The value of acos will be near-zero when the argument is near one (or near 180 degrees when near negative one), as seen in this picture:
As such, your inclination will be near zero (or 180) degrees only when the y axis is normalized to about one or negative one, eg when it is parallel to gravity, (thus, the device is "standing up").
If there's no other error, simply switching from:
int inclination = (int) Math.round(Math.toDegrees(Math.acos(y)));
to
int inclination = (int) Math.round(Math.toDegrees(Math.acos(z)));
should do it.

I used the code on this page Motion Sensors
public void onSensorChanged(SensorEvent event){
// In this example, alpha is calculated as t / (t + dT),
// where t is the low-pass filter's time-constant and
// dT is the event delivery rate.
final float alpha = 0.8;
// Isolate the force of gravity with the low-pass filter.
gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];
// Remove the gravity contribution with the high-pass filter.
linear_acceleration[0] = event.values[0] - gravity[0];
linear_acceleration[1] = event.values[1] - gravity[1];
linear_acceleration[2] = event.values[2] - gravity[2];
}
The intention of this is to factor out the force of gravity (over repeated measurements) in the accelerometer values, leaving just the acceleration component in each direction.
The force of gravity is measured along each axis, so once you know which axis represents the device lying flat, you can just check if the majority of the force of gravity lays in just that axis. That would mean the device is laying flat on the table.
You can also look at the linear acceleration to make sure the device isn't moving.

Related

Calculate target Pixels from given Angle

What i want :
I am using Orientation Sensor to get Azmuth value (Angle). i am also taking starting point from user and draw a circle. Now i want to draw next pixel on the point where the user is heading considering that one step is equal to 30 pixels.
As user starts walking i want to draw circles of user current position on the image of floor plan inserted on screen. I can't use GPS for this solution due to certain reasons.
Here are steps i am performing :
Get current user direction in angles from Orientation sensor.
User will touch on screen to draw starting point on image.
As user starts walking it will draw points on the image relative to user's real world direction like i showed in above image. How can i certainly achieve this given only starting point(pixelX,pixelY) and start angle of user and current angle where he just faced.
What we have achieved so far :
We can draw straight lines on 4 angles i.e 0 , 90,180 and 270 by just adding and subtracting pixels to current pixels.
newAzimuth is current angle of user direction
if (newAzimuth >= 45 && newAzimuth <= 135) {
startX = startX + oneStepPixelsWidth;
mScreenRotationTextView.setText("You turned (Right)");
} else if (newAzimuth > 135 && newAzimuth <= 225) {
mScreenRotationTextVniew.setText("You turned (Back)");
startY = startY + oneStepPixelsHeight;
} else if (newAzimuth > 225 && newAzimuth <= 315) {
mScreenRotationTextView.setText("You turned (Left)");
startX = startX - oneStepPixelsWidth;
} else if (newAzimuth > 315 || newAzimuth < 45) {
mScreenRotationTextView.setText("You turned (Front)");
startY = startY - oneStepPixelsHeight;
}
Given that calculated angles are:
Here's the equations for that.
X=distance*cos(angle)
Y=distance*sin(angle)
In your case distance will always be 30 pixel
so (30Cos(Angle),30Sin(Angle)) will give you your location.
To adjust your calculated angle to work you can rotate them with those formulas;
adjustedX = x cos(angle) − y sin(angle)
adjustedY = y cos(angle) + x sin(angle)
By exemple if the angle calculated are like this:
Then you will need to;
Rotate 90 degree right or 270 degree left.
Translate.
Rotate 270 degree right or 90 degree left.
private Pair<Double, Double> getPositionOf(Pair<Double, Double> lastPosition, double angle, int distance, int angleAdjustment)
{
final Pair<Double, Double> rotatedLeftPosition = rotateLeft(lastPosition, 360 - angleAdjustment);
final Pair<Double, Double> translatedLocation = applyTranslationTo(rotatedLeftPosition, angle, distance);
return rotateLeft(translatedLocation, angleAdjustment);
}
private Pair<Double, Double> rotateLeft(Pair<Double, Double> position, double degreeAngle)
{
double x = position.first;
double y = position.second;
double adjustedX = (x * Math.cos(degreeAngle)) - (y * Math.sin(degreeAngle));
double adjustedY = (y * Math.cos(degreeAngle)) + (x * Math.sin(degreeAngle));
return new Pair<>(adjustedX, adjustedY);
}
#NotNull
private Pair<Double, Double> applyTranslationTo(final Pair<Double, Double> position, final double angle, final int distance)
{
double x = distance * Math.cos(angle);
double y = distance * Math.sin(angle);
return new Pair<>(position.first + x, position.second + y);
}
Where angleAdjustment will be 90

Move camera to the direction it's facing

I have a camera that has X, Y and Z Coordinates.
The camera also has a Yaw and a pitch.
int cameraX = Camera.getX();
int cameraY = Camera.getY();
int cameraZ = Camera.getZ();
int cameraYaw = Camera.getYaw();
int cameraPitch = Camera.getPitch();
The yaw has 2048 units in 360 degrees, so at 160 degrees the getYaw() method will return 1024.
Currently I move the camera forward by just setting the Y + 1 in each loop.
Camera.setY(Camera.getY() + 1);
How would I set the camera X and Y to the direction I'm facing (The Yaw)?
I don't want to use the pitch in this situation, just the Yaw.
If I understand your question correctly, you're trying to get the camera to move in the direction you're looking (in 2D space, you're only moving horizontally).
I made a small LookAt header-only library for C++, but here is part of it rewritten in Java. What this code does is it takes a rotation and a distance, then calculates how far you need to move (in both the x and y coordinate) to get there.
// Returns how far you need to move in X and Y to get to where you're looking
// Rotation is in degrees, distance is how far you want to move
public static double PolarToCartesianX(double rotation, double distance) {
return distance * Math.cos(rotation * (Math.PI / 180.0D));
}
public static double PolarToCartesianY(double rotation, double distance) {
return distance * Math.sin(rotation * (Math.PI / 180.0D));
}

Rotation animation with custom view

I have a custom View, IndicatorView, which is essentially a triangle that orients itself according to a specified angle of a circle with a radius equal to the triangle's length. The angle the triangle points to is frequently updated and I would like to animate between these two positions similar to how a hand on a clock moves. Below is an illustration of my custom view (not drawn proportionally or to scale; drawn according to the Android View coordinate plane):
In the IndicatorView class, I draw the triangle using a Path object and three PointF objects:
#Override
protected void onDraw(Canvas canvas){
path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
//a, b, and c are PointF objects
path.moveTo(a.x, a.y);
path.lineTo(b.x, b.y);
path.lineTo(c.x, c.y);
path.close();
canvas.drawPath(path, paint);
}
To calculate the different points, given the angle, I use parametric equations:
public void showAngle(){
//x = centerX + radius * cos(angle)
//y = centerY + radius * sin(angle)
//TODO sloppy; tidy up / optimize once finished
//centerX, centerY, length, and bottomWidth are all values
//calculated in onSizeChanged
a = new PointF((float) (centerX + (length * Math.cos(angle))), (float) (centerY + (length * Math.sin(angle))));
//perpendicular bilateral radius
double pRadius = bottomWidth / 2;
//perpendicular angle plus or minus 90 degrees depending on point
float pAngle = angle - 90;
pAngle = (pAngle < 0) ? 360 - Math.abs(pAngle) : pAngle;
pAngle = (pAngle > 360) ? pAngle % 360 : pAngle;
b = new PointF((float) (centerX + (pRadius * Math.cos(pAngle))), (float) (centerY + (pRadius * Math.sin(pAngle))));
pAngle = angle + 90;
pAngle = (pAngle < 0) ? 360 - Math.abs(pAngle) : pAngle;
pAngle = (pAngle > 360) ? pAngle % 360 : pAngle;
c = new PointF((float) (centerX + (pRadius * Math.cos(pAngle))), (float) (centerY + pRadius * Math.sin(pAngle)));
invalidate();
}
When I have a new angle, I use an ObjectAnimator to animate between the two angles. I place an AnimatorUpdateListener on the ObjectAnimator and call my showAngle() method in my IndicatorView using the intermediate values specified from the Animator:
public void updateAngle(float newAngle){
//don't animate to an angle if the previous angle is the same
if(view.getAngle() != newAngle){
if(anim != null && anim.isRunning()){
anim.cancel();
}
anim = ObjectAnimator.ofFloat(view, "angle", view.getAngle(), newAngle);
anim.setDuration(duration);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
if(view != null){
view.showAngle();
}
}
});
}
}
However, this code produces some strange and unexpected behavior:
The width size of the triangle changes somewhat drastically. This could be due to casting between different types but it shouldn't be that dramatic.
The point of the triangle never stops at the specified angle. Instead it just keeps moving in a circle.
The angle seems to dictate the animations speed rather than where the triangle should stop.
Sometimes it seems as though there are numerous triangles on the screen. This could be due to the speed, perhaps it's moving very fast.
Obviously, somewhere along the line my calculations must be incorrect, though, I'm struggling to find out where I went wrong. Question(s): Is there a more efficient way of getting my custom view to animate rotation to a given angle? If I am approaching this correctly, where am I going wrong?
So, the solution to my problem was rather simple but simple enough to be overlooked. The angle field that was being used for the calculations was in degrees and it just had to be converted to radians in order for it to work with the sin and cos methods.
Change all PointF instantiations, for instance:
a = new PointF((float) (centerX + (length * Math.cos(angle))), (float) (centerY + (length * Math.sin(angle))));
to use the angle in radians:
a = new PointF((float) (centerX + (length * Math.cos(Math.toRadians(angle))),
(float) (centerY + (length * Math.sin(Math.toRadians(angle)))));
Also, part of the problem was due to sound constantly being analyzed and the View being updated before the previous animation had time to render a few frames. This led to the IndicatorView hardly moving when the angle was being updated often and when it was not it would quickly move to its destination. This happens because the previous animation is canceled before another animation is set (which is necessary to prevent a delay). This is a tricky problem to fix but one optimization I found was to avoid starting a new animation if the current angle and the previous angle were relatively close to each other.
Hopefully this will be useful for someone stuck with a similar problem. This was all part of a guitar tuner project I was working on and the source can be found on GitHub.

move bitmap from (x,y) to (x2,y2) how to compute x,y values between start and destination

Is there a way to move a bitmap from point1 to point 2 using the angle?
x += speed * Math.sin(getAngle(pointDestination));
y += speed * Math.cos(getAngle(pointDestination));
edit:
public double getAngle(Point target) {
double angle = (Math.atan2(target.y - y, target.x - x));
double angledeg = angle*0.0174532925;
return angledeg;
}
Should getAngle() be executed on every iteration or just once at the beginning?
Unfortunately the sprite moves to a wrong direction.
Your problem is that you increment the x value and when you go to increment the y too you are using the new x that you just incremented to calculate the angle.
Change it to:
float angle=getAngle(pointDestination);
x += speed * Math.cos(angle);
y += speed * Math.sin(angle);
public double getAngle(Point target) {
return Math.atan2(target.y - y, target.x - x);
}
Instead of doing a incremental update of the bitmap position, you better define a (mathematical) function that computes the position (x, y) over time. The advantage is that this will result in very exact and predictable movements independent of CPU speed / frames per second.
Assuming that the bitmap should move at constant speed from (x1, y1) to (x2, y2) in time milliseconds, so your (time dependent) position functions are as follows:
x(t) := x1 + (x2 - x1) * t / time // t in range [0, time]
y(t) := y1 + (y2 - y1) * t / time // t in range [0, time]
(Note: By doing some physics/maths, you can define more sophisticated functions that result in more complex movements).
This two functions can then be used in your animation thread to update the position of the bitmap:
bitmap.setX(x(currentTime - animationStartTime));
bitmap.setY(y(currentTime - animationStartTime));
Have a look at Trident animation library. It supports multiple UI frameworks and seems to be exactly what you're looking for!
Update: In case you really want to do a incremental update, e.g. based on your current frame rate, you don't need trigonometric functions (sin, cos, tan, ...) at all, just vectors:
// x, y is the current position of the bitmap
// calculate vector (dx, dy) to target:
double dx = x2 - x;
double dy = y2 - y;
// calculate length of this vector:
double l = Math.hypot(dx, dy); // calculates sqrt(dx² + dy²)
// calculate unit vector of (dx, dy):
double vx = dx / l;
double vy = dy / l;
// update bitmap position:
// distance is the number of pixels to travel in this iteration (frame)
x += distance * vx;
y += distance * vy;
Note that all values should be of type double. Otherwise, if int is used for x and y and the increment is lower than 1 (e.g. due to slow movement, i.e. distance is very low), the bitmap won't move at all due to rounding errors!
Also note that in this approach you have to measure the frame rate to adjust distance accordingly to compensate deviation. The formula could be something like:
double distance = (time elapsed since last frame in sec) * (distance to travel per sec)

How to draw a smooth line through a set of points using Bezier curves?

I need to draw a smooth line through a set of vertices. The set of vertices is compiled by a user dragging their finger across a touch screen, the set tends to be fairly large and the distance between the vertices is fairly small. However, if I simply connect each vertex with a straight line, the result is very rough (not-smooth).
I found solutions to this which use spline interpolation (and/or other things I don't understand) to smooth the line by adding a bunch of additional vertices. These work nicely, but because the list of vertices is already fairly large, increasing it by 10x or so has significant performance implications.
It seems like the smoothing should be accomplishable by using Bezier curves without adding additional vertices.
Below is some code based on the solution here:
http://www.antigrain.com/research/bezier_interpolation/
It works well when the distance between the vertices is large, but doesn't work very well when the vertices are close together.
Any suggestions for a better way to draw a smooth curve through a large set of vertices, without adding additional vertices?
Vector<PointF> gesture;
protected void onDraw(Canvas canvas)
{
if(gesture.size() > 4 )
{
Path gesturePath = new Path();
gesturePath.moveTo(gesture.get(0).x, gesture.get(0).y);
gesturePath.lineTo(gesture.get(1).x, gesture.get(1).y);
for (int i = 2; i < gesture.size() - 1; i++)
{
float[] ctrl = getControlPoint(gesture.get(i), gesture.get(i - 1), gesture.get(i), gesture.get(i + 1));
gesturePath.cubicTo(ctrl[0], ctrl[1], ctrl[2], ctrl[3], gesture.get(i).x, gesture.get(i).y);
}
gesturePath.lineTo(gesture.get(gesture.size() - 1).x, gesture.get(gesture.size() - 1).y);
canvas.drawPath(gesturePath, mPaint);
}
}
}
private float[] getControlPoint(PointF p0, PointF p1, PointF p2, PointF p3)
{
float x0 = p0.x;
float x1 = p1.x;
float x2 = p2.x;
float x3 = p3.x;
float y0 = p0.y;
float y1 = p1.y;
float y2 = p2.y;
float y3 = p3.y;
double xc1 = (x0 + x1) / 2.0;
double yc1 = (y0 + y1) / 2.0;
double xc2 = (x1 + x2) / 2.0;
double yc2 = (y1 + y2) / 2.0;
double xc3 = (x2 + x3) / 2.0;
double yc3 = (y2 + y3) / 2.0;
double len1 = Math.sqrt((x1-x0) * (x1-x0) + (y1-y0) * (y1-y0));
double len2 = Math.sqrt((x2-x1) * (x2-x1) + (y2-y1) * (y2-y1));
double len3 = Math.sqrt((x3-x2) * (x3-x2) + (y3-y2) * (y3-y2));
double k1 = len1 / (len1 + len2);
double k2 = len2 / (len2 + len3);
double xm1 = xc1 + (xc2 - xc1) * k1;
double ym1 = yc1 + (yc2 - yc1) * k1;
double xm2 = xc2 + (xc3 - xc2) * k2;
double ym2 = yc2 + (yc3 - yc2) * k2;
// Resulting control points. Here smooth_value is mentioned
// above coefficient K whose value should be in range [0...1].
double k = .1;
float ctrl1_x = (float) (xm1 + (xc2 - xm1) * k + x1 - xm1);
float ctrl1_y = (float) (ym1 + (yc2 - ym1) * k + y1 - ym1);
float ctrl2_x = (float) (xm2 + (xc2 - xm2) * k + x2 - xm2);
float ctrl2_y = (float) (ym2 + (yc2 - ym2) * k + y2 - ym2);
return new float[]{ctrl1_x, ctrl1_y, ctrl2_x, ctrl2_y};
}
Bezier Curves are not designed to go through the provided points! They are designed to shape a smooth curve influenced by the control points.
Further you don't want to have your smooth curve going through all data points!
Instead of interpolating you should consider filtering your data set:
Filtering
For that case you need a sequence of your data, as array of points, in the order the finger has drawn the gesture:
You should look in wiki for "sliding average".
You should use a small averaging window. (try 5 - 10 points). This works as follows: (look for wiki for a more detailed description)
I use here an average window of 10 points:
start by calculation of the average of points 0 - 9, and output the result as result point 0
then calculate the average of point 1 - 10 and output, result 1
And so on.
to calculate the average between N points:
avgX = (x0+ x1 .... xn) / N
avgY = (y0+ y1 .... yn) / N
Finally you connect the resulting points with lines.
If you still need to interpolate between missing points, you should then use piece - wise cubic splines.
One cubic spline goes through all 3 provided points.
You would need to calculate a series of them.
But first try the sliding average. This is very easy.
Nice question. Your (wrong) result is obvious, but you can try to apply it to a much smaller dataset, maybe by replacing groups of close points with an average point. The appropriate distance in this case to tell if two or more points belong to the same group may be expressed in time, not space, so you'll need to store the whole touch event (x, y and timestamp). I was thinking of this because I need a way to let users draw geometric primitives (rectangles, lines and simple curves) by touch
What is this for? Why do you need to be so accurate? I would assume you only need something around 4 vertices stored for every inch the user drags his finger. With that in mind:
Try using one vertex out of every X to actually draw between, with the middle vertex used for specifying the weighted point of the curve.
int interval = 10; //how many points to skip
gesture.moveTo(gesture.get(0).x, gesture.get(0).y);
for(int i =0; i +interval/2 < gesture.size(); i+=interval)
{
Gesture ngp = gesture.get(i+interval/2);
gesturePath.quadTo(ngp.x,ngp.y, gp.x,gp.y);
}
You'll need to adjust this to actually work but the idea is there.

Categories