解决esp32同时使用wifi、蓝牙内存不足的情况(基于Arduino框架)

        esp32同时使用wifi和蓝牙时,通过编译会发现内存不够。

如编译如下程序:

#include <Arduino.h>
#include "WiFi.h"
#include <BluetoothSerial.h>

const char *ssid="Xiaomi_6A31";
const char *password="12503811";

BluetoothSerial SerialBT;
BaseType_t xreturn=NULL;
QueueHandle_t xQueue=NULL;

//连接wifi
void WiFi_Connect()
{
   // WiFi.softAPConfig(local_IP,gateway,subnet);
   // WiFi.mode(WIFI_STA);
	WiFi.begin(ssid, password); //要连接的wifi和密码
	while (WiFi.status() != WL_CONNECTED)
	{ //这里是阻塞程序,直到连接成功
		delay(300);
		Serial.print(".");
	}
  Serial.println("WiFi connected");
	Serial.println("IP address: "); // 打印本地ip地址
	Serial.println(WiFi.localIP());
}

void vBT_task(void *arg){
  uint8_t i=0;
    for(;;){
    if(SerialBT.available()){//蓝牙接收到消息
    i=(uint8_t)SerialBT.read();
    xQueueSend(xQueue,&i,0);
    printf("i=%d\r\n",i);
    }
    vTaskDelay(10);
    }
}

void vLED_task(void *arg){
  uint8_t i=0;
    for(;;){
    xQueueReceive(xQueue,&i,portMAX_DELAY);
    if(i==0)   digitalWrite(2,LOW);
    else if(i==1)   digitalWrite(2,HIGH);
    }
}



void setup() {
  // put your setup code here, to run once:
  pinMode(2,OUTPUT);
  digitalWrite(2,LOW);
  Serial.begin(115200);
  WiFi_Connect();
  xQueue=xQueueCreate(1,sizeof(uint8_t));//创建队列:长度1,数据大小为1字节
  SerialBT.begin("sense_long");//蓝牙设备名
  SerialBT.setPin("1234");   // 蓝牙连接的配对码
  Serial.println("The device started, now you can pair it with bluetooth!");
  xreturn=xTaskCreatePinnedToCore(vBT_task,"bluetooth",2048,NULL,1,NULL,0);
  if(xreturn!=NULL) printf("BT Task create success!\r\n");
  else              printf("BT Task create failed!\r\n");
  xreturn=xTaskCreatePinnedToCore(vLED_task,"LED",2048,NULL,2,NULL,1);
  if(xreturn!=NULL) printf("LED Task create success!\r\n");
  else              printf("LED Task create failed!\r\n");

}


void loop() {
    //delay(10);
}

编译结果:

        该程序需要1404165bytes内存(1404165/1024/1024=1.34mb),但是可用内存只有1310720bytes(1310720/1024/1024=1.25mb),显然内存是不够的, 但是我们使用的esp-wroom-32的flash总共有4mb,那我们有没有办法增加用来存储程序的内存呢?答案是肯定的。

        esp32内存中有一张分区表,将内存划分成几个不同的区域,用于存储不同的内容,我们只需要对这一张分区表进行修改就能实现我们的目的。

       根据路径 C:\Users\pc\.platformio\packages\framework-arduinoespressif32\tools\partitions,打开partitions文件,里面有很多excel表格,这些就是esp32的分区表(在下载platformio时自动下载的)。

         其中default.csv就是默认的分区表,我们将其打开。

 这里用于存储程序的内存大小为0x140000=1310720bytes,与目前编译环境下的内存相同。

 现在我们采用现存的另一分区表huge_app.csv,我们将其打开。

 表中用于存储程序的内存为0x300000=3145728bytes。

为了使用该分区表,我们打开paltformio.ini,在其中输入以下命令。

         其中命令monitor_speed=115200是用于修改波特率的,命令upload_speed=921600是用于修改下载速度的,大家可以根据需要使用,修改完成后我们进行编译。

         此时内存变为我们刚才计算的数值3145728bytes(3145728/1024/1024=3mb),此时内存已经绰绰有余了。

        当然我们也可以根据自己的需要来修改分区表,复制一张默认分区表default.csv到工程文件中。

        将其文件名修改为mymenset.csv,在此处,我对该分区表进行了如下修改(大家可以根据需要自行修改):

        此时内存应为0x180000=1572864bytes,我们再在platformio.ini中进行对应修改。

 编译结果如下:

 

物联沃分享整理
物联沃-IOTWORD物联网 » 解决esp32同时使用wifi、蓝牙内存不足的情况(基于Arduino框架)

发表评论