Skip to content

Commit

Permalink
add a basic arduino program to respond to server's commands
Browse files Browse the repository at this point in the history
  • Loading branch information
catink123 committed Jan 12, 2024
1 parent a85b7c5 commit d32e91b
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/arduino_program/gate_control/gate_control.ino
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include <ArduinoJson.h>
const int capacity = 100;
StaticJsonDocument<capacity> doc;
bool state = false;

void setup() {
Serial.begin(115200);
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
}

void loop() {
if (Serial.available() > 0) {
String msg = Serial.readStringUntil('%');
// skip the message end character
Serial.read();

deserializeJson(doc, msg);
if (doc["type"] == "change_state" && doc["payload"] == true) {
digitalWrite(13, HIGH);
state = true;
} else if (doc["type"] == "change_state" && doc["payload"] == false) {
digitalWrite(13, LOW);
state = false;
} else if (doc["type"] == "query_state") {
DynamicJsonDocument dyn_doc(100);
dyn_doc["type"] = "query_state_result";
dyn_doc["payload"] = state;
String msg;
serializeJson(dyn_doc, msg);
msg += '%';

Serial.write(msg.c_str());
} else {
Serial.write("{\"type\": \"error\", \"payload\": \"unknown_command\"}%");
}
}
}

0 comments on commit d32e91b

Please sign in to comment.