Let’s connect the hardware,
#define ADC_Value A0
#define LED_pin 3
String receivedData;
float volt;
void setup() {
Serial.begin(115200); // Initialize UART communication at 115200 baud rate
pinMode(LED_pin, OUTPUT); // Set LED pin as output
}
void loop() {
if (Serial.available() > 0) { // Check if data is received
receivedData = Serial.readString();
receivedData.trim(); // Remove trailing newline or spaces
Serial.print("Received: ");
Serial.println(receivedData); // Print received data
if (receivedData == "AT") {
Serial.println("OK");
} else if (receivedData == "AT+LED=ON") {
digitalWrite(LED_pin, HIGH);
Serial.println("+LED:\"ON\"");
} else if (receivedData == "AT+LED=OFF") {
digitalWrite(LED_pin, LOW);
Serial.println("+LED:\"OFF\"");
} else if (receivedData == "AT+LED_STATUS?") {
// Check LED status and report
if (digitalRead(LED_pin) == HIGH) {
Serial.println("+LED_STATUS:\"ON\"");
} else {
Serial.println("+LED_STATUS:\"OFF\"");
}
} else if (receivedData == "AT+ADC_VALUE?") {
int adcVal = analogRead(ADC_Value); // Read ADC
Serial.print("+ADC_VALUE:");
Serial.println(adcVal);
} else if (receivedData == "AT+ADC_VOLTAGE?") {
int adcVal = analogRead(ADC_Value);
volt = (5.0 * adcVal) / 1023.0;
Serial.print("+ADC_VOLTAGE:");
Serial.println(volt, 2); // Prints voltage with 2 decimal places
} else if (receivedData == "AT+SYS_ON_TIME?") {
// Get system uptime in milliseconds
unsigned long uptime = millis();
// Convert uptime to hours, minutes, seconds
unsigned long hours = uptime / 3600000; // 1 hour = 3600000 milliseconds
unsigned long minutes = (uptime % 3600000) / 60000; // 1 minute = 60000 milliseconds
unsigned long seconds = (uptime % 60000) / 1000; // 1 second = 1000 milliseconds
// Print uptime in HH:MM:SS format
char timeBuffer[9]; // Buffer for "HH:MM:SS"
sprintf(timeBuffer, "%02lu:%02lu:%02lu", hours, minutes, seconds);
Serial.print("+SYS_ON_TIME:");
Serial.println(timeBuffer);
} else {
Serial.println("Invalid Command!"); // Handles unknown inputs
}
}
}
Serial.available();
check whether data is available in the buffer.Serial.readString()
; Read the string available in the receive buffer.
AT
→ Responds with OK.AT+LED=ON
→ Turns LED ON, responds +LED:"ON"
.AT+LED=OFF
→ Turns LED OFF, responds +LED:"OFF"
.AT+LED_STATUS?
→ Reports LED status: +LED_STATUS:"ON" or "OFF"
.AT+ADC_VALUE?
→ Reads analog pin (A0), responds with +ADC_VALUE:<0-1023>.
AT+ADC_VOLTAGE?
→ Converts ADC reading to voltage (0-5V), responds +ADC_VOLTAGE:<value>
.AT+SYS_ON_TIME?
→ Reports system uptime in HH:MM:SS.
"Invalid Command!"
.