Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ArduinoJson.h>
- #include <SoftwareSerial.h>
- SoftwareSerial mySerial(10, 11);
- String ID = "a";
- uint8_t MaxHops = 10;
- void setup() {
- Serial.begin(115200);
- while (!Serial) { ; }
- Serial.println("Serial started!");
- Serial.print("Your ID: ");
- Serial.println(ID);
- Serial.println("You can now send your messages with \"ID:MESSAGE\"");
- mySerial.begin(19200);
- }
- void sendData(String toId, String msg, int hops) {
- DynamicJsonBuffer jsonBuffer;
- JsonObject& json = jsonBuffer.createObject();
- json["fromId"] = ID;
- json["toId"] = toId;
- json["msg"] = msg;
- json["hops"] = hops;
- json.printTo(mySerial);
- }
- JsonObject& readData(String json) {
- DynamicJsonBuffer jsonBuffer;
- JsonObject& json_obj = jsonBuffer.parseObject(json);
- return json_obj;
- }
- void loop() {
- static String toId = "";
- static String msg = "";
- static boolean split = false;
- while (Serial.available() >= 1) {
- char c = Serial.read();
- if (!split) {
- if (c == 58) {
- split = true;
- } else {
- toId += c;
- }
- } else {
- if (c == 10) {
- // Send Data to Next Arduino
- Serial.print("Sending \"");
- Serial.print(msg);
- Serial.print("\" to ID ");
- Serial.println(toId);
- sendData(toId, msg, 1);
- toId = "";
- msg = "";
- split = false;
- } else {
- msg += c;
- }
- }
- }
- while (mySerial.available() >= 1) {
- String json = mySerial.readString();
- JsonObject& json_obj = readData(json);
- int hops = json_obj["hops"];
- String fromId = json_obj["fromId"];
- String msg = json_obj["msg"];
- String toId = json_obj["toId"];
- if (toId.equals(ID)) {
- Serial.print(fromId);
- Serial.print(" (HOPS: ");
- Serial.print(hops);
- Serial.print(")");
- Serial.print(" -> ");
- Serial.println(msg);
- } else {
- if (hops < MaxHops) {
- json_obj["hops"] = hops + 1;
- json_obj.printTo(mySerial);
- } else {
- Serial.print("MSG from ");
- Serial.print(fromId);
- Serial.print(" to ");
- Serial.print(toId);
- Serial.print(" Reached ");
- Serial.print(MaxHops);
- Serial.println(" HOPS");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement