Skip to content

Instantly share code, notes, and snippets.

Created June 3, 2015 20:29
Show Gist options
  • Save JoshuaJB/7db12d0d42a790f96897 to your computer and use it in GitHub Desktop.
Save JoshuaJB/7db12d0d42a790f96897 to your computer and use it in GitHub Desktop.
Pebble Accelerometer Variance Demo Scaffold
#include <pebble.h>
Window *my_window;
TextLayer *text_layer;
// isqrt_impl and isqrt provided by Siu Ching Pong on stackoverflow
uint32_t isqrt_impl(uint64_t const n, uint64_t const xk) {
uint64_t const xk1 = (xk + n / xk) / 2;
return (xk1 >= xk) ? xk : isqrt_impl(n, xk1);
uint32_t isqrt(uint64_t const n) {
if (n == 0) return 0;
if (n == 18446744073709551615ULL) return 4294967295U;
return isqrt_impl(n, n);
// Called with accelerometer data samples
static void display_acceleration(AccelData * data, uint32_t num_samples) {
// Compute local average
int local_x_avg = 0;
int local_y_avg = 0;
int local_z_avg = 0;
for (unsigned int i = 0; i < num_samples; i++) {
local_x_avg += data[i].x;
local_y_avg += data[i].y;
local_z_avg += data[i].z;
local_x_avg /= (int)num_samples;
local_y_avg /= (int)num_samples;
local_z_avg /= (int)num_samples;
// TODO: Compute the vector magnitude, subtract 1.04G for earth's gravity, and possibly a bit more for calibration to get the variance from 0.
// Make sure to use isqrt, the Pebble doesn't support floating point
// TODO: Create an empty display string variable large enough
// TODO: Use snprintf to format the accelerometer readings into a character stream
// TODO: Use text_layer_set_text(text_layer, char * <your string here>); to display
static void main_window_load(Window *window) {
// Setup the text layer
text_layer = text_layer_create(layer_get_bounds(window_get_root_layer(my_window)));
layer_add_child(window_get_root_layer(my_window), text_layer_get_layer(text_layer));
text_layer_set_text(text_layer, "Acquiring data...");
// Set Accelerometer to 25Hz sample rate
// Register event handler with 25 sample buffer
accel_data_service_subscribe(25, display_acceleration);
void handle_init(void) {
my_window = window_create();
// Setup main_window_load to run once the window loads
window_set_window_handlers(my_window, (WindowHandlers){.load = main_window_load});
window_stack_push(my_window, true);
void handle_deinit(void) {
// De-register event handler
int main(void) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment