Skip to content

Instantly share code, notes, and snippets.

@dmiddlecamp
Created March 23, 2016 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmiddlecamp/4e4a7d42500455d1e5be to your computer and use it in GitHub Desktop.
Save dmiddlecamp/4e4a7d42500455d1e5be to your computer and use it in GitHub Desktop.
#include "InternetButton/InternetButton.h"
#include "math.h"
/*Did you know that the SparkButton can detect if it's moving? It's true!
Specifically it can read when it's being accelerated. Recall that gravity
is a constant acceleration and this becomes very useful- you know the orientation!*/
#define AVG_COUNT 50.0
#define ARR_SIZE 50
int idx = 0;
float xArr[ARR_SIZE], yArr[ARR_SIZE], zArr[ARR_SIZE];
float avgX = 0, avgY = 0, avgZ = 0;
InternetButton b = InternetButton();
void setup() {
//lastX = lastY = lastZ = 0;
//Tell b to get everything ready to go
// Use b.begin(1); if you have the original SparkButton, which does not have a buzzer or a plastic enclosure
// to use, just add a '1' between the parentheses in the code below.
b.begin();
}
void loop(){
//How much are you moving in the x direction? (look at the white text on the board)
float xValue = abs(b.readX());
//How about in the y direction?
float yValue = abs(b.readY());
//And the z!
float zValue = abs(b.readZ());
//
// Calculate the moving average of the last 50 readings
//
xArr[idx % ARR_SIZE] = xValue;
yArr[idx % ARR_SIZE] = yValue;
zArr[idx % ARR_SIZE] = zValue;
idx++;
avgX = avgY = avgZ = 0;
for(int i=0;i<ARR_SIZE;i++) {
avgX += xArr[i];
avgY += yArr[i];
avgZ += zArr[i];
}
avgX /= AVG_COUNT;
avgY /= AVG_COUNT;
avgZ /= AVG_COUNT;
//
// Subtract the average from the current reading.
// This should cause the lights to fade to off as the button stops moving
//
xValue = avgX - xValue;
yValue = avgY - yValue;
zValue = avgZ - zValue;
//This will make the color of the Button change with what direction you shake it
//The abs() part takes the absolute value, because negatives don't work well
b.allLedsOn(abs(xValue), abs(yValue), abs(zValue));
//Wait a mo'
// Since we're delaying 50 ms, we're taking 20 readings a second.
// Since we're holding 50 points, we'll fade over a period of about 2.5 seconds.
delay(50);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment