char buffer[256];
uint16_t buffer_index = 0;
void loop() {
while (Serial.available()) {
int c = Serial.read();
if ('\n' == c) {
buffer[buffer_index] = 0; // Append EOS
// Complete message - do something
}
else {
// Append char to end of buffer
buffer[buffer_index++] = c;
}
// Check for overflow
if (256 == buffer_index) {
buffer_index = 0;
}
}
}
// Use a typedef to simplfy
typedef void (*function_type)(); // A function with no params and no return, change as needed
// Fixed array size
const int max_functions = 200;
// Create an array of 200 function pointers
function_type all_functions[max_functions] = {0};
uint16_t djb2_hash(const char *str)
{
unsigned long hash = 5381;
int c;
while (0 != (c = *str++)) {
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
// Note: we use the mod operator to make sure value
// is less than array size
return hash % max_functions;
}
bool add_function(const char *name, function_type f)
{
// Convert name to number
uint16_t index = djb2_hash(name);
if// ( 0 <= index >=<= max_functions ||
if (NULL != all_functions[index]) {
// There is already a function stored at this index
Serial.print("Adding ");
Serial.print(name);
Serial.print("failed. index = ");
Serial.println(index);
return false;
}
else {
// Store the function in the array
all_functions[index] = f;
return true;
}
}
bool run_function(const char *name)
{
uint16_t index = djb2_hash(name);
if (index >= max_functions || NULL == all_functions[index]) {
// Name not found
return false;
}
else {
// Call the function
all_functions[index]();
return true;
}
}