The best and most intuitive way is to use the serialEvent () callback, which Arduino defines along with loop () and setup ().
I created a small library that handles the reception of messages, but did not manage to open it yet. This library gets \ n complete lines, which are a command and an arbitrary payload, separated by spaces. You can configure it to easily use your own protocol.
First of all, the library, SerialReciever.h:
#ifndef __SERIAL_RECEIVER_H__ #define __SERIAL_RECEIVER_H__ class IncomingCommand { private: static boolean hasPayload; public: static String command; static String payload; static boolean isReady; static void reset() { isReady = false; hasPayload = false; command = ""; payload = ""; } static boolean append(char c) { if (c == '\n') { isReady = true; return true; } if (c == ' ' && !hasPayload) { hasPayload = true; return false; } if (hasPayload) payload += c; else command += c; return false; } }; boolean IncomingCommand::isReady = false; boolean IncomingCommand::hasPayload = false; String IncomingCommand::command = false; String IncomingCommand::payload = false; #endif
To use it, do the following in your project:
#include <SerialReceiver.h> void setup() { Serial.begin(115200); IncomingCommand::reset(); } void serialEvent() { while (Serial.available()) { char inChar = (char)Serial.read(); if (IncomingCommand::append(inChar)) return; } }
To use the received commands:
void loop() { if (!IncomingCommand::isReady) { delay(10); return; } executeCommand(IncomingCommand::command, IncomingCommand::payload);
Blazer Sep 28 '13 at 11:44 2013-09-28 11:44
source share