Tag Archives: Java

Wifi-based trilateration on Android

404px-Sea_island_surveyTriangulation offers a way to locate yourself in space.  Cartographers in the 1600s originally used the technique to measure things like the height of the cliff, which would be too impractical to measure directly.  Later, triangulation evolved into an early navigation system when Dutch mathematician Willebrord Snell discovered three points can be used to locate a point on a map.

While triangulation uses angles to locate points, trilateration uses lateral distances.  If we know the positions of three points P1P2, and P3, as well as our distance from each of the points, r1r2, and r3; we can look at the overlapping circles formed to estimate where we are relative to the three points. We can even extend the technique to 3D, finding the intersecting region of spheres surrounding the points.

In this project, I’d like to show how we can use the Wifi signal strength, in dB, to approximate distance from a wireless access point (AP) or router.  Once we have this distance, we can create a circle surrounding an AP to show possible locations we might occupy.  In the next part of the project, I plan to show how we can use three APs to estimate our position in a plane using concepts of trilateration. (Note: I haven’t had time to implement this, but you can use this Wiki article to implement it yourself).

Trilateration using 3 access points providing a very precise position (a) and a rougher estimate (b)

Trilateration using 3 access points providing a very precise position (a) and a rougher estimate (b)

Determining distance from decibel level

There’s a useful concept in physics that lets us mathematically relate the signal level in dB to a real-world distance.  Free-space path loss (FSPL) characterizes how the wireless signal degrades over distance (following an inverse square law):

Screen Shot 2013-07-05 at 2.36.07 PM

The constant there, 92.45, varies depending on the units you’re using for other measurements (right now it’s using GHz for frequency and km for distance).  For my application I used the recommended constant -27.55, which treats frequency in MHz and distance in meters (m).  We can re-arrange the equation to solve for d, in Java:

