Skip to content

Instantly share code, notes, and snippets.

@SijmenHuizenga
Last active September 27, 2017 20:47
Show Gist options
  • Save SijmenHuizenga/e038df3994889bfea5c496df9cb34262 to your computer and use it in GitHub Desktop.
Save SijmenHuizenga/e038df3994889bfea5c496df9cb34262 to your computer and use it in GitHub Desktop.
Play a tune on device movement!
/**
* Use a LSM303 to detect movement. When the chip moves than a song is played!
*
* To compile requires `piches.h` that is found here: https://www.arduino.cc/en/Tutorial/toneMelody
* And the LSM303 Library is required: https://github.com/pololu/lsm303-arduino
*/
#include <Wire.h>
#include <LSM303.h>
#include "pitches.h"
#define BUZZPIN 9
#define SENSITIVITY 350
LSM303 compass;
int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
const int buzzerPin = 9;
unsigned long buzzUntil = 0;
float lastX, lastY, lastZ, nowX, nowY, nowZ;
void setup() {
Serial.begin(9600);
Serial.println("Begin init");
pinMode(BUZZPIN, OUTPUT);
Wire.begin();
compass.init();
compass.enableDefault();
Serial.println("finished init");
}
void loop() {
readAc();
if(abs(nowX - lastX) > SENSITIVITY || abs(nowY - lastY) > SENSITIVITY || abs(nowZ - lastZ) > SENSITIVITY) {
for (int thisNote = 0; thisNote < sizeof(melody)/sizeof(int); thisNote++) {
int noteDuration = 1000 / noteDurations[thisNote];
tone(buzzerPin, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
noTone(buzzerPin);
}
readAc();
}
lastX = nowX;
lastY = nowY;
lastZ = nowZ;
delay(100);
}
void readAc(){
compass.readAcc();
nowX = compass.a.x >> 4;
nowY = compass.a.y >> 4;
nowZ = compass.a.z >> 4;
}
@SijmenHuizenga
Copy link
Author

img_20170927_223321

@SijmenHuizenga
Copy link
Author

untitled sketch_bb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment