Skip to content

Instantly share code, notes, and snippets.

@phstc
Created May 7, 2012 15:39
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 phstc/2628502 to your computer and use it in GitHub Desktop.
Save phstc/2628502 to your computer and use it in GitHub Desktop.
It's an Arduino experiment to count how many times Mia (my cat) eats per day, if she eats more on the week or weekend when we are at home. http://f.cl.ly/items/3E3Q3p2x2S132e1T2332/Image%202012.10.27%201:05:59%20PM.png
#include "Ultrasonic.h"
#include <SD.h>
Ultrasonic ultrasonic(7,6);
File file;
boolean eating = false;
int hour = 23;
int minu = 0;
int sec = 0;
int day = 29;
int sleepmili = 10000;
// initialDistance will be defined after the first minute that the Arduino is turned on. Mia is eating If the current distance (currDistance) is less than initialdistance.
int initialDistance = 0;
int countInitialDistance = 0;
// safeDistance is a small safe distance to guarantee if the mia's food move up.
int safeDistance = 5;
//------------------------------------------------------------------------------
void setup() {
Serial.begin(9600);
if (!SD.begin()) {
Serial.println("sd begin failed");
return;
}
}
void updateDateTime(){
sec += sleepmili / 1000;
if(sec > 60){
sec = sleepmili / 1000;
minu++;
if(minu > 60){
minu = 1;
hour++;
if(hour > 24){
hour = 1;
day++;
if(day > 30){
day = 1;
}
}
}
}
}
boolean isEating(int currDistance){
return currDistance < initialDistance && !eating;
}
boolean stoppedEating(int currDistance){
return currDistance > initialDistance && eating;
}
boolean isDefiningInitialDistance(int currDistance){
if(initialDistance == 0){
countInitialDistance += 1;
if(countInitialDistance == 6){
initialDistance = currDistance - safeDistance;
}
}
return initialDistance == 0;
}
//------------------------------------------------------------------------------
void loop()
{
updateDateTime();
int currDistance = ultrasonic.Ranging(CM);
if(!isDefiningInitialDistance(currDistance)){
if(isEating(currDistance)){
logEating(currDistance, "Mia eating");
eating = true;
} else if(stoppedEating(currDistance)) {
logEating(currDistance, "Mia stop eating");
eating = false;
}
}
delay(sleepmili);
}
void logEating(int currDistance, char *msg){
file = SD.open("eating.txt", FILE_WRITE);
file.print(day);
file.print(" - ");
file.print(hour);
file.print(":");
file.print(minu);
file.print(",");
file.print(msg);
file.print(",");
file.print(currDistance);
file.println("cm");
file.close();
// Debug output
Serial.print(day);
Serial.print(" - ");
Serial.print(hour);
Serial.print(":");
Serial.print(minu);
Serial.print(",");
Serial.print(msg);
Serial.print(",");
Serial.print(currDistance);
Serial.println("cm");
}
@phstc
Copy link
Author

phstc commented May 7, 2012

@phstc
Copy link
Author

phstc commented Nov 10, 2012

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