public double calculateDistance(double levelInDb, double freqInMHz)    {
   double exp = (27.55 - (20 * Math.log10(freqInMHz)) + Math.abs(levelInDb)) / 20.0;
   return Math.pow(10.0, exp);

Now, there are few drawbacks to this rough approximation:

  1. FSPL explicitly requires “free space” for calculation, while most Wifi signals are obstructed by walls and other materials.
  2. Ideally, we will want to sample the signal strength many times (10+) to account for varying interference.

Problem (1) will be resolved in the future by using the signal-to-noise ratio to more accurately estimate (that sounds like an oxymoron) obstructions to the wifi signal.  Problem (2) can be implemented in code by sampling many times and computing the average signal level.

Using the above code along with Android’s WifiManager and ScanResult classes, I can print out our final measurements:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

registerReceiver(new BroadcastReceiver()
	public void onReceive(Context c, Intent intent) 
		results = wifi.getScanResults();
		for (ScanResult s : results)	{
			DecimalFormat df = new DecimalFormat("#.##");
			Log.d(TAG, s.BSSID + ": " + s.level + ", d: " + 
					df.format(calculateDistance((double)s.level, s.frequency)) + "m");
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); 


And we can get back data that appears to be correct when moving further away from my test router (MAC address: 84:1b:5e:2c:76:f2):

[Image lost during host transition, but basically just showed how the distance increased]

Quickie: Which way does gravity point?


Everyone knows a compass always points north, and most people know it’s because of magnetic fields present on Earth’s surface.  There’s another force here on Earth directed to a central point, and that’s gravity.  Humans are quite adept at sensing gravity thanks to equilibrioception, where  fluid contained in structures in our inner ear provide feedback to help us stay balanced.

But machines, too, can detect gravity thanks to the simple accelerometer.  Already present in most smartphones today, accelerometers react to gravity with tiny springs, creating a voltage difference that we can measure and turn into meaningful units.

On Android, we can easily read the accelerometer data:

SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accel, SensorManager.SENSOR_DELAY_NORMAL);


public void onSensorChanged(SensorEvent event) {
	float x, y, z;
	x = event.values[0];
	y = event.values[1];
	z = event.values[2];

Using accelerometers to emulate human’s perception of gravity

I’d like to show how we can use an Android phone (even my dusty old Droid Eris) to visualize the force of gravity.  To save time, we’re only going to use two dimensions, x and y, but the technique used here can easily be extended into 3D.

Let’s represent gravity the same way students in a high school physics class would — with an arrow pointing down.  The goal would be the ability to rotate the phone (changing the x and y position), while still having that arrow point down, illustrating the direction of gravity.

The first thing we’ll need to do is convert the rectangular coordinates given to us (x and y) to a polar system (r, θ), where extracting an angle is much easier.

Thinking back to high school geometry, the inverse tangent will provide that angle directly.  Java has a built-in method, atan2(), which even gracefully handles the divide-by-zero case when x = 0. Because the image rotation I’m using is based on degrees (more on that in a moment), we can convert the radian angle to a common degree (0-360°).

double theta = Math.atan2(y, x);
double degree = ((theta * -180.0) / 3.14159) + 180;  // +180 to keep 0 on the right

That gives us the degree rotation of the phone in 2D.  We’re almost there.  To determine the degree that we would like the gravity arrow to point, we need to offset that degree, modulo 360 to keep us within the range (0-360°):

float rotateDegree = (float) ((degree + 270.0) % 360.0);

Now it’s just a matter of re-drawing the arrow image on the screen.  Android offers some fancy animation techniques, but for this quickie project, I chose to use a matrix rotation:

Matrix matrix = new Matrix();
Bitmap rotated = Bitmap.createBitmap(myImg, 0, 0, myImg.getWidth(), myImg.getHeight(),matrix, true);

With that code in place, we can finally visualize the force of gravity, at least in two dimensions:

If you are interested, you can find more educational video presentations on YouTube promoted by The Marketing Heaven.
This project was a quick one (writing this blog entry actually took longer than the code itself), but I think it’s important to show how we can figuratively “teach” a device a human trait and give them a new skill.  For instance, with a faster refresh rate and perhaps a little more accuracy, a robot can use this technique to keep itself balanced, much like humans use information from gravitational forces to stay balanced.

Github available here.

MultiType Eclipse Plugin


As part of this team project for my CS 307 software engineering course, we developed a collaborative editor plug-in for the Eclipse environment. Users are able to share source code files with other users, who can view changes made to a document by other users in real-time, and make their own viewable modifications.

The plug-in integrates seamlessly with the Eclipse IDE, and features an independent server that can be run on any port-forwarded connection. Future versions will support additional editors, with more customizable features.

Update (5/7/11)

Test-drive the plug-in and browse the source code at our project homepage, hosted on Google Code here.

Arduino-controlled Robotic Arm with Android Interface


Project hosted on Google Code [LINK].

Continuing my trend of Arduino projects, I decided to toy around with this robotic arm I got for Christmas. The arm is not the best construction, using DC motors instead of servos, but with Adafruit’s motor/stepper/servo shield kit, I think I can make it somewhat more useful.

First to go is the flimsy plastic controller. The motor shield allows up to four of the of five motor joints to be controlled with the Arduino. I want to use sikishub.com this opportunity to explore the Java serial libraries to communicate with the Arduino over the Internet in a Java applet *or* purchase an Arduino ethernet shield and send commands directly to the device (see below) https://billigastemobilabonnemang.nu/.

I suppose, as an overall goal, I would like to be able to feed my fish while away with the use of a webcam and this robotic arm.

Completed Robotic Arm connection to motor

IMAG0138_1 IMAG0135_1

This setup allows control of the maximum of four motors.  I’d rather have everything integrated into one cable, but the supplied cable didn’t have enough pins to handle 4 motors and power and ground.  That’s why I added the red/black leads shown above v.  Here’s how everything looks hooked up to the freshly soldered motor shield:



Right now the Arduino is powered by USB, and the motors are powered by the arm’s original DC power source — 4 D batteries. This can easily be changed to have the arm run off of a DC adapter.

Next up: Due to the number of pins that the motor shield requires, I won’t be able to use an ethernet shield with this project. So, Java-based serial communication it is!

Update 4/16/11

I wrote a Java application with SWT to handle the serial communication with the Arduino’s motor controller. Essentially, it relays messages over the serial line about what motor to enable. The “speed” of the motor is an illusion by using a custom TimerTask to repeatedly send requests to enable the motor (every 10ms) and then sleep the thread for a duration between each task interval, until the button is no longer pressed. This solution makes the robotic arm much more useful as it can now make very controlled movements (<1mm).

Here is a screen shot of the user interface:



Update 9/7/12

I’ve started working on this project again! I decided to clean up some of the code and create an Android app that can control the arm wirelessly (as long as it’s connected to a host PC).


Project hosted on Google Code [LINK].

Java-based Map Editor and Map Viewer

This team project consisted of two parts, both built with a Java GUI. The first half, the map editor, allows a user to mark locations and paths on an image to create an overlay graph data structure. The user can also name locations and export the saved data structure as an XML file.

The second half, the map viewer, loads the map image and XML file and uses an implementation of Djikstra’s algorithm to allow the user to find the shortest path between two selected points on the map. The map viewer also outputs the steps along the path, and adds the step costs using a scale factor to calculate the total distance of the path.

You can download a zip file containing the JAR files for MapEditor and MapViewer, along with the Purdue map image and sample XML dataset:

Run the application via:

java -jar MapEditor.jar
java -jar MapViewer.jar