element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products & Partners
    Products & Partners
    • Arduino
    • Avnet & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
    About the element14 Community
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      •  Vietnam
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
My Project Is Trash
  • Challenges & Projects
  • Design Challenges
  • My Project Is Trash
  • More
  • Cancel
My Project Is Trash
Forum Knock-Knock-Sortin' #10 - The Nicla firmware
  • News
  • Forum
  • Projects
  • Enroll
  • Leaderboard
  • Files
  • Members
  • More
  • Cancel
  • New
Join My Project Is Trash to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • Replies 0 replies
  • Subscribers 1 subscriber
  • Views 5 views
  • Users 0 members are here
  • camdenboss
  • KnockKnockSort
  • my project is trash
  • analog devices
  • my-project-is-trash
  • design-challenge
Related

Knock-Knock-Sortin' #10 - The Nicla firmware

amgalbu
amgalbu 19 minutes ago

In post #9 the bin finally came together: chute, gate, motor, LED panel. One board was still missing from the party: the Nicla Vision that is mounted under the gate plate: it hears the knock with its microphone, feels it with its accelerometer, and tells the rest of the machine what it thinks the item is made of.

image
In this post I describe the firmware that runs on the Nicla. It does three things:

  1.  It waits for the Nano to say "something is falling".
  2. It cuts half a second of sound and vibration around the knock and runs the Edge Impulse model on it.
  3. It sends the answer back to the Nano, as one short line of text.

image


How it works

First, let's see how the work is split between the boards. The Arduino Nano 33 BLE reads the CN0569 IR beam, turns the chute, opens the gate and drives the LED panel. The Nicla Vision under the gate plate has one job: say what landed on the plate.

The two boards talk through two wires, plus 5 V and ground in the same 4-core cable:

  • DETECT, from the Nano to the Nicla. The Nano raises it when the IR beam sees an item falling, and keeps it high until the answer arrives, or for 2 s at most.
  • NICLA_TX, from the Nicla to the Nano. One line of text per item, at 19200 baud. In short, the Nano says "listen" and the Nicla answers "plastic, 94% sure".

The conversation between the Nano and the Nicla, and the wires that carry it

image

The DETECT signal

Capture on the Nicla can not be started based on a threshold, because a lot of things could be loud near a bin (the gate slams, the stepper motor moves the chute). Every one of those would wake the classifier, and in the best case the model would say "noise" a hundred times a day.

The Nano already knows when an item is really coming thanks to IR sensor CN0569. So the Nano raises DETECT, and only a knock that comes while DETECT is up counts.

The model was trained on windows cut around the knock, with the knock always 50 ms after the start of the window. If I started the recording at the DETECT edge, the knock would land somewhere different every time, depending on how fast the item falls. In post #7, moving the knock 20 ms earlier dropped the accuracy from 99.2% to 96.7%. So DETECT arms the recording instead of starting it: the recording still starts on the loud sample of the knock, exactly as during data collection, but only while the Nicla is armed.

This is what happens over time, from the beam break to the reply

image

DETECT arrives on the Nicla's D2 pin. In MicroPython, a rising edge on a pin can call a function, so the handler is tiny. It only takes note of the time:

detect = Pin("D2", Pin.IN, Pin.PULL_DOWN)
detect.irq(trigger=Pin.IRQ_RISING, handler=on_detect)

def on_detect(pin):
global armed, armed_t
armed = True
armed_t = time.ticks_ms()

Meanwhile, the microphone and the accelerometer never stop. The microphone stores 16,000 samples per second into a ring buffer that always holds the last second of sound. The accelerometer on the Nicla does the same at 3,333 samples per second. Ring buffer stores data continuously, overwriting the oldest data, so when something happens, the moments just before it are still there. That's how every window gets its 50 ms of quiet lead-in before the knock.

When a loud sample arrives, the main loop checks the current application state:

  • Armed: this is the knock. Wait 450 ms more, so the whole window is in both rings, and classify.
  • Not armed: keep the knock in mind for 300 ms. If DETECT shows up in that time (an item that falls fast, or a beam that sees it late), the knock still counts. If not, forget it.
  • Armed for 2 s and no knock: something crossed the beam but never hit the plate, or hit it too softly. The Nicla sends none 0.00, so the Nano doesn't wait for nothing.

After each capture, the Nicla ignores everything for 1.5 s to filter out events like an item that bounces or, the gate that opens and closes.

I didn't touch the capture code itself. The ring buffers, the trigger level, the 500 ms window and the way the accelerometer is aligned to the microphone are the same lines that recorded the dataset. If I change any of that, I have to record the dataset again, and dropping a plastic bottle 20 times is the most boring activity in a design challenge.

