Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
Alex Miller
Published

Real-time Food Quality Prediction

Detect spoiled products using the Tiny Machine Learning approach.

ExpertFull instructions provided5,959

Things used in this project

Hardware components

Arduino Mega 2560
Arduino Mega 2560
×1
Arm Cortex M0
×1

Software apps and online services

Neuton
Neuton Tiny ML Neuton

Story

Read more

Code

Initialization

C/C++
static NeuralNet neuralNet = { 0 };
extern const unsigned char model_bin[];
extern const unsigned int model_bin_len;

uint8_t app_init()
{
   return (ERR_NO_ERROR != CalculatorInit(&neuralNet, NULL));
}
 
inline Err CalculatorOnInit(NeuralNet* neuralNet)
{
   memUsage += sizeof(*neuralNet);
 
   app_reset();
   timer_init();
 
   return CalculatorLoadFromMemory(neuralNet, model_bin, model_bin_len, 0);
}

Creation of the model

C/C++
CalculatorLoadFromMemory(neuralNet, model_bin, model_bin_len, 0);

Model predictions

C/C++
inline float* app_run_inference(float* sample, uint32_t size_in, uint32_t *size_out)
{
   if (!sample || !size_out)
       return NULL;
 
   if (size_in / sizeof(float) != app_inputs_size())
       return NULL;
 
   *size_out = sizeof(float) * neuralNet.outputsDim;
 
   if (app.reverseByteOrder)
       Reverse4BytesValuesBuffer(sample, app_inputs_size());
 
   return CalculatorRunInference(&neuralNet, sample);
}

Measurection the prediction

C/C++
inline void CalculatorOnInferenceResult(NeuralNet* neuralNet, float* result)
{
   if (neuralNet->taskType == TASK_BINARY_CLASSIFICATION && neuralNet->outputsDim >= 2)
   {
       float* value = result[0] >= result[1] ? &result[0] : &result[1];
       if (*value > 0.5)
       {
           if (value == &result[0])
           {
               led_green(1);
               led_red(0);
           }
           else
           {
               led_green(0);
               led_red(1);
           }
       }
       else
       {
           led_green(0);
           led_red(0);
       }
   }
}      

Credits

Alex Miller

Alex Miller

8 projects • 76 followers
Director of Data Science and Engineering at Neuton.AI

Comments