Add Serial library

This commit is contained in:
Ollo 2024-12-07 11:01:46 +01:00
parent 365d8c987a
commit 30deee981b
2 changed files with 130 additions and 0 deletions

16
include/SerialCmd.h Normal file
View File

@ -0,0 +1,16 @@
#ifndef SERIALCMD_H
#define SERIALCMD_H
#include <stdint.h>
int SerialCmd_readFromSerial (void);
void SerialCmd_clearCmdArray (void);
int SerialCmd_checkCmdArrayForPrefix (void);
uint32_t SerialCmd_parseColor(int startOffset);
char SerialCmd_type(void);
#endif /* SERIALCMD_H */

114
src/SerialCmd.cpp Normal file
View File

@ -0,0 +1,114 @@
#include "SerialCmd.h"
#include "ColorUtil.h"
#include <Arduino.h>
// Serial fields
#define CMD_MAX 128
static char myCmd[CMD_MAX];
/**
* @brief
* number of read bytes
* @return int
*/
int SerialCmd_readFromSerial (void)
{
//read from the serial buffer and flush
int inputSize = Serial.available();
//give serial a chance to receive all bytes
if(inputSize > 0){
delay(100);
inputSize = Serial.available();
}
if(inputSize > 0 && inputSize < CMD_MAX)
{
Serial.print("inputSize: ");
Serial.print(inputSize);
for (int i = 0; i < inputSize; i++){
myCmd[i] = Serial.read();
}
}
else if(inputSize >= CMD_MAX)
{
Serial.flush();
Serial.print("too much data, flush");
}
return inputSize;
}
/**
* @brief
* clear the cmd array
*/
void SerialCmd_clearCmdArray(void)
{
for (int i = 0; i < CMD_MAX; i++)
{
myCmd[i] = '\0';
}
}
/**
* @brief
* check if command has the required prefix
* @return int
*/
int SerialCmd_checkCmdArrayForPrefix (void)
{
if (myCmd[0] == 'o'
&& myCmd[1] == 'l'
&& myCmd[2] == 'l'
&& myCmd[3] == 'p'
&& myCmd[4] == 'e')
{
return 1;
}
else
{
return 0;
}
}
char SerialCmd_type(void)
{
if (SerialCmd_checkCmdArrayForPrefix())
{
return myCmd[5];
}
else
{
return '\0';
}
}
uint32_t SerialCmd_parseColor(int startOffset)
{
unsigned int colorParts[3]; /* 0: red, 1: green, 2: blue */
unsigned int colorSum = 0;
if (startOffset > (CMD_MAX - sizeof(colorParts)))
{
return 0;
}
for (int i=0; i < (2*3); i+= 2)
{
colorParts[i/2] = (myCmd[i+startOffset] <= '9') ? ((myCmd[i+startOffset]-'0') << 4) : (((myCmd[i+startOffset]-'A')+10) << 4);
if (colorParts[i/2] < 0)
{
Serial.print("calcErr:");
Serial.println(colorParts[i/2]);
}
colorParts[i/2] += ( (myCmd[i+startOffset+1] <= '9') ? (myCmd[i+startOffset+1]-'0') : (((myCmd[i+startOffset+1]-'A')+10)) );
}
int r = colorParts[0]; /* fill red */
int g = colorParts[1]; /* fill green */
int b = colorParts[2]; /* fill blue */
return Color(r, g, b);
}