Loading the Edge Impulse model

The Nicla runs the OpenMV firmware, which is MicroPython. Edge Impulse can export an impulse for OpenMV, but only for image models. For audio and vibration it offers an Arduino library in C++, which would mean throwing away all the Python capture code.

So I split the impulse in two:

  • The neural network is downloaded from Edge Impulse as a TensorFlow Lite file (trained.tflite, int8, the 51 kB model of post #7). OpenMV has an ml module tht runs these files directly.
  • The processing blocks (MFE on the microphone, Spectrogram on the vertical axis of the accelerometer) are computed in Python, in a file called features.py. It's a port of Edge Impulse's own open-source processing code to ulab, the numpy-like library of MicroPython. I checked it on the PC against Edge Impulse's own Python code, on the same recordings.

The model file and a labels.txt with the class names go on the Nicla's USB drive, next to main.py. At boot, the firmware loads them and makes one important check (simplified here):

self.model = ml.Model("trained.tflite")
self.labels = [l.strip() for l in open("labels.txt") if l.strip()]
n_feat = features.feature_count(DSP_BLOCKS, 8000, 16000) # 1200 + 231
if n_feat != n_in: # n_in: the model's input size
raise ModelError("model takes %d features but DSP_BLOCKS give %d" % (n_in, n_feat))

The settings of the two processing blocks live in config.py, copied from the Edge Impulse pages. If I retrain with different settings and forget to copy them, the number of features no longer matches what the network expects. Instead of producing confident nonsense, the Nicla stops at boot, lights the red LED and says why on the USB serial port.

Item classification

Once the window is complete, the Nicla runs the impulse. These are the steps, and the code (again simplified) is shorter than the list:

  1. Cut 500 ms out of both rings, starting 50 ms before the knock.
  2. Bring the accelerometer to the microphone's 16 kHz, so every row has the same time: [mic, accX, accY, accZ]. That's how the training files were built, so the model expects it.
  3. Compute the features: 30 × 40 sound energies from the MFE block and 7 × 33 vibration energies from the Spectrogram block.
  4. Run the network and take the class with the highest score.

win = build_window(mic_trig - PRE_MIC, acc_trig - PRE_ACC) # 8000 x 4
x = features.compute(win, DSP_BLOCKS, 16000, tick=drain) # 1431 numbers
scores = model.predict([x.reshape(shape)])[0]
label, conf = best_of(labels, scores) # "plastic", 0.94

The tick=drain argument keeps the accelerometer running during the maths. Computing the features takes a while in Python, and the accelerometer's hardware FIFO only holds a few tens of milliseconds of data. So the feature code calls drain() every few frames, which empties the FIFO into the ring buffer, and the accelerometer never loses its place.

image

Sending classification result to Nano

The answer is one line of plain text: the material, a space, the confidence with two decimals, and a newline.
For example: "plastic 0.94\n"

def send(label, conf):
uart.write("%s %.2f\n" % (label, conf))

This is the same format I used to test Nano's application: you can type this same line in the Serial Monitor and see how to firmwae reacts.

Initially, I planned to send the bin, like PLASTIC 0.93. I changed my mind: the Nicla sends the material, not the bin. Which bin a material goes to is a Nano's and only Nano's concern. If recycling rules change or I want to add another bin, I just need to update one table on the Nano, and the model doesn't need to know. The same goes for the confidence: below 0.70 the Nano calls the item "unsure" and plays it safe with the landfill bin, and for noise it doesn't move at all.

Note that the Nano has only one hardware serial port. Its TX pin talks to the Uno that drives the LEDs, its RX pin listens to the Nicla, and both directions must share the same speed.
In post #8, I connnected the Nicla's pin marked D1/TX to the Nano. In the Arduino core that pin is a serial port, but in the OpenMV firmware it isn't: the D1 and D2 pins are routed to a low-power UART that MicroPython can't use, and that the usable UART on the header is UART4, on the two pins marked SDA and SCL.

The Nicla doesn't use I2C any more (the CN0569 is connected to the Nano), so those pins are free. The fix is to move the NICLA_TX wire from pin J2-3 (D1) to pin J2-1 (SDA).

Firmware files

The firmware is in the nicla_classifier folder of the project, and all of it goes on the Nicla's USB drive:

main.py DETECT, ring buffers, window, reply on the UART
config.py Every setting: pins, baud rate, timings, capture values, DSP blocks
features.py The Edge Impulse MFE and Spectrogram blocks, ported to MicroPython
classifier.py Loads trained.tflite and labels.txt and runs the model
trained.tflite, labels.txt The model, downloaded from Edge Impulse

Thanks for reading and see you soon!

  • Sign in to reply
  • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2026 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube