/*
This sketch shows you how to monitor if your Bean moves by sampling the acceleration at 5Hz and measuring change.
The LED will blink red when it's being moved.
Please note that if motion detection is triggered often, the LED use will drain the battery quickly.
This example code is in the public domain.
*/
// When acceleration change goes beyond this threshold, the LED will blink.
#define THRESHOLD 100
#define bucketMax 3000
#define leak 10
#define bucketMin 2350
AccelerationReading previousAccel;
//int bucketMax = 47000; //was 4700000
unsigned int bucket = 2400;
//int leak = 3; //was 27
int buttonState = LOW;
void setup() {
Serial.begin(9600);
Bean.setLed(0, 0, 0);
digitalWrite(0,HIGH);
pinMode(0, OUTPUT);
pinMode(4, INPUT);
digitalWrite(5,HIGH);
pinMode(5, OUTPUT);
// Turn off the Bean's LED
Bean.setLed(0, 0, 0);
// Initial reading
previousAccel = Bean.getAcceleration();
}
void loop() {
buttonState = digitalRead(4);
if (buttonState == HIGH){
digitalWrite(0,LOW);
digitalWrite(5,LOW);
Bean.setLed(0, 255, 0);
}
Bean.setLed(0, 0, 0);
// Get the current acceleration with a conversion of 3.9110-3 g/unit.
AccelerationReading currentAccel = Bean.getAcceleration();
// Find the difference between the current acceleration and that of 200ms ago.
int accelDifference = getAccelDifference(previousAccel, currentAccel);
// Update previousAccel for the next loop.
previousAccel = currentAccel;
// Check if the Bean has been moved beyond our threshold.
if(accelDifference > THRESHOLD){
// Blink the LED
if (bucket < bucketMax) {
bucket = bucket + accelDifference;
}
}
else{
if (bucket>leak) {
bucket = bucket - leak;
}
Serial.println(bucket);
delay(200);
Bean.sleep(200);
}
if (bucket <= bucketMin) {
digitalWrite(0,LOW);
digitalWrite(5,LOW);
}
else {
digitalWrite(0,HIGH);
digitalWrite(5,HIGH);
}
}
// This function calculates the difference between two acceleration readings
int getAccelDifference(AccelerationReading readingOne, AccelerationReading readingTwo){
int deltaX = abs(readingTwo.xAxis - readingOne.xAxis);
int deltaY = abs(readingTwo.yAxis - readingOne.yAxis);
int deltaZ = abs(readingTwo.zAxis - readingOne.zAxis);
// Return the magnitude
//String stringToPrint = String();
//stringToPrint = stringToPrint + bucket;
return deltaX + deltaY + deltaZ;
}
Comments