Demo 32: Simple Machine Learning - Artificial neural network demo using Arduino ESP32

1. Introduction
In this demo, I will make a simple Machine Learning - Artificial neural network system using Arduino ESP32. Certainly, I will not use ESP32 for training process; instead, i will use Python + numpy for training process. After training, I will use the result weights will be used by ESP32 for output calculation based on input.
Artificial neural network (ANN) systems are inspired by the biological neural networks. These systems can learn to do tasks by considering examples, without task-specific programming. One of most famous methods for ANN training is Backpropagation. You can refer here.
In this demo: ESP32 with 2 buttons (B1 and B2) with possible states: pressed (0) or released (1) and there is 1 LED output with possible state state on (1) or off (0). The LED output can be set based on the state of input.
B1 B2 LED
pressed pressed off
pressed released on
released pressed on
released released off
Figure: state of LED based on state of buttons
We will create an ANN to learn the table above. The network has structure:
Figure: ANN structure of demo
2. Hardware
Here we set input pins as INPUT_PULLUP so the schematic is simple and we can re-use the schematic in Demo 21.
 Figure: hardware connections
[ESP32 GIO12 - BUTTON 1 - GND]
[ESP32 GIO13 - BUTTON 2 - GND]
[ESP32 GIO14 - LED - GND]
3. Software
3.1 ANN is implemented by Python + numpy
I used the code here.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import numpy as np
 
epochs = 10000                                  # Number of iterations
inputLayerSize, hiddenLayerSize, outputLayerSize = 2, 3, 1
L = 0.1                                         # learning rate      
 
X = np.array([[0,0], [0,1], [1,0], [1,1]])      # Buttons states array
Y = np.array([ [0],   [1],   [1],   [0]])       # LED states array
 
def sigmoid (x): return 1/(1 + np.exp(-x))      # activation function
                                                # weights on layer inputs
Wh = np.random.uniform(size=(inputLayerSize, hiddenLayerSize))
Wz = np.random.uniform(size=(hiddenLayerSize,outputLayerSize))
 
for i in range(epochs):
 
    H = sigmoid(np.dot(X, Wh))                  # calculate forward part
    Z = np.dot(H,Wz)                            # 
    E = Y - Z                                   # calculate error
    dZ = E * L                                  # delta Z
    Wz +=  H.T.dot(dZ)                          # calculate backpropagation part
    dH = dZ.dot(Wz.T) * sigmoid_deriv(H)        # 
    Wh +=  X.T.dot(dH)                          # update hidden layer weights

print("**************** error ****************") 
print(E)
print("***************** output **************") 
print(Z)   
print("*************** weights ***************") 
print("input to hidden layer weights: ")     
print(Wh)
print("hidden to output layer weights: ")
print(Wz)

Figure: training process and weights output
3.2 Arduino ESP32
The Arduino code just do the forward part to calculate the output when getting the inputs.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <math.h>

#define B1  12
#define B2  13
#define LED 14

int X[1][2]    =   {{1,0}};
/*these matrices was calculated by python */
float W1[2][3] =   {{0.74000854,  4.47769531, -0.98692059}, 
                    {0.83034991,  4.48772758, -0.55733578}};
float W2[3][1] =   {{-6.17234487}, 
                    {4.8835918}, 
                    {1.28875386}};
float Wo1[1][3];
float sum = 0;
float Y = 0;

/*sigmoid function*/
float sigmoid (float x)
{
    return 1/(1 + exp(-x));
}


void setup()
{
  Serial.begin(115200);
  pinMode(B1, INPUT_PULLUP); 
  pinMode(B2, INPUT_PULLUP); 
  pinMode(LED, OUTPUT); 
  digitalWrite(LED, LOW);
}

void loop()
{
  X[0][0] = digitalRead(B1);
  X[0][1] = digitalRead(B2);
  printf("B1 = %d, B2 = %d\n", X[0][0], X[0][1]);
  
  /* calculate forward part based on weights */
  //hidden layer
  for(int i=0; i<1; i++)
  {
      for(int j=0;j <3; j++)
      {
          for(int k=0; k<2; k++)
          {
              sum += X[i][k]*W1[k][j];
          }
          Wo1[i][j] = sigmoid(sum);
          sum = 0;  
      }
  }
  //output layer
  for(int i=0; i<1; i++)
  {
      for(int j=0;j <1; j++)
      {
          for(int k=0; k<3; k++)
          {
              Y += Wo1[i][k]*W2[k][j];
          } 
      }
  }
  printf("Y = %f\n", (Y));
  Y = round(Y);
  digitalWrite(LED, int(Y));
  Y = 0;
  delay(1000);
}
4. Result

