#include "SdFat.h"
#define SPI_SPEED SD_SCK_MHZ(4)
#define CS_PIN 10
SdFat sd;
int motionPin=2;
int doorPin=3;
int tamperPin=4;
bool motion=false;
bool doorOpened=false;
int tamperInterval=1000;
int tamperPing=0;
File file;
void setup() {
Serial.begin(9600);
if (!sd.begin(CS_PIN, SPI_SPEED)) {
if (sd.card()->errorCode()) {
Serial.println("SD initialization failed.");
} else if (sd.vol()->fatType() == 0) {
Serial.println("Can't find a valid FAT16/FAT32 partition.");
} else {
Serial.println("Can't determine error type");
}
return;
}
pinMode(motionPin, INPUT);
pinMode(doorPin, INPUT_PULLUP);
pinMode(tamperPin, INPUT_PULLUP);
}
void loop() {
String commande=Serial.readString();
commande.trim();
char buffer[32];
commande.toCharArray(buffer,32);
if(!strcmp(buffer,"logs")){
Serial.println("Logs:");
char line[32];
file=sd.open("log.txt", O_RDONLY);
while(file.fgets(line, sizeof(line)) > 0){
Serial.print(line);
}
}
else if(!strcmp(strtok(buffer," "),"log")){
char str[64];
strcpy(str,strtok(NULL,""));
file=sd.open("log.txt", O_WRITE | O_CREAT | O_APPEND); //IA
file.print("---");
file.print(str);
file.println("-------");
file.close();
}
else if(!strcmp(buffer,"clear")){
file=sd.open("log.txt", O_WRITE | O_TRUNC);
file.close();
}
if(digitalRead(motionPin)==HIGH && !motion){
file=sd.open("log.txt", O_WRITE | O_CREAT | O_APPEND); //IA
Serial.print("Detected something\n");
file.println("Detected something");
motion=true;
file.close();
}
else if(digitalRead(motionPin)==LOW && motion){
file=sd.open("log.txt", O_WRITE | O_CREAT | O_APPEND);
Serial.print("Not detecting it anymore\n");
file.println("Not detecting it anymore");
motion=false;
file.close();
}
if(digitalRead(doorPin)==HIGH && !doorOpened){
file=sd.open("log.txt", O_WRITE | O_CREAT | O_APPEND);
Serial.print("door opened\n");
file.println("door opened");
doorOpened=true;
file.close();
}
else if(digitalRead(doorPin)==LOW && doorOpened){
file=sd.open("log.txt", O_WRITE | O_CREAT | O_APPEND);
Serial.print("door closed\n");
file.println("door closed");
doorOpened=false;
file.close();
}
if(digitalRead(tamperPin)==HIGH && millis()-tamperPing>=tamperInterval){
file=sd.open("log.txt", O_WRITE | O_CREAT | O_APPEND);
Serial.print("being tampered\n");
file.println("being tampered");
file.close();
tamperPing=millis();
}
delay(500);
}