ESP8266无法将字符添加到很长的字符串(> 8000个字符) [英] ESP8266 Fails to add char to a very long String (>8000 chars)

查看:284
本文介绍了ESP8266无法将字符添加到很长的字符串(> 8000个字符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从HTTPS请求正确获取有效负载后,将客户端的字符添加到String中后,大约8000个字符后停止,然后恢复并再次停止几次
这是我的代码段:

After correctly getting the payload from an HTTPS request, adding the client's chars to a String stops after about 8000 characters, then resumes and stops again a few times Here's a snippet of my code:

long streamSize = 0;
Serial.println("Now reading payload...");
while (stream.connected()) {
    while (stream.available() > 0) {
        char ch = (char)stream.read();
        Serial.println((String)"Reading [" + ++streamSize + "] " + ch);
        ret += ch;
        Serial.println(ret.length());
    }
}

工作正常,直到:

Reading [8685] t
8685
Reading [8686] r
8686
Reading [8687] u
8687
Reading [8688] m
8687
Reading [8689]  
8687
Reading [8690] e
8687
[Resumes correctly appending chars]
Reading [9226] i
8748
Reading [9227] p
8749
Reading [9228] t
8750
Reading [9229] i
8751
Reading [9230] o
8751
Reading [9231] n
8751

如此多次。
内存堆大小似乎不是问题,因为在附加所有内容后,我从 system_get_free_heap_size()中获得了14128个可用字节。
我正在使用Wemos D1 R1,并且这是我正在尝试的文件完整阅读,进行测试,使用Github API

And so on for quite a few times. Memory Heap size doesn't seem to be the issue, as I'm getting 14128 free bytes from system_get_free_heap_size() after appending everything. I'm using a Wemos D1 R1, and this is the file I'm trying to fully read, for testing, using the Github API

推荐答案

我发现Arduino可能无法由于可用内存量少而将字符串连接起来。而且,Arduino中的String类似乎没有错误处理程序,因此,例如,当内存过于分散时,它可能会默默地失败。

I've found out that Arduino can fail to concatenate strings because of a low amount of free memory. Moreover, String class in Arduino seems not to have an error handler, so it can silently fail when - for example - memory is too fragmented.

请参见此处:来自Arduino论坛
以及此处:来自Stack Overflow中的讨论

许多在某些情况下,他们建议您可以通过 String reserve(int)调用来预分配缓冲区。

In many cases they suggest that you could pre-allocate the buffer with a String reserve(int) call.

也许您事先不知道如何大的字符串将增长,但也许您可以管理它。例如,通过两次调用您的https目标。第一次只是想知道您的答案有多大(这样您就可以分配确切的内存量);第二次有效阅读。

Maybe you could not know in advance how big your string will grow, but maybe you could managing it. For example, by calling two times your https target. First time just to know how big your answer will be (and so you will able to allocate the exact amount of memory); second time to effectively read.

这篇关于ESP8266无法将字符添加到很长的字符串(> 8000个字符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