Post a Comment

70 Comments

ppf said…
sigmoid derivative function is missing

def sigmoid_deriv(x):
f = sigmoid(x)
return f * (1 - f)

source : https://stackoverflow.com/questions/10626134/derivative-of-sigmoid

Great post.
Very helpfull to start experiments.
Lot of your other posts are also well done.
Thx.
Thank friend,

this is feed forward part so you will not see derivative.
I am wrtting new blog about machine learning.
It is http://www.fossreview.com/
Hope you like it :)
Regards
markson said…
This is significant for clients who need to break down information from alternate points of view and the investigation of one viewpoint prompts business addresses that should be analyzed from different viewpoints. data science course in pune
Manikanta said…
Such a very useful article. Very interesting to read this article. I have learn some new information.thanks for sharing. ExcelR
ravali said…
I am looking for and I love to post a comment that "The content of your post is awesome" Great work!
ExcelR data science
I have to agree with the valid points you make in your article because I see things like you. Additionally, your content is interesting and really good reading material.
SAP training in Kolkata
Best SAP training in Kolkata
SAP training institute in Kolkata
Best said…
With the gradual increase of popularity in social media and other internet platforms, customers, clients is gradually becoming socially interlinked for almost 24*7. From a business point of view, it is an immense opportunity to target the probable customers that surely affect the business outcome and image. digital marketing course in hyderabad
Anirban Ghosh said…
The content that I normally go through in the recent times is nothing like what you have on paper. Thank you for writing this!
The-interface is the perfect solution for SAP training. Interface is one of best SAP training in Kolkata, India. We are providing very prompt and world-class SAP training, SAP training in Kolkata. It is also a renowned SAP training institute in Kolkata.
The Interface is a unique SAP institute in Kolkata, and a SAP training center in Kolkata. It also gives best guidance on SAP through online training and thus,
it is considered as the Best SAP training in Kolkata.You can here directly contact the institute for SAP training in Kolkata and for any information. So keep visiting our websites to get update on regular basis.
EXCELR said…
Attend The data science course in Hyderabad From ExcelR. Practical data science course in Hyderabad Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The data science course in Hyderabad. data science course in Hyderabad
Anonymous said…
very well explained. I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Correlation vs Covariance
Simple Linear Regression
data science interview questions
KNN Algorithm
Logistic Regression explained
Unknown said…
Very interesting to read this article.I would like to thank you for the efforts. I also offer Data Scientist Courses data scientist courses
EXCELR said…
Very interesting to read this article.I would like to thank you for the efforts. I also offer Data Scientist Courses data scientist courses
Morgan said…
When we think of Data, we actually tend to think of 0s and 1s and most the Information Technology industries like social media, e-commerce, the block chain, crypto-technology etc. data science course syllabus
saketh321 said…
very interesting post.this is my first time visit here.i found so many interesting stuff in your blog especially its discussion..thanks for the post! ExcelR Business Analytics Courses
Deekshitha said…
Very informative blog
Join 360digiTMG for the best courses
data science training in Pune
Unknown said…
This material makes for great reading. It's full of useful information that's interesting,well-presented, and easy to understand. I like articles that are well done.
https://socialprachar.com/
Artificial Intelligence Training and Course in Hyderabad
Very informative post and well explain about Machine learning.
Thanks for sharing on IoT, an interesting blog, and well written .Keep making such blogs.

Visit us @

Data Science Training in Pune
Techwriter said…
I recently came across your article and have been reading along. I want to express my admiration of your writing skill and ability to make readers read from the beginning to the end.
Python Classes in Pune

