Select Page

# Dice Roll

Use your Phidget Accelerometer to simulate shaking dice. By calculating the total magnitude of the acceleration and using a random number generator, you can detect shaking and produce a random dice roll.

## 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.

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

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

public class DiceRoll {

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

//Create
Accelerometer accelerometer = new Accelerometer();

//Open
accelerometer.open(1000);

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

//calculate the magnitude of the acceleration and print it
double totalAccel = Math.sqrt(x * x + y * y + z * z);

//compare magnitude to a threshold value
if(totalAccel > 3.0){
System.out.println("Shaking");
}

}
}
}
```
```
```  ```
package diceroll;

import com.phidget22.*;

public class DiceRoll {

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

//Create
Accelerometer accelerometer = new Accelerometer();

//Open
accelerometer.open(1000);

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

//calculate the magnitude of the acceleration and print it
double totalAccel = Math.sqrt(x * x + y * y + z * z);

//compare magnitude to a threshold value
if(totalAccel > 3.0){
System.out.println("Shaking");
}

}
}
}
```
```

## 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.

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 math operations
import math

#Create
accelerometer = Accelerometer()

#Open
accelerometer.openWaitForAttachment(1000)

while (True):
#Get acceleration values
x = accelerometer.getAcceleration()[0]
y = accelerometer.getAcceleration()[1]
z = accelerometer.getAcceleration()[2]

#calculate the magnitude of the acceleration
totalAccel = math.sqrt(x*x + y*y + z*z)

#compare magnitude to a threshold value
if(totalAccel > 3):
print("Shaking")

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.

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

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

namespace DiceRoll
{
class Program
{
static void Main(string[] args)
{
//Create
Accelerometer accelerometer = new Accelerometer();

//Open
accelerometer.Open(1000);

while (true)
{
//Get acceleration values
double x = accelerometer.Acceleration[0];
double y = accelerometer.Acceleration[1];
double z = accelerometer.Acceleration[2];

//calculate the magnitude of the acceleration
double totalAccel = Math.Sqrt(x * x + y * y + z * z);

//compare magnitude to a threshold value
if (totalAccel > 3.0)
{
Console.WriteLine("Shaking");
}

}
}
}
}
```
```

## 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.

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

```  ```
import Cocoa

import Phidget22Swift

class ViewController: NSViewController {

@IBOutlet weak var diceLabel: 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 {
//Get acceleration values
let x = data.acceleration[0]
let y = data.acceleration[1]
let z = data.acceleration[2]

//calculate the magnitude of the acceleration and print it
let totalAccel = (x*x + y*y + z*z).squareRoot()

//compare magnitude to threshold
if(totalAccel > 3.0){
self.diceLabel.stringValue = "Shaking"
}
else{
self.diceLabel.stringValue = "Not Shaking"
}
}
}
}
```
```

Run your program. You will see the text Shaking when you shake your Phidget Accelerometer with enough force.

## Practice

1. Modify the threshold value and see how it changes the behavior of your code. For example, if you modify the value from 3.0 to 5.0, what does this mean?
2. When the user has shaken the "dice", generate a random number between 1 and 6 and print the results to the console.

Hint: use the following code to generate a random number.

```  ```
//Math.random() generates a random double between 0 and 1
// Multiple by 5 to get a random number between 0 and 5
// Add 1 to get a random number between 1 and 6
//Math.round to round the number to a integer
Math.round(Math.random()*5+1);
```
```

Hint: use the following code to generate a random number.

```  ```
import random
random.randint(1,6)
```
```

Hint: use the following code to generate a random number.

```  ```
Random rnd = new Random();
rnd.Next(1, 6);
```
```

Hint: use the following code to generate a random number.

```  ```
Int.random(in: 1..<7)
```
```
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