#include <Arduino.h>
#include <math.h>
// ==================================================
// BRAIN-INSPIRED ADAPTIVE NEUROMORPHIC SYSTEM
// STM32 NUCLEO-C031C6
// SEVEN-NEURON SPIKING NEURAL NETWORK
// ==================================================
#define INPUT_PIN A0
#define NEURON_COUNT 7
#define UPDATE_INTERVAL 5
#define PRINT_INTERVAL 1000
// Neuron indexes
#define N1 0
#define N2 1
#define N3 2
#define N4 3
#define N5 4
#define N6 5
#define N7 6
// ==================================================
// LIF NEURON PARAMETERS
// ==================================================
const float threshold = 0.8f;
const float resetPotential = 0.1f;
const float tauMembrane = 0.05f;
const float dt = 0.005f;
// ==================================================
// SYNAPTIC PARAMETERS
// ==================================================
const float synapticDecay = 0.82f;
const float maxSynapticCurrent = 8.0f;
const float initialWeight = 3.0f;
const float minimumWeight = 1.0f;
const float maximumWeight = 5.0f;
// Three adaptive connections:
// N2 -> N5
// N3 -> N6
// N4 -> N7
float weights[3] = {
initialWeight,
initialWeight,
initialWeight
};
// ==================================================
// STDP LEARNING PARAMETERS
// ==================================================
const float A_PLUS = 0.0005f;
const float A_MINUS = 0.0006f;
const float tauSTDP = 0.100f;
const float traceDecay =
expf(-dt / tauSTDP);
float preTrace[3] = {0};
float postTrace[3] = {0};
unsigned long learningUpdates = 0;
// ==================================================
// NEURON VARIABLES
// ==================================================
float membrane[NEURON_COUNT] = {0};
float synapticCurrent[NEURON_COUNT] = {0};
bool spike[NEURON_COUNT] = {false};
// Total spike counters
unsigned long totalSpikes[NEURON_COUNT] = {0};
// Current one-second window counters
unsigned long windowSpikes[NEURON_COUNT] = {0};
// ==================================================
// INPUT VARIABLES
// ==================================================
int adcValue = 0;
float inputSignal = 0.0f;
int activePattern = -1;
int candidatePattern = -1;
int candidateCount = 0;
const int PATTERN_CONFIRM_COUNT = 5;
// ==================================================
// TIMING VARIABLES
// ==================================================
unsigned long previousUpdate = 0;
unsigned long previousPrint = 0;
// ==================================================
// PATTERN NAMES
// ==================================================
const char* patternName(int pattern) {
if (pattern == 0) return "LOW";
if (pattern == 1) return "MEDIUM";
if (pattern == 2) return "HIGH";
return "UNKNOWN";
}
// ==================================================
// ADC PATTERN DETECTION
// ==================================================
int detectPattern(int adc) {
if (adc < 1365) {
return 0;
}
else if (adc < 2730) {
return 1;
}
else {
return 2;
}
}
// ==================================================
// RESET DYNAMIC NETWORK STATE
// Preserves learned weights and total spike counts.
// ==================================================
void resetNetworkState() {
for (int i = 0; i < NEURON_COUNT; i++) {
membrane[i] = 0.0f;
synapticCurrent[i] = 0.0f;
spike[i] = false;
windowSpikes[i] = 0;
}
for (int i = 0; i < 3; i++) {
preTrace[i] = 0.0f;
postTrace[i] = 0.0f;
}
}
// ==================================================
// LIF NEURON UPDATE
// Returns true when a neuron generates a spike.
// ==================================================
bool updateNeuron(int index, float inputCurrent) {
float dv =
((-membrane[index] + inputCurrent)
/ tauMembrane) * dt;
membrane[index] += dv;
if (membrane[index] >= threshold) {
membrane[index] = resetPotential;
spike[index] = true;
totalSpikes[index]++;
windowSpikes[index]++;
return true;
}
return false;
}
// ==================================================
// ADD SYNAPTIC CURRENT WITH LIMIT
// ==================================================
void addSynapticInput(int neuron, float value) {
synapticCurrent[neuron] += value;
if (synapticCurrent[neuron] >
maxSynapticCurrent) {
synapticCurrent[neuron] =
maxSynapticCurrent;
}
}
// ==================================================
// SYNAPTIC CURRENT DECAY
// ==================================================
void decaySynapticCurrents() {
for (int i = 1; i < NEURON_COUNT; i++) {
synapticCurrent[i] *= synapticDecay;
if (synapticCurrent[i] < 0.001f) {
synapticCurrent[i] = 0.0f;
}
}
}
// ==================================================
// STDP LEARNING
//
// Pre-spike followed by post-spike:
// potentiation.
//
// Post-spike followed by pre-spike:
// depression.
//
// Weights are bounded between 1 and 5.
// ==================================================
void updateSTDP(int connection,
bool preSpikeEvent,
bool postSpikeEvent) {
// Decay previous spike traces
preTrace[connection] *= traceDecay;
postTrace[connection] *= traceDecay;
// Presynaptic event:
// Depression based on previous post activity
if (preSpikeEvent) {
weights[connection] -=
A_MINUS * postTrace[connection];
}
// Postsynaptic event:
// Potentiation based on previous pre activity
if (postSpikeEvent) {
weights[connection] +=
A_PLUS * preTrace[connection];
}
// Keep weights within safe limits
if (weights[connection] < minimumWeight) {
weights[connection] = minimumWeight;
}
if (weights[connection] > maximumWeight) {
weights[connection] = maximumWeight;
}
// Update traces after weight calculation
if (preSpikeEvent) {
preTrace[connection] += 1.0f;
}
if (postSpikeEvent) {
postTrace[connection] += 1.0f;
}
if (preSpikeEvent || postSpikeEvent) {
learningUpdates++;
}
}
// ==================================================
// RUN SEVEN-NEURON NETWORK
// ==================================================
void runNetwork() {
// Clear previous time-step spike flags
for (int i = 0; i < NEURON_COUNT; i++) {
spike[i] = false;
}
// Decay existing synaptic currents
decaySynapticCurrents();
// ----------------------------------------------
// N1: INPUT NEURON
// ----------------------------------------------
bool inputSpike =
updateNeuron(N1, inputSignal);
// ----------------------------------------------
// N2, N3, N4: FEATURE NEURONS
// ----------------------------------------------
// Route input spikes to selected feature pathway
if (inputSpike) {
int selectedFeature = activePattern + 1;
addSynapticInput(
selectedFeature,
initialWeight
);
}
bool lowFeatureSpike =
updateNeuron(N2, synapticCurrent[N2]);
bool mediumFeatureSpike =
updateNeuron(N3, synapticCurrent[N3]);
bool highFeatureSpike =
updateNeuron(N4, synapticCurrent[N4]);
// ----------------------------------------------
// N5, N6, N7: OUTPUT NEURONS
// ----------------------------------------------
// Low pathway
if (lowFeatureSpike) {
addSynapticInput(N5, weights[0]);
}
// Medium pathway
if (mediumFeatureSpike) {
addSynapticInput(N6, weights[1]);
}
// High pathway
if (highFeatureSpike) {
addSynapticInput(N7, weights[2]);
}
bool lowOutputSpike =
updateNeuron(N5, synapticCurrent[N5]);
bool mediumOutputSpike =
updateNeuron(N6, synapticCurrent[N6]);
bool highOutputSpike =
updateNeuron(N7, synapticCurrent[N7]);
// ----------------------------------------------
// STDP CONNECTION UPDATES
// ----------------------------------------------
updateSTDP(
0,
lowFeatureSpike,
lowOutputSpike
);
updateSTDP(
1,
mediumFeatureSpike,
mediumOutputSpike
);
updateSTDP(
2,
highFeatureSpike,
highOutputSpike
);
}
// ==================================================
// CLASSIFICATION OUTPUT
// ==================================================
void printClassification() {
unsigned long lowFeature =
windowSpikes[N2];
unsigned long mediumFeature =
windowSpikes[N3];
unsigned long highFeature =
windowSpikes[N4];
unsigned long lowOutput =
windowSpikes[N5];
unsigned long mediumOutput =
windowSpikes[N6];
unsigned long highOutput =
windowSpikes[N7];
Serial.println();
Serial.println("======================================");
Serial.println(" BRAIN-INSPIRED PATTERN RECOGNITION");
Serial.println("======================================");
Serial.print("ADC INPUT : ");
Serial.println(adcValue);
Serial.print("INPUT CURRENT : ");
Serial.println(inputSignal, 3);
Serial.print("INPUT PATTERN : ");
Serial.println(patternName(activePattern));
// ----------------------------------------------
// FEATURE NEURON SPIKES
// ----------------------------------------------
Serial.println();
Serial.println("FEATURE NEURON SPIKES");
Serial.print("N2 LOW : ");
Serial.println(lowFeature);
Serial.print("N3 MEDIUM : ");
Serial.println(mediumFeature);
Serial.print("N4 HIGH : ");
Serial.println(highFeature);
// ----------------------------------------------
// OUTPUT NEURON SPIKES
// ----------------------------------------------
Serial.println();
Serial.println("OUTPUT NEURON SPIKES");
Serial.print("N5 LOW : ");
Serial.println(lowOutput);
Serial.print("N6 MEDIUM : ");
Serial.println(mediumOutput);
Serial.print("N7 HIGH : ");
Serial.println(highOutput);
// ----------------------------------------------
// WINNER SELECTION
// ----------------------------------------------
Serial.println();
Serial.println("CLASSIFICATION RESULT");
unsigned long maximumCount = lowOutput;
if (mediumOutput > maximumCount) {
maximumCount = mediumOutput;
}
if (highOutput > maximumCount) {
maximumCount = highOutput;
}
if (maximumCount == 0) {
Serial.println("NO DECISION");
}
else {
int winners = 0;
if (lowOutput == maximumCount) winners++;
if (mediumOutput == maximumCount) winners++;
if (highOutput == maximumCount) winners++;
if (winners > 1) {
Serial.println("TIE / AMBIGUOUS");
}
else if (lowOutput == maximumCount) {
Serial.println("PATTERN DETECTED : LOW");
}
else if (mediumOutput == maximumCount) {
Serial.println("PATTERN DETECTED : MEDIUM");
}
else {
Serial.println("PATTERN DETECTED : HIGH");
}
}
// ----------------------------------------------
// ADAPTIVE SYNAPTIC WEIGHTS
// ----------------------------------------------
Serial.println();
Serial.println("STDP LEARNING WEIGHTS");
Serial.print("N2 -> N5 : ");
Serial.println(weights[0], 5);
Serial.print("N3 -> N6 : ");
Serial.println(weights[1], 5);
Serial.print("N4 -> N7 : ");
Serial.println(weights[2], 5);
Serial.print("LEARNING EVENTS : ");
Serial.println(learningUpdates);
Serial.println("======================================");
// Clear one-second spike window
for (int i = 0; i < NEURON_COUNT; i++) {
windowSpikes[i] = 0;
}
}
// ==================================================
// SETUP
// ==================================================
void setup() {
Serial.begin(115200);
analogReadResolution(12);
pinMode(INPUT_PIN, INPUT);
delay(1000);
Serial.println();
Serial.println("======================================");
Serial.println(" BRAIN-INSPIRED COMPUTING SYSTEM");
Serial.println(" ADAPTIVE NEUROMORPHIC COMPUTING");
Serial.println(" STM32 NUCLEO-C031C6");
Serial.println(" SEVEN-NEURON SNN");
Serial.println("======================================");
Serial.println("N1 : INPUT NEURON");
Serial.println("N2 : LOW FEATURE DETECTOR");
Serial.println("N3 : MEDIUM FEATURE DETECTOR");
Serial.println("N4 : HIGH FEATURE DETECTOR");
Serial.println("N5 : LOW OUTPUT");
Serial.println("N6 : MEDIUM OUTPUT");
Serial.println("N7 : HIGH OUTPUT");
Serial.println("--------------------------------------");
Serial.println("LIF NEURONS INITIALIZED");
Serial.println("SYNAPTIC CONNECTIONS INITIALIZED");
Serial.println("STDP LEARNING INITIALIZED");
Serial.println("PATTERN RECOGNITION INITIALIZED");
Serial.println("--------------------------------------");
previousUpdate = millis();
previousPrint = millis();
}
// ==================================================
// MAIN LOOP
// ==================================================
void loop() {
unsigned long now = millis();
// ----------------------------------------------
// READ INPUT AND DETECT PATTERN
// ----------------------------------------------
adcValue = analogRead(INPUT_PIN);
int detectedPattern = detectPattern(adcValue);
// Debounce pattern changes
if (detectedPattern == candidatePattern) {
if (candidateCount < PATTERN_CONFIRM_COUNT) {
candidateCount++;
}
}
else {
candidatePattern = detectedPattern;
candidateCount = 1;
}
// ----------------------------------------------
// ACCEPT STABLE PATTERN
// ----------------------------------------------
if (candidateCount >= PATTERN_CONFIRM_COUNT &&
candidatePattern != activePattern) {
activePattern = candidatePattern;
resetNetworkState();
previousPrint = now;
Serial.println();
Serial.println("--------------------------------------");
Serial.println("INPUT PATTERN CHANGED");
Serial.print("ACTIVE PATTERN : ");
Serial.println(patternName(activePattern));
Serial.println("NETWORK STATE RESET");
Serial.println("LEARNED WEIGHTS PRESERVED");
Serial.println("--------------------------------------");
}
// Wait until a valid input pattern is selected
if (activePattern == -1) {
return;
}
// ----------------------------------------------
// INPUT ENCODING
// ----------------------------------------------
inputSignal =
0.9f + (adcValue / 4095.0f) * 0.5f;
// ----------------------------------------------
// SNN UPDATE
// ----------------------------------------------
if (now - previousUpdate >= UPDATE_INTERVAL) {
previousUpdate = now;
runNetwork();
}
// ----------------------------------------------
// SERIAL MONITOR OUTPUT
// ----------------------------------------------
if (now - previousPrint >= PRINT_INTERVAL) {
previousPrint = now;
printClassification();
}
}
Loading
st-nucleo-c031c6
st-nucleo-c031c6