The Internet of Things (IoT) has revolutionized the tech industry, driving the development of new sensors to gather more data. With 18 years of experience in the tech corporate sector, I’ve advised multiple IoT companies on optimizing their data pipelines. In this tech post, I’ll guide you through building a simple yet powerful IoT home automation system that enables smart control of devices like lights, fans, and appliances via the internet. Using an Arduino board, AWS Lambda for serverless API execution, and a MySQL database to store device status, you’ll gain a deep understanding of IoT.
By following this step-by-step tutorial, you will:
- Programme an Arduino to control devices via a relay.
- Automate device status control using AWS Lambda (Serverless API).
- Store and retrieve device data from a MySQL database.
Prerequisites
Hardware:
- Arduino (Uno/Nano): To control appliances.
- Relay Module: To switch appliances on/off.
- Wi-Fi Module (ESP8266 or ESP32): To enable internet communication.
- Home Devices: Such as lights or fans.
- Power Supply: For the Arduino board.
Software:
- AWS Lambda: To handle automation logic.
- AWS API Gateway: To create the API endpoint.
- MySQL Database: To store device statuses.
- Arduino IDE: For writing and uploading code.
- Postman: For testing API requests.
Step 1: Arduino Setup to Control Devices
First, connect the relay module to the Arduino, which will control the switching of home devices. Use a Wi-Fi module (ESP8266/ESP32) to send HTTP requests to an API endpoint, which will dictate whether to turn a device on or off.
Here’s the Arduino code to control a device (like a light) based on the status fetched from the API:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "your-SSID";
const char* password = "your-password";
const char* apiEndpoint = "http://<your-api-url>/device-status"; // API endpoint for device status
int relayPin = 2; // Pin connected to relay module
void setup() {
Serial.begin(115200);
pinMode(relayPin, OUTPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
HTTPClient http;
WiFiClient client;
http.begin(client, apiEndpoint);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println("Device Status: " + payload);
if (payload == "ON") {
digitalWrite(relayPin, HIGH); // Turn on the device
} else {
digitalWrite(relayPin, LOW); // Turn off the device
}
} else {
Serial.println("Error fetching device status");
}
http.end();
delay(60000); // Check every minute (60 seconds)
}
Step 2: Setting Up MySQL for Device Status Storage
Next, configure a MySQL database to store the current status of the home devices (ON or OFF). This will enable persistent storage and retrieval of device statuses.
SQL Schema for MySQL Database:
CREATE DATABASE IoT_HomeAutomation;
USE IoT_HomeAutomation;
CREATE TABLE DeviceStatus (
id INT AUTO_INCREMENT PRIMARY KEY,
device_name VARCHAR(50) NOT NULL,
status VARCHAR(10) NOT NULL,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
-- Insert default device status
INSERT INTO DeviceStatus (device_name, status) VALUES ('Light', 'OFF');
Step 3: Building the AWS Lambda Function
Your AWS Lambda function will act as the backend service, communicating with the MySQL database to fetch or update device statuses based on API calls. Use Python and the pymysql
library to connect Lambda to the MySQL instance.
Here’s the Python code for the Lambda function that retrieves the device status:
import pymysql
import json
# MySQL database connection settings
db_host = "your-db-endpoint"
db_user = "your-username"
db_password = "your-password"
db_name = "IoT_HomeAutomation"
def lambda_handler(event, context):
# Connect to MySQL database
connection = pymysql.connect(host=db_host, user=db_user, password=db_password, database=db_name)
# Query to get device status
with connection.cursor() as cursor:
sql = "SELECT status FROM DeviceStatus WHERE device_name = %s"
cursor.execute(sql, ('Light',))
result = cursor.fetchone()
status = result[0]
# Close database connection
connection.close()
return {
'statusCode': 200,
'body': json.dumps({'status': status})
}
Step 4: Creating an API with AWS API Gateway
Now, expose the Lambda function via AWS API Gateway to make it accessible to your Arduino device.
- Log in to AWS and navigate to API Gateway.
- Create a new REST API.
- Define a GET method to call your Lambda function.
- Deploy the API and note the URL endpoint.
This API will be used by the Arduino code to fetch the device status and control the relay.
Step 5: Updating Device Status via the API
You can also create a second Lambda function to allow device status updates through the API. The following Python code updates the device status in the MySQL database:
import pymysql
import json
db_host = "your-db-endpoint"
db_user = "your-username"
db_password = "your-password"
db_name = "IoT_HomeAutomation"
def lambda_handler(event, context):
# Get status from API query string
status = event['queryStringParameters']['status']
# Connect to MySQL database
connection = pymysql.connect(host=db_host, user=db_user, password=db_password, database=db_name)
# Update device status
with connection.cursor() as cursor:
sql = "UPDATE DeviceStatus SET status = %s WHERE device_name = %s"
cursor.execute(sql, (status, 'Light'))
connection.commit()
# Close database connection
connection.close()
return {
'statusCode': 200,
'body': json.dumps({'message': 'Device status updated successfully!'})
}
Step 6: Testing the API with Postman
To test the APIs for both retrieving and updating the device status, use Postman:
- Get Device Status:
Send a GET request tohttp://<api-gateway-url>/device-status
.
The response will return whether the device is ON or OFF. - Update Device Status:
Send a GET request tohttp://<api-gateway-url>/update-status?status=ON
to turn the device ON, orstatus=OFF
to turn it OFF.
This Tech-Concept post on IoT home automation is your starting point for creating various automations, with a focus solely on programming to stream data. Arduino basics and hardware control can be explored further through countless YouTube tutorials. This project serves as the foundation for more advanced home automation setups. Enhance the system by adding more devices, sensors, or features like scheduling or integrating with voice assistants such as Alexa or Google Assistant.
#AskDushyant
#TechConcept #IoT #Lamda #Serverless #API #Arduino #Mysql
Leave a Reply