Ramesh Sampangi said…
Nice blog, informative content. I really enjoyed reading this blog. I bookmarked your site for further reads. Keep sharing more.
AI Patasala Data Science Training
360DigiTMG, the top-rated organisation among the most prestigious industries around the world, is an educational destination for those looking to pursue their dreams around the globe. The company is changing careers of many people through constant improvement, 360DigiTMG provides an outstanding learning experience and distinguishes itself from the pack. 360DigiTMG is a prominent global presence by offering world-class training. Its main office is in India and subsidiaries across Malaysia, USA, East Asia, Australia, Uk, Netherlands, and the Middle East.
360digiTMG.com said…
I am always searching online for articles that can help me. There is obviously a lot to know about this. I think you made some good points in Features also. Keep working, great job data analytics course in mysore
Its as if you had a great grasp on the subject matter, but you forgot to include your readers. Perhaps you should think about this from more than one angle. 360DigiTMG data science course in jaipur
data analyst course malaysia said…
Through this post, I realize that your great information in playing with all the pieces was exceptionally useful. I advise this is the primary spot where I discover issues I've been scanning for. You have a smart yet alluring method of composing.data analyst course malaysia
data science course in gorakhpur said…
Nowadays, every company is running its business on the data. That is why data is considered the most crucial factor of any organization.
data science training in gorakhpur
data science course in lucknow said…
People are impressed with this technology, and the experts have predicted a bright future of data science.
data science course in lucknow
data science course in borivali said…
This article will present a closer look at data science courses that give you a comprehensive look at the field. So let's get started.
data science course in borivali
Fast forward your career with the best Data Analyst Course offered by 360DigiTMG. Get trained by expert trainers with placement assistance.


Data Science Course in Delhi
Start your career preparation with the best Data Science courses offered by 360DigiTMG. A world-class curriculum, LMS Access, assignments, and real-time project to grab a high-paying job.

Data Scientist Course in Delhi
If you are aspiring to become a Data Scientist? Then 360DigiTMG is the answer for you. A job-ready curriculum and expert trainers will help you in making your journey easier.

Data Science Course in Bangalore with Placement
Data Science has specific deliverables and objectives that come with it. These deliverables assist in addressing the objectives of fixing the problem at hand.


Data Science Course in Jaipur

Tom said…
Neural networks are amazing
Swarnalatha said…
"If you are also one of them and want to know what the companies demand from the data scientists to do in their organization, you have come to the right place.data science course in kolkata"
deekshitha said…
Data Science course is for smart people. Make the smart choice and reach the apex of your career. data analytics course in dombivli
Swarnalatha said…
Data Analytics is a great field with multiple job opportunities. Start your career right with 360DigiTMG. Enroll today.business analytics course in kolkata
prathyusha said…
Start your Data analytics Course today with 360DigiTMG and be score a high-paying job soon.data analytics training in hyderabad
Rupesh kumar said…
Really an awesome blog and very useful information for me. Ziyyara Edutech’s online English tuition platform offers exceptional spoken English classes designed to cater to learners in Bahrain who are eager to excel in their communication abilities.
For more info visit Spoken english class in bahrain
Rupesh kumar said…
I found so many interesting stuff in your blog especially its discussion. Looking for the best way to enhance your spoken English skills in Kuwait? Look no further than Ziyyara Edutech's exceptional online spoken English classes.
For more info visit Spoken English classes in Kuwait
Gayatri said…
This article showcases a brilliant fusion of machine learning and hardware, demonstrating an Artificial Neural Network system with Arduino ESP32. The meticulous explanation and code snippets make it an excellent resource for tech enthusiasts. Kudos to the author!
Data Analytics Courses in Nashik
Advisor Uncle said…
This is an intriguing project! I like how you used Python and numpy to train the ANN and then implemented it on the ESP32. It's a great method to capitalize on each platform's capabilities. It's simple to follow along thanks to your detailed explanation of the hardware and software components. Thank you for providing this useful information!
Data Analytics Courses in Delhi
TM said…
Impressive work, Tech It Yourself! Your demonstration of a simple Machine Learning Artificial Neural Network using Arduino ESP32 is both informative and hands-on. The way you've explained the concept and provided the code for implementation is clear and helpful. Keep up the fantastic work in the world of tech exploration and innovation! 👏🤖🔌 #TechInnovator
Anonymous said…
This article likely demonstrates a simple machine learning experiment involving an artificial neural network implemented using an Arduino ESP32, showcasing the potential of incorporating machine learning into embedded systems.

