Skip to content

Instantly share code, notes, and snippets.

@johnty
Created January 14, 2022 23:57
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 johnty/341f5dbd5624a8773ff3acd33d4203e0 to your computer and use it in GitHub Desktop.
Save johnty/341f5dbd5624a8773ff3acd33d4203e0 to your computer and use it in GitHub Desktop.
// w for Fwd
//
// A simple Teensy based USB keyboard that associats some kind of
// physical motion event to a 'w' press. This can be used to advance Google StreetView
// for an interactive exercise experience (Example here: https://www.instagram.com/p/CF-xVWgJiFK/)
//
// Must select the "SERIAL+KEYBOARD..." mode under "USB TYPE" for the Teensy!
//
// This version uses a Sharp IR sensor (or equivalent), connected to A9 pin of a Teensy 3.2
//
// Can adapt easily to use some other sensor that can be associated with movement.
// (e.g. a peak detector on accelerometer attached to the body, or a hall effects sensor)
//
// info@johnty.ca
// license: CC BY-SA 4.0
// October 2020
#define THRES 350 //used for basic thresholding of IR sensor
//************************
// BEGIN Data structure code
//
// this is a very simple data structure that
// accumulates ARRAY_LEN values and then
// allows computation of the average
#define ARRAY_LEN 25
int DATA[ARRAY_LEN];
int arrPtr = 0;
void pushToArray(int val) {
DATA[arrPtr] = val;
arrPtr++;
arrPtr = arrPtr % ARRAY_LEN;
}
int computeAvg() {
int sum = 0;
for (int i = 0; i < ARRAY_LEN; i++) {
sum += DATA[i];
}
sum /= ARRAY_LEN;
return sum;
}
// END Data structure code
//************************
int minInterval = 500; //min expected time between keyboard triggers, to prevent spamming due to bad data
unsigned long t0, t1;
void setup() {
Serial.begin(115200);
t0 = millis();
}
void loop() {
// put your main code here, to run repeatedly:
int val = analogRead(A9);
pushToArray(val);
delay(5);
Serial.print("AVG = ");
Serial.println(computeAvg());
if (pkDetected(computeAvg())) {
t1 = millis();
int elapsed = t1 - t0;
//only emit if min interval has passed:
if (elapsed >= minInterval) {
t0 = t1;
Keyboard.print('w');
}
}
}
//peaks happen if we have constantly increasing values followed
// by decreasing ones; so check the sign of the delta and see when it
// switches from + to -
bool pkDetected(int val) {
if (val > THRES)
return true;
else
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment