使用arduinoJson库将通过http请求获得的数据写入arduino SD卡中的文本文件

时间:2019-06-05 09:48:47

标签: c++ json http arduino

我在arduino中使用http请求从数据库中获取了一些数据。我使用ArduinoJson库提取数据。我成功打印了。我想将此数据写入Arduino的SD卡中。我想将其另存为字符串。我的疑问是如何有效地做到这一点,而不是分配给变量并添加到字符串中。如何直接添加到字符串?有什么建议吗?

void httpRequest(){
  EthernetClient client;
  client.setTimeout(10000);
  if (!client.connect("localhost", 80)) {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("Connected!"));
  // Send HTTP request
  client.println(F("GET /config.json HTTP/1.0"));
  client.println(F("Host: arduinojson.org"));
  client.println(F("Connection: close"));
  if (client.println() == 0) {
    Serial.println(F("Failed to send request"));
    return;
  }

  // Check HTTP status
  char status[32] = {0};
  client.readBytesUntil('\r', status, sizeof(status));
  if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
    Serial.print(F("Unexpected response: "));
    Serial.println(status);
    return;
  }

  // Skip HTTP headers
  char endOfHeaders[] = "\r\n\r\n";
  if (!client.find(endOfHeaders)) {
    Serial.println(F("Invalid response"));
    return;
  }

  // Allocate JsonBuffer
  // Use arduinojson.org/assistant to compute the capacity.
  //const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
const size_t capacity = JSON_OBJECT_SIZE(20) + JSON_ARRAY_SIZE(30) + 60;
  DynamicJsonBuffer jsonBuffer(capacity);

  // Parse JSON object
  JsonObject& root = jsonBuffer.parseObject(client);
  if (!root.success()) {
    Serial.println(F("Parsing failed!"));
    return;
  }
//here i am printing, 
//but i want to write it to a text file.
  Serial.println(F("Response:"));

  Serial.println(root["para1"].as<char*>());
  Serial.println(root["para2"].as<char*>());
  Serial.println(root["para3"].as<char*>());
  Serial.println(root["para4"].as<char*>());
  // Disconnect
  client.stop();  
  }


void WriteParameters()

{

//create the file
  Serial.println("Creating test.txt. . ." );
  myParameterFile = SD.open("test.txt", FILE_WRITE);  //test.txt is the file name to be created and FILE_WRITE is a command to create file.
  myParameterFile.close();  //Closing the file


//If the file was successfully created, 
//we can now write on it.

  myParameterFile = SD.open("test.txt", FILE_WRITE);

//if the file opened okay, write to it:
  if (myParameterFile) {
    Serial.print("Writing to test.txt...");
//how to write my extracted data??? here  
    myParameterFile.println("testing 1, 2, 3.");
    // close the file:
    myParameterFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
  }

0 个答案:

没有答案