Select Page

# Digital Level

Use your Phidget Accelerometer as a digital level. By using the accelerometer data to calculate tilt angles, you can built your own digital level.

## Setup

Before getting started, make sure you have the following parts.

Note: you can also use the Phidget Spatial or any Phidget with an accelerometer for this project.

### Step 1

Attach the Accelerometer Phidget to the VINT Hub and VINT Hub to your computer

## Write code (Java)

Copy the code below into a new Java project. If you need a reminder of how to do this, revisit the Getting Started Course. Insert the code below.

Not your programming language? Set your preferences so we can display relevant code examples

```  ```
import com.phidget22.*;

public class DigitalLevel {

public static void main(String[] args) throws Exception {

//Create
Accelerometer acceleration = new Accelerometer();

//Open
acceleration.open(1000);

while (true) {
//Get axis information
double x = acceleration.getAcceleration()[0];
double y = acceleration.getAcceleration()[1];
double z = acceleration.getAcceleration()[2];

//Calculate tilt angles
double pitch = Math.round(Math.toDegrees(Math.atan(x / z)));
double roll = Math.round(Math.toDegrees(Math.atan(y / z)));

System.out.println("Pitch: " + pitch + "°, Roll: " + roll + "°");

}
}
}
```
```
```  ```
package digitallevel;

import com.phidget22.*;

public class DigitalLevel {

public static void main(String[] args) throws Exception {

//Create
Accelerometer acceleration = new Accelerometer();

//Open
acceleration.open(1000);

while (true) {
//Get axis information
double x = acceleration.getAcceleration()[0];
double y = acceleration.getAcceleration()[1];
double z = acceleration.getAcceleration()[2];

//Calculate tilt angles
double pitch = Math.round(Math.toDegrees(Math.atan(x / z)));
double roll = Math.round(Math.toDegrees(Math.atan(y / z)));

System.out.println("Pitch: " + pitch + "°, Roll: " + roll + "°");

}
}
}
```
```

## Write code (Python)

Copy the code below into a new Python project. If you need a reminder of how to do this, revisit the Getting Started Course. Insert the code below.

Not your programming language? Set your preferences so we can display relevant code examples

```  ```
from Phidget22.Phidget import *
from Phidget22.Devices.Accelerometer import *
#Required for sleep statement
import time
#Required for atan
import math

#Create
accel = Accelerometer()

#Open
accel.openWaitForAttachment(1000)

while (True):
#Get axes information
x = accel.getAcceleration()[0]
y = accel.getAcceleration()[1]
z = accel.getAcceleration()[2]

#Calculate tilt angles
pitch = round(math.degrees(math.atan(x/z)))
roll = round(math.degrees(math.atan(y/z)))

print("Pitch: " + str(pitch) + "°, Roll: " + str(roll) + "°")

time.sleep(0.15)
```
```

## Write code (C#)

Copy the code below into a new C# project. If you need a reminder of how to do this, revisit the Getting Started Course. Insert the code below.

Not your programming language? Set your preferences so we can display relevant code examples

```  ```
using System;
using Phidget22;

namespace Level
{
class Program
{
static void Main(string[] args)
{

//Create
Accelerometer accel = new Accelerometer();

//Open
accel.Open(1000);

while (true)
{

// Get x,y,z acceleration
double x = accel.Acceleration[0];
double y = accel.Acceleration[1];
double z = accel.Acceleration[2];

//calculate tilt angles
double pitch = Math.Round((Math.Atan(x / z)) * (180.0 / Math.PI));
double roll = Math.Round((Math.Atan(y / z)) * (180.0 / Math.PI));

System.Console.WriteLine("Pitch: " + pitch + " degrees, Roll: " +roll + " degrees");

}
}
}
}
```
```

## Write code (Swift)

Copy the code below into a new Swift project. If you need a reminder of how to do this, revisit the Getting Started Course. Insert the code below.

Not your programming language? Set your preferences so we can display relevant code examples

```  ```
import Cocoa
import Phidget22Swift

class ViewController: NSViewController {

@IBOutlet weak var xLabel: NSTextField!
@IBOutlet weak var yLabel: NSTextField!

//Create
let accelerometer = Accelerometer()

do{
//Subscribe to event

//Open
try accelerometer.open()
}catch{
print(error)
}
}

func onAccelerationChange(sender:Accelerometer, data: (acceleration:[Double], timestamp: Double)){
DispatchQueue.main.async {
//Use information from your Phidget to change label
let x = data.acceleration[0]
let y = data.acceleration[1]
let z = data.acceleration[2]

let roll = atan(y/z)*180/Double.pi
let pitch = atan(x/z)*180/Double.pi

self.xLabel.stringValue = "Roll: " + String(roll) + " °"
self.yLabel.stringValue = "Pitch: " + String(pitch) + " °"

}
}
}

```
```

Run your program. When tilting your device, you will see the angle output change.

## Tilt Angles

In the code above we calculated two tilt angles Roll and Pitch.

## Pitch

Pitch is the side to side movement.

## Roll

Roll is the forward and backward movement.

## Tilt Angles contd.

Acceleration values in the three axis change as you move accelerometer. When the accelerometer is level or at rest, the x axis acceleration is 0, the y axis acceleration is 0, and the z axis acceleration is 1. We can use the acceleration values to calculate the angle the accelerometer is at compared to the rest position.

Trigonometry can be used to calculate the angles.

The result of these equations can be seen in the code above.

## Practice

1. Create a level using your accelerometer and tilt angles. If the Roll and Pitch are between -2 and 2 degrees, print “Object level”. Otherwise print the angles to the user.
2. If you are able to create a graphical program (for example, using Processing, Pygame, etc.), try creating a visual aspect to the level. Similar programs are available on the iPhone (shown below).
Designed by Julius Popa

### What are Phidgets?

Phidgets are programmable USB sensors. Simply plug in your sensor, write code in your favorite language and go!

Phidgets have been used by STEM professionals for over 20 years and are now available to students.

Windows

Mac OS

Raspberry Pi

Java

Python

C#

Swift

NetBeans

Processing

Eclipse

Thonny

PyCharm

PyScripter

Visual Studio

Xcode

Setting your preferred operating system, programming language and environment lets us display relevant code samples for the Getting Started Tutorial, Device Tutorials and Projects