#pragma once /* * Simple Serial Protocol * * This product includes software developed by Nick Leeman. * Simple Serial Protocol (https://git.aterve.com/Frozenverse/SimpleSerialProtocol). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include class SerialConnection { private: int serialBufferSize = 265; char serialBuffer[265]; // Receiving a new packet boolean newSerialData = false; // Currently receiving a packet boolean serialReadInProgress = false; // Total bytes received in current packet byte serialBytesReceived = 0; // Serial connection Stream *serialRefrence; public: const char packetStartMarker = 180; const char packetMidMarker = 196; const char packetEndMarker = 195; void init(HardwareSerial &serialHandle, unsigned long serialBaud); void send(char* data); char* handle(); int getBufferSize(); }; void SerialConnection::init(HardwareSerial &serialHandle, unsigned long serialBaud) { // serialBuffer[serialBufferSize] = {0}; serialRefrence = &serialHandle; serialHandle.begin(serialBaud); }; char* SerialConnection::handle() { if(serialRefrence->available() > 0) { char _byte = serialRefrence->read(); // Check if we reached end of packet if (_byte == packetEndMarker) { serialReadInProgress = false; newSerialData = true; serialBuffer[serialBytesReceived] = 0; return serialBuffer; } // Read packet data if(serialReadInProgress) { serialBuffer[serialBytesReceived] = _byte; serialBytesReceived++; if (serialBytesReceived == serialBufferSize) { serialBytesReceived = serialBufferSize - 1; } } // Check if received new packet marker if (_byte == packetStartMarker) { serialBytesReceived = 0; serialReadInProgress = true; } return NULL; } return NULL; }; void SerialConnection::send(char* data) { serialRefrence->println(data); }; int SerialConnection::getBufferSize() { return (int)serialBufferSize; };