ChatGPT: ESP32 Control Relay
ChatGPT adalah satu tools yang boleh membantu programmer menulis code. Berikut adalah contoh menulis code ESP32 mengawal relay dengan soalan di bawah.
Berikut adalah contoh ESP32 code yang diberikan oleh ChatGPT dan programmer perlu memahami cara fungsi code tersebut.
#include <ArduinoJson.h>
// Define relay pins
const int relayPin1 = 13;
const int relayPin2 = 25;
const int relayPin3 = 26;
const int relayPin4 = 27;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set relay pins as outputs
pinMode(relayPin1, OUTPUT);
pinMode(relayPin2, OUTPUT);
pinMode(relayPin3, OUTPUT);
pinMode(relayPin4, OUTPUT);
// Initially turn off all relays
digitalWrite(relayPin1, HIGH);
digitalWrite(relayPin2, HIGH);
digitalWrite(relayPin3, HIGH);
digitalWrite(relayPin4, HIGH);
}
void loop() {
if (Serial.available()) {
// Read the command from the Serial Monitor
String command = Serial.readStringUntil('\n');
command.trim();
if (command == "status") {
// Read the status of all relays
bool relayStatus1 = digitalRead(relayPin1) == LOW;
bool relayStatus2 = digitalRead(relayPin2) == LOW;
bool relayStatus3 = digitalRead(relayPin3) == LOW;
bool relayStatus4 = digitalRead(relayPin4) == LOW;
// Create a JSON document
StaticJsonDocument<128> jsonDoc;
// Populate the JSON document
jsonDoc["relay1"] = relayStatus1;
jsonDoc["relay2"] = relayStatus2;
jsonDoc["relay3"] = relayStatus3;
jsonDoc["relay4"] = relayStatus4;
// Serialize the JSON document to a string
String jsonString;
serializeJson(jsonDoc, jsonString);
// Send the JSON string to the Serial Monitor
Serial.println(jsonString);
} else if (command.startsWith("set ")) {
// Extract the relay number and state from the command
int relayNum = command.substring(4, 5).toInt();
bool relayState = command.substring(6).toInt() == 1;
// Set the specified relay to the desired state
if (relayNum == 1) {
digitalWrite(relayPin1, relayState ? LOW : HIGH);
} else if (relayNum == 2) {
digitalWrite(relayPin2, relayState ? LOW : HIGH);
} else if (relayNum == 3) {
digitalWrite(relayPin3, relayState ? LOW : HIGH);
} else if (relayNum == 4) {
digitalWrite(relayPin4, relayState ? LOW : HIGH);
}
// Send an acknowledgment back to the Serial Monitor
Serial.println("OK");
} else {
// Unknown command, send an error message to the Serial Monitor
Serial.println("Invalid command");
}
}
}
Berikut adalah demo ChatGPT.
Leave a Reply