2017-05-27 66 views
0

我正在尝试为打印类打印数据的重定向库。我不幸被困在错误读取Arduino:重写打印类问题

error: cannot declare variable 'diagData' to be of abstract type 'PrintToString'

note: because the following virtual functions are pure within 'PrintToString'

note: virtual size_t PrintToString::write(uint8_t)

我想如何实现这一点,但没有运气几个变化。 (从互联网来源)


链接

打印类:github.com/ Print.hPrint.cpp

我的代码

PrintToString.h

#ifndef PRINT_TO_STRING_H 

    #define PRINT_TO_STRING_H 

    #include <Arduino.h> 


    class PrintToString : public Print 
    { 
     private: 
      String* data; 

     public: 
      PrintToString(); 
      ~PrintToString(); 

      String* results(); 
      void clear(); 

      size_t write(uint8_t) = 0; 
      size_t write(const uint8_t* buffer, size_t size); 
    }; 

#endif 

PrintToString.cpp

#include "PrintToString.h" 



PrintToString::PrintToString() 
{ 
    data = new String(); 
} 

PrintToString::~PrintToString() 
{ 
    delete data; 
    data = NULL; 
} 


String* PrintToString::results() 
{ 
    return data; 
} 

void PrintToString::clear() 
{ 
    delete data; 
    data = new String(); 
} 


size_t PrintToString::write(const uint8_t* buffer, size_t size) 
{ 
    size_t n = 0; 

    while (size--) 
    { 
     if (data->concat(*buffer++)) 
      n++; 
     else 
      break; 
    } 

    return n; 
} 

TestSketch.ino(我已经离开了所有的常量的内容)

#include <ESP8266WiFi.h> 
#include <PrintToString.h> 

const char* WIFI_SSID 
const char* WIFI_PASS 

const char* API_HOST 
const uint16_t API_PORT 
const uint16_t LOCAL_UDP_PORT 

WiFiUDP UDPClint; 
PrintToString diagData; 
uint64_t packetNumber = 0; 

void setup() 
{ 
    WiFi.begin(WIFI_SSID, WIFI_PASS); 
    UDPClint.begin(LOCAL_UDP_PORT); 

    while (WiFi.status() != WL_CONNECTED) 
     delay(500); 

    WiFi.printDiag(diagData); 
    sendStringPacket(diagData.result()); 
    diagData.clear(); 
} 

void loop() 
{ 
    delay(1000); 
} 

void sendStringPacket(String payload) 
{ 
    UDPClint.beginPacket(API_HOST, API_PORT); 


    uint64_t thisPNumber = packetNumber++; 
    String thisPNumberStr; 

    while (thisPNumber > 0) 
    { 
     uint8_t digit = thisPNumber % 10; 
     thisPNumberStr.concat(digit); 

     thisPNumber /= 10; 
    } 

    UDPClint.write(';'); 

    for (uint64_t i = 0; i < payload.length(); i++) 
     UDPClint.write(payload.charAt(i)); 

    UDPClint.endPacket(); 
} 
+2

你可以上传你的Arduino Sketch吗?顺便说一句,你对'String * data'的内存管理有严重的错误。您应该首先删除'data',并在'〜PrintToString()'中将其设置为空。在clear()中获得一个新字符串之前,你应该首先'删除'。否则,这个类会在几分钟内让您的Arduino崩溃。 –

+0

感谢您提供内存管理建议我非常喜欢它。草图很短,所以我已经包括它来回答。 – PSSGCSim

回答

1

这是因为这个类有一个pure virtual function这里:

size_t write(uint8_t) = 0;

具有纯虚函数的类不能实例化。所以方法write(uint8_t)必须以某种方式在你的代码中实现。

编辑:考虑利用您在sendStringPacket()中使用的代码write(uint8_t)。您可以在不使用sendStringPacket(diagData.result());语句的情况下重定向输出。