#include <SPI.h> // Include SPI library if using an Ethernet shield
#include <Ethernet.h> // Include Ethernet library (replace with Wi-Fi library if applicable)
// the media access control (ethernet hardware) address for the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Replace these with your MySQL server details
const char* server = "localhost";
const int port = 3306;
const char* user = "root";
const char* password = "";
const char* database = "cs423";
EthernetClient client; // Ethernet client for communication (replace with WiFiClient if using Wi-Fi)
int ledPin = 4;
int pirPin = 2;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(pirPin, INPUT);
// Connect to the Ethernet shield (replace with Wi-Fi connection if applicable)
if (Ethernet.begin(mac) != 0) {
Serial.println("Failed to connect to Ethernet shield");
while (true);
}
Serial.print("IP address: ");
Serial.println(Ethernet.localIP());
}
void loop() {
int motion = digitalRead(pirPin);
if (motion != digitalRead(pirPin)) { // Check for change in sensor state (debouncing)
unsigned long currentTime = millis();
static unsigned long lastDebounceTime = 0;
if ((currentTime - lastDebounceTime) > 50) { // Debounce time in milliseconds
lastDebounceTime = currentTime;
if (motion == HIGH) {
Serial.println("Motion detected, light activated");
digitalWrite(ledPin, HIGH);
insertIntoMySQL("activated");
} else {
Serial.println("Motion stopped, light deactivated");
digitalWrite(ledPin, LOW);
insertIntoMySQL("deactivated");
}
}
}
delay(500); // Reduce delay to check sensor more frequently (adjust as needed)
}
void insertIntoMySQL(const char* state) {
// Connect to the MySQL server
if (!client.connect(server, port)) {
Serial.println("Connection failed");
return;
}
// Create a formatted timestamp string
char timestamp[20];
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
Serial.println("Failed to get local time");
client.stop();
return;
}
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", &timeinfo);
// Build the SQL query string
String query = "INSERT INTO sensor_data (datetime, state) VALUES ('";
query += timestamp;
query += "', '";
query += state;
query += "')";
// Send the query to the server
Serial.print("Sending query: ");
Serial.println(query);
client.print("USE ");
client.println(database);
client.print(query);
client.println();
// Wait for a response (optional, for debugging)
boolean waiting = true;
while (waiting && client.connected()) {
char c = client.read();
Serial.write(c);
if (c == '\n') {
waiting = false;
}
}
client.stop();
}