You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Arduino发送二维数组至服务器并使用JavaScript接收

Solution: Send 2D MAC Array from Arduino to JavaScript via JSON

Arduino Code Modifications

First, ensure the Arduino_JSON library is installed (required for JSON serialization). Update your code to convert the maclist[64][3] 2D array into a JSON array of objects:

#include <Arduino_JSON.h>

// Assume your 2D array is defined as:
String maclist[64][3]; // [index][0] = Name, [index][1] = addr, [index][2] = ttl

String KnownMacDetails() {
  JSONVar macArray;
  
  // Iterate through all entries in the 2D array
  for (int i = 0; i < 64; i++) {
    // Skip empty entries (adjust condition based on how you mark unused rows)
    if (maclist[i][0].isEmpty()) continue;
    
    // Create a JSON object for each valid device
    JSONVar deviceObj;
    deviceObj["Name"] = maclist[i][0];
    deviceObj["addr"] = maclist[i][1];
    deviceObj["ttl"] = maclist[i][2];
    
    // Add the object to the JSON array
    macArray.push(deviceObj);
  }
  
  // Convert the JSON array to a string
  return JSON.stringify(macArray);
}

Update the Server Endpoint

Your existing server code stays mostly the same—just ensure it calls the updated KnownMacDetails() function:

server.on("/clientsniffer", HTTP_GET, [](AsyncWebServerRequest *request){
    String json = KnownMacDetails();
    request->send(200, "application/json", json);
    json = String(); // Clean up to free memory
});

JavaScript Code to Receive and Process the Data

You can use either the modern fetch API (Promise-based) or XMLHttpRequest to receive the JSON array.

Option 1: Using Fetch (Promise-Based)

Recommended for modern browsers:

async function fetchMacList() {
  try {
    const response = await fetch('/clientsniffer');
    if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
    
    // Parse JSON response into a JavaScript array
    const macDevices = await response.json();
    
    // Process each device in the array
    macDevices.forEach(device => {
      console.log(`Device Name: ${device.Name}, MAC Address: ${device.addr}, TTL: ${device.ttl}`);
      // Add your logic here (e.g., display on webpage, store in a variable)
    });
  } catch (error) {
    console.error('Failed to fetch MAC list:', error);
  }
}

// Call the function to retrieve data
fetchMacList();

Option 2: Using XMLHttpRequest

For compatibility with older browsers:

function getMacList() {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', '/clientsniffer', true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  
  xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 300) {
      // Parse JSON response into an array
      const macDevices = JSON.parse(xhr.responseText);
      
      // Process each device
      macDevices.forEach(device => {
        console.log(`Device Name: ${device.Name}, MAC Address: ${device.addr}, TTL: ${device.ttl}`);
        // Add your display or processing logic here
      });
    } else {
      console.error('Request failed with status:', xhr.status);
    }
  };
  
  xhr.onerror = function() {
    console.error('Network error occurred');
  };
  
  xhr.send();
}

// Trigger the request
getMacList();

Key Notes

  • Empty Entries: The Arduino code skips empty rows by checking if the Name field is empty. Adjust this condition if you use a different marker for unused entries.
  • JSON Structure: The response sent to JavaScript is a JSON array, where each element is an object matching your original single-device data structure.
  • Memory Management: Using push ensures only valid entries are included in the JSON string, reducing memory usage on the Arduino.

内容的提问来源于stack exchange,提问作者Ramesh A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:50:25