⌚SB Watch 2
🚚 Free fedex shipping from 97 $
🌎 WORLDWIDE SHIPPING for 25 $

Atom Level

About

Did you know that PeekSmith 3 has an accelerometer inside? Let us demonstrate with this code how you can use it to create a Level Tool. For sure it is for fun, however, you will get some idea of how you can work with accelerometer data. Atom andΒ SB Watch also has an accelerometer!

We are not going to complicate the project. At first, in the main function, the code connects to a PeekSmith, then turns on the accelerometer, and starts a timer to run the vibrate function once per second.

In the onEvent function, it returns if the event is not about accelerometer data from the PeekSmith accelerometer. Then convert the string to 3 numbers, and call the onAccel method with them.

In the onAccel function, we only need the x value. It is transformed into a number between 0 and 8, and the code prints the “graphics” to the PeekSmith screen.

And finally, the vibrate function, which is running every second, the code checks if the level is middle. If yes, it sends a short vibration to PeekSmith.

				
					function main() {
    ps.connect();
    ps.print('Atom\nLevel');
    ps.accel('on');
    setInterval(vibrate, 1000);
}

function onEvent(e) {
    if (e.type !== 'xyz' || e.source !== 'ps:accel') return;
    
    let xyz = strSplit(e.value, ',');
    for (let index = 0; index < 3; index++) {
        xyz[index] = parseInt(xyz[index]);
    }
    onAccel(xyz[0], xyz[1], xyz[2]);
}

let currentLevel = -1; // unknown
let levels = [
    'O--------',
    '-O-------',
    '--O------',
    '---O-----',
    '====O====',
    '-----O---',
    '------O--',
    '-------O-',
    '--------O',
];

function onAccel(x, y, z) {
    currentLevel = ( (x / 2048) + 1) * 4.2 | 0; // calculate a number between 0 - 8
    if (currentLevel < 0) currentLevel = 0;
    if (currentLevel > 8) currentLevel = 8;
    ps.print(levels[currentLevel]);
}

function vibrate() {
    if (currentLevel === 4) ps.vibrate('.');
}
				
			

General

πŸ“ƒΒ First Steps

MagiScript Editor

πŸ“ƒΒ Basics

πŸ“ƒΒ Running Your First Program

πŸ“ƒΒ App Store

πŸ“ƒΒ Atom Settings (Editor)

πŸ“ƒΒ Debugging Techniques

Examples

πŸ“ƒΒ Atom Time

🎞️ Time Practice

πŸ“ƒΒ Atom Pi (Pi Revelations)

πŸ“ƒΒ Atom Drum

🎞️ Atom Stack

πŸ“ƒΒ Atom Square

πŸ“ƒΒ Atom Level

πŸ“ƒΒ Atom THMPR

πŸ“ƒΒ Poker Hands

πŸ“ƒΒ Keyboard Numeric

πŸ“ƒΒ Keyboard NOKIA

πŸ“ƒΒ Keyboard Cursor

πŸ“ƒΒ Keyboard Media

πŸ“ƒΒ Keyboard Custom

Input/Output

πŸ“ƒΒ Buttons

πŸ“ƒΒ Vibration Motor

πŸ“ƒΒ RGB LED

πŸ“ƒΒ Devices

πŸ“ƒΒ PeekSmith

πŸ“ƒΒ SB Watch

πŸ“ƒΒ Bluetooth Keyboard

πŸ“ƒΒ Bluetooth Mouse

πŸ“ƒΒ Timers

πŸ“ƒΒ Database

πŸ“ƒΒ Events

πŸ“ƒΒ System (exit, sleep, rand)

πŸ“ƒΒ Objects (card, time)

Language

πŸ“ƒΒ Summary

πŸ“ƒΒ Comments

πŸ“ƒΒ Variable Declarations

πŸ“ƒΒ Operators

πŸ“ƒΒ Control Flow

πŸ“ƒΒ Functions

πŸ“ƒΒ Numbers

πŸ“ƒΒ Strings

πŸ“ƒΒ Arrays

πŸ“ƒΒ Objects

πŸ“ƒΒ Uint8Array