ハロー ブログ

日々のつぶやき @c2c2c2c221

ESP-NOWの双方向通信のサンプルプログラム 

ESP-NOWは双方向通信が可能です。双方向通信を実現するためには、送信側と受信側の両方にESP-NOWライブラリをインストールし、双方向通信を実現するためのスケッチを書く必要があります。

双方向通信を行うためには、一方のESPデバイスがデータを送信し、もう一方のESPデバイスがそのデータを受信し、応答を返すことが必要です。このため、受信側のESPデバイスも、送信側のESPデバイスと同様に、データを送信することができます。送信側と受信側が同時に送信し合うと、競合が発生する可能性があるため、適切な競合回避機能を実装する必要があります。

双方向通信を実現するための具体的なスケッチの書き方については、ESP-NOWライブラリの公式ドキュメントを参照することをお勧めします。

競合回避するサンプルプログラムを教えてください 以下は、ESP-NOWを使用して双方向通信を行う場合の競合回避を実現するためのサンプルプログラムです。このプログラムは、送信側と受信側が同時にデータを送信しようとした場合に、競合が発生することを避けるために、送信側が受信側の応答を待つ方法を使用しています。

#include <esp_now.h>
#include <WiFi.h>

// Replace with your own MAC addresses

// Define a variable to store the message to be sent
String message = "";

// Define a variable to store the message received from the partner
String receivedMessage = "";

// Define a variable to store the timestamp of the last message sent
unsigned long lastSentTime = 0;

// Define a variable to store the minimum interval between messages (in milliseconds)
const unsigned long MESSAGE_INTERVAL = 1000;

// Define a variable to store the timeout period for waiting for a response (in milliseconds)
const unsigned long RESPONSE_TIMEOUT = 100;

// Define a variable to store whether a response has been received from the partner
bool responseReceived = false;

// Define a callback function to handle incoming messages
void onDataReceived(const uint8_t *senderMac, const uint8_t *data, int len) {
  // Convert the incoming message to a string
  String receivedMessage = "";
  for (int i = 0; i < len; i++) {
    receivedMessage += (char)data[i];
  }
  
  // Print the received message
  Serial.print("Received message: ");
  Serial.println(receivedMessage);
  
  // Set the responseReceived flag to true
  responseReceived = true;
}

void setup() {
  // Initialize serial communication
  Serial.begin(9600);

  // Initialize WiFi
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();

  // Initialize ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }
  
  // Register the callback function to handle incoming messages
  esp_now_register_recv_cb(onDataReceived);
  
  // Add the broadcast address to the peer list
  esp_now_peer_info_t broadcastPeer;
  memset(&broadcastPeer, 0, sizeof(broadcastPeer));
  broadcastPeer.channel = 0;
  broadcastPeer.encrypt = false;
  memcpy(broadcastPeer.peer_addr, broadcastAddress, 6);
  esp_now_add_peer(&broadcastPeer);
  
  // Add the partner address to the peer list
  esp_now_peer_info_t partnerPeer;
  memset(&partnerPeer, 0, sizeof(partnerPeer));
  partnerPeer.channel = 0;
  partnerPeer.encrypt = false;
  memcpy(partnerPeer.peer_addr, partnerAddress, 6);
  esp_now_add_peer(&partnerPeer);
}

void loop() {
  // Check if it's time to send a message
  if (millis() - lastSentTime >= MESSAGE_INTERVAL) {
    // Reset the responseReceived flag
    responseReceived = false;
    
    // Generate a random message
    message = "Hello from ESP-NOW! " + String(random(100));
// Convert the message to a byte array
uint8_t messageBytes[message.length() + 1];
message.getBytes(messageBytes, message.length() + 1);

// Send the message to the partner
esp_err_t result = esp_now_send(partnerAddress, messageBytes, message.length() + 1);

// Check if the message was sent successfully
if (result == ESP_OK) {
  Serial.print("Sent message: ");
  Serial.println(message);
}
else {
  Serial.println("Error sending message");
}

// Record the timestamp of the message sent
lastSentTime = millis();