Arduino “having11” Guy
Published © GPL3+

Getting Started with TinyML by Edge Impulse

Learn how to use Edge Impulse's TinyML platform to gather data, train a model, and deploy it to a device of your choice.

BeginnerProtip2 hours604
Getting Started with TinyML by Edge Impulse

Things used in this project

Hardware components

Smartphone
Any generic smartphone will do
×1

Software apps and online services

Edge Impulse TinyML

Story

Read more

Schematics

Phone

Code

run-impulse.js

JavaScript
// Load the inferencing WebAssembly module
const Module = require('./edge-impulse-standalone');

// Classifier module
let classifierInitialized = false;
Module.onRuntimeInitialized = function() {
    classifierInitialized = true;
};

class EdgeImpulseClassifier {
    //_initialized = false;

    init() {
        if (classifierInitialized === true) return Promise.resolve();

        return new Promise((resolve) => {
            Module.onRuntimeInitialized = () => {
                resolve();
                classifierInitialized = true;
            };
        });
    }

    classify(rawData, debug = false) {
        if (!classifierInitialized) throw new Error('Module is not initialized');

        const obj = this._arrayToHeap(rawData);
        let ret = Module.run_classifier(obj.buffer.byteOffset, rawData.length, debug);
        Module._free(obj.ptr);

        if (ret.result !== 0) {
            throw new Error('Classification failed (err code: ' + ret.result + ')');
        }

        let jsResult = {
            anomaly: ret.anomaly,
            results: []
        };

        for (let cx = 0; cx < ret.classification.size(); cx++) {
            let c = ret.classification.get(cx);
            jsResult.results.push({ label: c.label, value: c.value });
        }

        return jsResult;
    }

    _arrayToHeap(data) {
        let typedArray = new Float32Array(data);
        let numBytes = typedArray.length * typedArray.BYTES_PER_ELEMENT;
        let ptr = Module._malloc(numBytes);
        let heapBytes = new Uint8Array(Module.HEAPU8.buffer, ptr, numBytes);
        heapBytes.set(new Uint8Array(typedArray.buffer));
        return { ptr: ptr, buffer: heapBytes };
    }
}

if (!process.argv[2]) {
    return console.error('Requires one parameter (a comma-separated list of raw features)');
}

// Initialize the classifier, and invoke with the argument passed in
let classifier = new EdgeImpulseClassifier();
classifier.init().then(() => {
    let result = classifier.classify(process.argv[2].trim().split(',').map(n => Number(n)));

    console.log(result);
}).catch(err => {
    console.error('Failed to initialize classifier', err);
});

Credits

Arduino “having11” Guy

Arduino “having11” Guy

81 projects • 538 followers
18 year-old IoT and embedded systems enthusiast. Also an intern at Hackster.io who loves working on projects and sharing knowledge.

Comments