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

71 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
This is a wonderful article, Given so much info in it, Thanks for sharing. CodeGnan offers courses in new technologies and makes sure students understand the flow of work from each and every perspective in a Real-Time environmen python training in vijayawada. , data scince training in vijayawada . , java training in vijayawada. ,
priyash said…
wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries. keep it up.
data analytics course in Bangalore
priyash said…
wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries. keep it up.
data analytics course in Bangalore
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
priyash said…
Very interesting to read this article.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
priyash said…
Very interesting to read this article.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
EXCELR said…
Very interesting blog Thank you for sharing such a nice and interesting blog and really very helpful article.
Data Science Course in Hyderabad
Priyanka said…
Attend The Data Analyst Course From ExcelR. Practical Data Analyst Course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analyst Course.
Data Analyst Course
hrithiksai said…
This Was An Amazing ! I Haven't Seen This Type of Blog Ever ! Thankyou For Sharing, data sciecne course in hyderabad
piyasd said…
Amazing Article ! 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.
Simple Linear Regression
Correlation vs covariance
data science interview questions
KNN Algorithm
Logistic Regression explained
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
I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
Data Analytics Courses in Bangalore
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
Maneesha said…
Your amazing insightful information entails much to me and especially to my peers. Thanks a ton; from all of us.
data scientist training and placement
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

Impressive blog to be honest definitely this post will inspire many more upcoming aspirants. Eventually, this makes the participants to experience and innovate themselves through knowledge wise by visiting this kind of a blog. Once again excellent job keep inspiring with your cool stuff.

Data Science Training in Bhilai
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
Unknown said…
Just pure brilliance from you here. I have never expected something less than this from you and you have not disappointed me at all. I suppose you will keep the quality work going on. data science course in mysore
Unknown said…
I really enjoyed reading this post, big fan. Keep up the good work andplease tell me when can you publish more articles or where can I read more on the subject? data science training in mysore
Data Science said…
Amazingly by and large very interesting post. I was looking for such an information and thoroughly enjoyed examining this one. Keep posting.
An obligation of appreciation is all together for sharing.data analytics course in gwalior
Project Management Course said…
Happy to visit your blog, I am by all accounts forward to more solid articles and I figure we as a whole wish to thank such huge numbers of good articles, blog to impart to us.https://360digitmg.com/course/project-management-professional-pmp
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
data analytics course in gorakhpur said…
Unleash your potential and expand your capabilities with the Data Science Certification Course.
data analytics 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…
"Amazing demo! Your use of Arduino ESP32 for implementing a simple neural network is impressive. Thanks for sharing this cool project!"
Data Analytics Courses in Mumbai
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
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.
Learning about machine brains with Arduino sounds mind-boggling! Can't wait to try this neural network demo on my ESP32. Thanks for sharing this cool project!
Data Analytics Courses in Canada