Data Analytics Courses In Kochi



Aruna Sen said…
This demo brilliantly showcases the integration of machine learning with Arduino ESP32. The use of Python for training and ESP32 for real-time inference is a commendable example of practical AI applications. Well done.
Data Analytics Courses In Dubai
Advisor Uncle said…
This is so great! I really loved the way you explained the topic of Simple Machine Learning - An artificial neural network demo using Arduino. Waiting for episode 33.
This article demonstrates an Artificial Neural Network system with Arduino ESP32, showcasing a spectacular mix of hardware and machine learning. It's a great resource for computer aficionados because to the thorough explanation and code samples.
Data Analytics Courses in Agra
Pratyaksha said…
Thank you for sharing this artificial neural network demo using Arduino. I appreciate your thought process.
Data Analytics Courses In Chennai

Pratyaksha said…
It's truly inspiring to see the fusion of AI and hardware on such a compact platform. I'm so exited.
Data Analytics Courses In Chennai
Advisor Uncle said…
Your blog is so amazing. I am definitely going to share it with my friends.
Visit - Data Analytics Courses in Delhi
Surabhi said…
An artificial neural network demo using Arduino ESP32 showcases the intersection of hardware and machine learning, providing an exciting platform for embedded AI applications. In the realm of data analytics, Glasgow offers comprehensive Data Analytics courses to equip professionals with the skills to harness AI and machine learning technologies, making informed decisions in the data-driven world. Please also read Data Analytics courses in Glasgow.
This blog is a fantastic resource for anyone interested in combining machine learning with IoT using Arduino ESP32. The demonstration of an artificial neural network is both practical and enlightening. Great work.
Digital marketing courses in illinois
Anonymous said…
Excellent post and I am very happy to read this blog. Keep doing. Struggling to grasp the complexities of Genetics and Heredity? Need guidance on the intricacies of Cell Division and Cell Cycle? Curious about the theory of Evolution and the wonders of Biotechnology and Genetic Engineering?
For more info contact +91-9654271931 or visit Online tuition for cbse board
DA in limerick said…
Thanks for sharing excellent and outstanding demo for simple Machine Learning - Artificial neural network system using Arduino ESP32.
data analyst courses in limerick
"Great post! I appreciate the clear explanation of using Arduino ESP32 for simple machine learning with artificial neural networks. The connection to semolina is intriguing – curious to learn more about how it ties into the project. Looking forward to your next update!"
Best Data analytics courses in India
very well written blog & also well explained video, thanks for sharing.
Digital marketing business

This post provides a clear and detailed demonstration of creating a simple Machine Learning - Artificial neural network system using Arduino ESP32. Well-explained! Thanks for sharing


Digital marketing tips for small businesses

This comprehensive demo brilliantly combines Python, ESP32, and neural networks, showcasing your adeptness in both hardware and software. Your clear explanations and well-organized code make it accessible for enthusiasts. Kudos for sharing such an insightful and practical post

Digital marketing tips for small businesses
Gogou Misao said…
Fantastic post. I admit most of it went over my head, but I'm loving the skills involved. Great share.

Investment banking analyst jobs
jecksmith said…
Integrating machine learning with the power of ESP32 opens up endless possibilities for real-world applications. The simplicity of the demonstration makes it accessible for beginners. I would like to thank you for you to write this awesome article.
Digital marketing courses in city of Westminster

"Your blog on Demo 32 showcasing a simple machine learning artificial neural network with Arduino ESP32 is a fascinating journey into the intersection of hardware and intelligence
Investment banking as a career in India
Rajsingh said…
The clear breakdown of hardware and software setup makes it accessible for enthusiasts at all levels. The neural network design and training insights were especially insightful. great work.
Data analytics framework
seep learn said…
Machine learning on Arduino ESP32 is indeed possible, but there are some considerations and challenges due to the constraints of the ESP32 microcontroller:

Hardware Constraints: The ESP32 has limited processing power (compared to traditional computers or even more powerful microcontrollers like the Raspberry Pi). This limits the complexity of the machine learning models that can be run directly on the ESP32.

Machine Learning Final Year Projects

Image Processing Projects For Final Year Students

python projects for final year students
aditistalk said…
excellent post. keep posting regularly. Full Stack Training In Pune