/* * Task 1: Basic API Programming
* This code demonstrates a simple Serial API to control an LED.
*/
const int ledPin = 2; // LED connected to GPIO 2
void setup() {
// Initialize Serial communication at 115200 bits per second:
Serial.begin(115200);
// Set the LED pin as an output:
pinMode(ledPin, OUTPUT);
Serial.println("API System Ready. Please enter 'ON' or 'OFF'...");
}
void loop() {
// Check if there is an incoming API request (Serial data)
if (Serial.available() > 0) {
String request = Serial.readStringUntil('\n'); // Read the request
request.trim(); // Remove any extra spaces or hidden characters
// API Logic
if (request == "ON") {
digitalWrite(ledPin, HIGH);
Serial.println("Response: { 'status': 'success', 'message': 'LED is now ON' }");
}
else if (request == "OFF") {
digitalWrite(ledPin, LOW);
Serial.println("Response: { 'status': 'success', 'message': 'LED is now OFF' }");
}
else {
Serial.println("Response: { 'status': 'error', 'message': 'Invalid Command' }");
}
}
}Loading
esp32-devkit-c-v4
esp32-devkit-c-v4