sensebox/React-Ardublockly

[Blockly][Codegenerator] Add ESP Now

Closed this issue · 1 comments

ESP now is a nice feature to communicate directly between two or more devices.

  • create new Category
  • create sender sketch
  • create receiver sketch

some minimal sketches:

  1. finding mac address
    The sender needs to know the mac address of the receiver.
#include "WiFi.h"

void setup(){
  Serial.begin(115200);
  WiFi.mode(WIFI_MODE_STA);
  Serial.println(WiFi.macAddress());
}
  1. Sender
#include <esp_now.h>
#include <WiFi.h>

uint8_t broadcastAddress[] = {0x84, 0xF7, 0x03, 0xD1, 0x08, 0xA8};

esp_now_peer_info_t peerInfo;
 
void setup() {
  WiFi.mode(WIFI_STA);
  if (esp_now_init() != ESP_OK) {
    return;
  }
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;  
  peerInfo.encrypt = false;
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    return;
  }
}
 
void loop() { 
  esp_err_t result = esp_now_send(broadcastAddress, (const uint8_t*)"test", sizeof("test"));
  delay(2000);
}
  1. Receiver
#include <esp_now.h>
#include <WiFi.h>

void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
  Serial.println((const char*)incomingData);
}
 
void setup() {
  Serial.begin(115200);
  
  WiFi.mode(WIFI_STA);
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }
  esp_now_register_recv_cb(OnDataRecv);
}
 
void loop() {}