3434
3535//  Global copy of slave
3636esp_now_peer_info_t  slave;
37- # define   CHANNEL   1 
38- #define  PRINTSCANRESULTS  0 
39- #define  DELETEBEFOREPAIR  0 
37+ bool  slaveFound; 
38+ #define  PRINT_ALL_SCAN_RESULTS  0 
39+ #define  DELETE_PEER_BEFORE_PAIRING  0 
4040
4141//  Init ESP Now with fallback
4242void  InitESPNow () {
4343  WiFi.disconnect ();
4444  if  (esp_now_init () == ESP_OK) {
4545    Serial.println (" ESPNow Init Success" 
46-   }
47-   else  {
46+   } else  {
4847    Serial.println (" ESPNow Init Failed" 
4948    //  Retry InitESPNow, add a counte and then restart?
5049    //  InitESPNow();
@@ -57,53 +56,59 @@ void InitESPNow() {
5756void  ScanForSlave () {
5857  int8_t  scanResults = WiFi.scanNetworks ();
5958  //  reset on each scan
60-   bool   slaveFound = 0 ;
59+   slaveFound = false ;
6160  memset (&slave, 0 , sizeof (slave));
6261
6362  Serial.println (" " 
6463  if  (scanResults == 0 ) {
6564    Serial.println (" No WiFi devices in AP Mode found" 
6665  } else  {
67-     Serial.print (" Found " print (scanResults); Serial.println ("  devices " 
68-     for  (int  i = 0 ; i < scanResults; ++i) {
69-       //  Print SSID and RSSI for each device found
70-       String SSID = WiFi.SSID (i);
71-       int32_t  RSSI = WiFi.RSSI (i);
72-       String BSSIDstr = WiFi.BSSIDstr (i);
73- 
74-       if  (PRINTSCANRESULTS) {
75-         Serial.print (i + 1 );
66+     if  (PRINT_ALL_SCAN_RESULTS) {
67+       Serial.print (" Found " print (scanResults); Serial.println ("  devices " 
68+       for  (int  i = 0 ; i < scanResults; ++i) {
69+         //  Print SSID and RSSI for each device found
70+         String SSID = WiFi.SSID (i);
71+         int32_t  RSSI = WiFi.RSSI (i);
72+         String BSSIDstr = WiFi.BSSIDstr (i);
73+         Serial.print (i);
7674        Serial.print (" : " 
7775        Serial.print (SSID);
7876        Serial.print ("  (" 
7977        Serial.print (RSSI);
8078        Serial.print (" )" 
8179        Serial.println (" " 
82-       }
83-       delay (10 );
80+       } //  for - loop through scanResults
81+     } //  if PRINT_ALL_SCAN_RESULTS
82+ 
83+     for  (int  i = 0 ; i < scanResults; ++i) {
84+       //  Print SSID and RSSI for each device found
85+       String SSID = WiFi.SSID (i);
86+       int32_t  RSSI = WiFi.RSSI (i);
87+       String BSSIDstr = WiFi.BSSIDstr (i);
88+ 
8489      //  Check if the current device starts with `Slave`
8590      if  (SSID.indexOf (" Slave" 0 ) {
8691        //  SSID of interest
87-         Serial.println (" Found a Slave." 
88-         Serial.print (i + 1 ); Serial.print (" : " print (SSID); Serial.print ("  [" print (BSSIDstr); Serial.print (" ]" print ("  (" print (RSSI); Serial.print (" )" println (" " 
92+         Serial.print (" Found a Slave: " print (i); Serial.print (" : " print (SSID);
93+         Serial.print ("  [" print (BSSIDstr); Serial.print (" ]" 
94+         Serial.print ("  (" print (RSSI); Serial.print (" )" println (" " 
8995        //  Get BSSID => Mac Address of the Slave
90-         int  mac[6 ];
91-         if  ( 6  == sscanf (BSSIDstr.c_str (), " %x:%x:%x:%x:%x:%x" 0 ], &mac[1 ], &mac[2 ], &mac[3 ], &mac[4 ], &mac[5 ] ) ) {
92-           for  (int  ii = 0 ; ii < 6 ; ++ii ) {
93-             slave.peer_addr [ii] = (uint8_t ) mac[ii];
94-           }
96+         uint8_t  mac[6 ];
97+         if  (6  == sscanf (BSSIDstr.c_str (), " %x:%x:%x:%x:%x:%x" 0 ], &mac[1 ], &mac[2 ], &mac[3 ], &mac[4 ], &mac[5 ] ) ) {
98+           Serial.printf (" Adding peer with MAC [%02x:%02x:%02x:%02x:%02x:%02x]\n " 0 ], mac[1 ], mac[2 ], mac[3 ], mac[4 ], mac[5 ]);
99+           memcpy (slave.peer_addr , mac, 6 );
95100        }
96101
97-         slave.channel  = CHANNEL ; //  pick a  channel
98-         slave.encrypt  = 0 ; //  no encryption
102+         slave.channel  = 0 ; //  0 = Use whatever  channel the Slave (AP) is using 
103+         slave.encrypt  = false ; //  no encryption
99104
100-         slaveFound = 1 ;
105+         slaveFound = true ;
101106        //  we are planning to have only one slave in this example;
102107        //  Hence, break after we find one, to be a bit efficient
103108        break ;
104-       }
105-     }
106-   }
109+       }  //  if SSID starts with "Slave" 
110+     }  //  for - loop in scanResults 
111+   }  //  scanResults > 0 
107112
108113  if  (slaveFound) {
109114    Serial.println (" Slave Found, processing.." 
@@ -118,15 +123,14 @@ void ScanForSlave() {
118123//  Check if the slave is already paired with the master.
119124//  If not, pair the slave with master
120125bool  manageSlave () {
121-   if  (slave. channel  == CHANNEL ) {
122-     if  (DELETEBEFOREPAIR ) {
126+   if  (slaveFound ) {
127+     if  (DELETE_PEER_BEFORE_PAIRING ) {
123128      deletePeer ();
124129    }
125130
126131    Serial.print (" Slave Status: " 
127132    //  check if the peer exists
128-     bool  exists = esp_now_is_peer_exist (slave.peer_addr );
129-     if  ( exists) {
133+     if  (esp_now_is_peer_exist (slave.peer_addr )) {
130134      //  Slave already paired.
131135      Serial.println (" Already Paired" 
132136      return  true ;
@@ -140,23 +144,18 @@ bool manageSlave() {
140144      } else  if  (addStatus == ESP_ERR_ESPNOW_NOT_INIT) {
141145        //  How did we get so far!!
142146        Serial.println (" ESPNOW Not Init" 
143-         return  false ;
144147      } else  if  (addStatus == ESP_ERR_ESPNOW_ARG) {
145148        Serial.println (" Invalid Argument" 
146-         return  false ;
147149      } else  if  (addStatus == ESP_ERR_ESPNOW_FULL) {
148150        Serial.println (" Peer list full" 
149-         return  false ;
150151      } else  if  (addStatus == ESP_ERR_ESPNOW_NO_MEM) {
151152        Serial.println (" Out of memory" 
152-         return  false ;
153153      } else  if  (addStatus == ESP_ERR_ESPNOW_EXIST) {
154154        Serial.println (" Peer Exists" 
155-         return  true ;
156155      } else  {
157-         Serial.println (" Not sure what happened" 
158-         return  false ;
156+         Serial.println (" Undefined Error" 
159157      }
158+       return  false ;
160159    }
161160  } else  {
162161    //  No slave found to process
@@ -183,16 +182,19 @@ void deletePeer() {
183182  }
184183}
185184
186- uint8_t  data = 0 ;
187185//  send data
188186void  sendData () {
189-   data++ ;
187+   static   uint8_t   data =  0 ;
190188  const  uint8_t  *peer_addr = slave.peer_addr ;
191-   Serial.print (" Sending: " println (data);
189+   char  peer_addr_str[18 ];
190+   snprintf (peer_addr_str, sizeof (peer_addr_str), " %02x:%02x:%02x:%02x:%02x:%02x" 
191+            peer_addr[0 ], peer_addr[1 ], peer_addr[2 ], peer_addr[3 ], peer_addr[4 ], peer_addr[5 ]);
192+   Serial.print (" Sending: " print (data); Serial.print ("  to addr: " println (peer_addr_str);
192193  esp_err_t  result = esp_now_send (peer_addr, &data, sizeof (data));
193-   Serial.print (" Send Status: " 
194+   Serial.print (" Send Status code=  " ); Serial. print (result); Serial. print ( " : " 
194195  if  (result == ESP_OK) {
195196    Serial.println (" Success" 
197+     data++;
196198  } else  if  (result == ESP_ERR_ESPNOW_NOT_INIT) {
197199    //  How did we get so far!!
198200    Serial.println (" ESPNOW not Init." 
@@ -209,13 +211,13 @@ void sendData() {
209211  }
210212}
211213
212- //  callback  when data is sent from Master to Slave
214+ //  Callback  when data is sent from Master to Slave
213215void  OnDataSent (const  uint8_t  *mac_addr, esp_now_send_status_t  status) {
214216  char  macStr[18 ];
215217  snprintf (macStr, sizeof (macStr), " %02x:%02x:%02x:%02x:%02x:%02x" 
216218           mac_addr[0 ], mac_addr[1 ], mac_addr[2 ], mac_addr[3 ], mac_addr[4 ], mac_addr[5 ]);
217219  Serial.print (" Last Packet Sent to: " println (macStr);
218-   Serial.print (" Last Packet Send Status: " println (status == ESP_NOW_SEND_SUCCESS ? " Delivery Success" " Delivery Fail" 
220+   Serial.print (" Last Packet Send Status code= " ); Serial. print (status); Serial. print ( "   : "    Serial.println (status == ESP_NOW_SEND_SUCCESS ? " Delivery Success" " Delivery Fail" 
219221}
220222
221223void  setup () {
@@ -235,13 +237,10 @@ void setup() {
235237void  loop () {
236238  //  In the loop we scan for slave
237239  ScanForSlave ();
238-   //  If Slave is found, it would be populate in `slave` variable
239-   //  We will check if `slave` is defined and then we proceed further
240-   if  (slave.channel  == CHANNEL) { //  check if slave channel is defined
241-     //  `slave` is defined
240+   //  Check if slave was found
241+   if  (slaveFound) {
242242    //  Add slave as peer if it has not been added already
243-     bool  isPaired = manageSlave ();
244-     if  (isPaired) {
243+     if (manageSlave ()){
245244      //  pair success or already paired
246245      //  Send data to device
247246      sendData ();
@@ -250,10 +249,6 @@ void loop() {
250249      Serial.println (" Slave pair failed!" 
251250    }
252251  }
253-   else  {
254-     //  No slave found to process
255-   }
256- 
257252  //  wait for 3seconds to run the logic again
258253  delay (3000 );
259254}
0 commit comments